Bug Summary

File:lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Warning:line 15644, column 1
Potential leak of memory pointed to by 'N0UsedElements.X'

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 DAGCombiner.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/lib/CodeGen/SelectionDAG -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp

/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp

1//===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
12//
13// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/AliasAnalysis.h"
33#include "llvm/Analysis/MemoryLocation.h"
34#include "llvm/CodeGen/DAGCombine.h"
35#include "llvm/CodeGen/ISDOpcodes.h"
36#include "llvm/CodeGen/MachineFrameInfo.h"
37#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineMemOperand.h"
39#include "llvm/CodeGen/MachineValueType.h"
40#include "llvm/CodeGen/RuntimeLibcalls.h"
41#include "llvm/CodeGen/SelectionDAG.h"
42#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
44#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
45#include "llvm/CodeGen/TargetLowering.h"
46#include "llvm/CodeGen/TargetRegisterInfo.h"
47#include "llvm/CodeGen/TargetSubtargetInfo.h"
48#include "llvm/CodeGen/ValueTypes.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/Constant.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/DerivedTypes.h"
53#include "llvm/IR/Function.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/CodeGen.h"
58#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Compiler.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/KnownBits.h"
63#include "llvm/Support/MathExtras.h"
64#include "llvm/Support/raw_ostream.h"
65#include "llvm/Target/TargetMachine.h"
66#include "llvm/Target/TargetOptions.h"
67#include <algorithm>
68#include <cassert>
69#include <cstdint>
70#include <functional>
71#include <iterator>
72#include <string>
73#include <tuple>
74#include <utility>
75#include <vector>
76
77using namespace llvm;
78
79#define DEBUG_TYPE"dagcombine" "dagcombine"
80
81STATISTIC(NodesCombined , "Number of dag nodes combined")static llvm::Statistic NodesCombined = {"dagcombine", "NodesCombined"
, "Number of dag nodes combined", {0}, {false}}
;
82STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created")static llvm::Statistic PreIndexedNodes = {"dagcombine", "PreIndexedNodes"
, "Number of pre-indexed nodes created", {0}, {false}}
;
83STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created")static llvm::Statistic PostIndexedNodes = {"dagcombine", "PostIndexedNodes"
, "Number of post-indexed nodes created", {0}, {false}}
;
84STATISTIC(OpsNarrowed , "Number of load/op/store narrowed")static llvm::Statistic OpsNarrowed = {"dagcombine", "OpsNarrowed"
, "Number of load/op/store narrowed", {0}, {false}}
;
85STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int")static llvm::Statistic LdStFP2Int = {"dagcombine", "LdStFP2Int"
, "Number of fp load/store pairs transformed to int", {0}, {false
}}
;
86STATISTIC(SlicedLoads, "Number of load sliced")static llvm::Statistic SlicedLoads = {"dagcombine", "SlicedLoads"
, "Number of load sliced", {0}, {false}}
;
87
88static cl::opt<bool>
89CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
90 cl::desc("Enable DAG combiner's use of IR alias analysis"));
91
92static cl::opt<bool>
93UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
94 cl::desc("Enable DAG combiner's use of TBAA"));
95
96#ifndef NDEBUG
97static cl::opt<std::string>
98CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
99 cl::desc("Only use DAG-combiner alias analysis in this"
100 " function"));
101#endif
102
103/// Hidden option to stress test load slicing, i.e., when this option
104/// is enabled, load slicing bypasses most of its profitability guards.
105static cl::opt<bool>
106StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
107 cl::desc("Bypass the profitability model of load slicing"),
108 cl::init(false));
109
110static cl::opt<bool>
111 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
112 cl::desc("DAG combiner may split indexing from loads"));
113
114namespace {
115
116 class DAGCombiner {
117 SelectionDAG &DAG;
118 const TargetLowering &TLI;
119 CombineLevel Level;
120 CodeGenOpt::Level OptLevel;
121 bool LegalOperations = false;
122 bool LegalTypes = false;
123 bool ForCodeSize;
124
125 /// \brief Worklist of all of the nodes that need to be simplified.
126 ///
127 /// This must behave as a stack -- new nodes to process are pushed onto the
128 /// back and when processing we pop off of the back.
129 ///
130 /// The worklist will not contain duplicates but may contain null entries
131 /// due to nodes being deleted from the underlying DAG.
132 SmallVector<SDNode *, 64> Worklist;
133
134 /// \brief Mapping from an SDNode to its position on the worklist.
135 ///
136 /// This is used to find and remove nodes from the worklist (by nulling
137 /// them) when they are deleted from the underlying DAG. It relies on
138 /// stable indices of nodes within the worklist.
139 DenseMap<SDNode *, unsigned> WorklistMap;
140
141 /// \brief Set of nodes which have been combined (at least once).
142 ///
143 /// This is used to allow us to reliably add any operands of a DAG node
144 /// which have not yet been combined to the worklist.
145 SmallPtrSet<SDNode *, 32> CombinedNodes;
146
147 // AA - Used for DAG load/store alias analysis.
148 AliasAnalysis *AA;
149
150 /// When an instruction is simplified, add all users of the instruction to
151 /// the work lists because they might get more simplified now.
152 void AddUsersToWorklist(SDNode *N) {
153 for (SDNode *Node : N->uses())
154 AddToWorklist(Node);
155 }
156
157 /// Call the node-specific routine that folds each particular type of node.
158 SDValue visit(SDNode *N);
159
160 public:
161 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
162 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
163 OptLevel(OL), AA(AA) {
164 ForCodeSize = DAG.getMachineFunction().getFunction().optForSize();
165
166 MaximumLegalStoreInBits = 0;
167 for (MVT VT : MVT::all_valuetypes())
168 if (EVT(VT).isSimple() && VT != MVT::Other &&
169 TLI.isTypeLegal(EVT(VT)) &&
170 VT.getSizeInBits() >= MaximumLegalStoreInBits)
171 MaximumLegalStoreInBits = VT.getSizeInBits();
172 }
173
174 /// Add to the worklist making sure its instance is at the back (next to be
175 /// processed.)
176 void AddToWorklist(SDNode *N) {
177 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Deleted Node added to Worklist") ? void (0) : __assert_fail
("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
178 "Deleted Node added to Worklist")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Deleted Node added to Worklist") ? void (0) : __assert_fail
("N->getOpcode() != ISD::DELETED_NODE && \"Deleted Node added to Worklist\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
;
179
180 // Skip handle nodes as they can't usefully be combined and confuse the
181 // zero-use deletion strategy.
182 if (N->getOpcode() == ISD::HANDLENODE)
183 return;
184
185 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
186 Worklist.push_back(N);
187 }
188
189 /// Remove all instances of N from the worklist.
190 void removeFromWorklist(SDNode *N) {
191 CombinedNodes.erase(N);
192
193 auto It = WorklistMap.find(N);
194 if (It == WorklistMap.end())
195 return; // Not in the worklist.
196
197 // Null out the entry rather than erasing it to avoid a linear operation.
198 Worklist[It->second] = nullptr;
199 WorklistMap.erase(It);
200 }
201
202 void deleteAndRecombine(SDNode *N);
203 bool recursivelyDeleteUnusedNodes(SDNode *N);
204
205 /// Replaces all uses of the results of one DAG node with new values.
206 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
207 bool AddTo = true);
208
209 /// Replaces all uses of the results of one DAG node with new values.
210 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
211 return CombineTo(N, &Res, 1, AddTo);
212 }
213
214 /// Replaces all uses of the results of one DAG node with new values.
215 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
216 bool AddTo = true) {
217 SDValue To[] = { Res0, Res1 };
218 return CombineTo(N, To, 2, AddTo);
219 }
220
221 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
222
223 private:
224 unsigned MaximumLegalStoreInBits;
225
226 /// Check the specified integer node value to see if it can be simplified or
227 /// if things it uses can be simplified by bit propagation.
228 /// If so, return true.
229 bool SimplifyDemandedBits(SDValue Op) {
230 unsigned BitWidth = Op.getScalarValueSizeInBits();
231 APInt Demanded = APInt::getAllOnesValue(BitWidth);
232 return SimplifyDemandedBits(Op, Demanded);
233 }
234
235 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
236
237 bool CombineToPreIndexedLoadStore(SDNode *N);
238 bool CombineToPostIndexedLoadStore(SDNode *N);
239 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
240 bool SliceUpLoad(SDNode *N);
241
242 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
243 /// load.
244 ///
245 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
246 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
247 /// \param EltNo index of the vector element to load.
248 /// \param OriginalLoad load that EVE came from to be replaced.
249 /// \returns EVE on success SDValue() on failure.
250 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
251 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
252 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
253 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
254 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
255 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
256 SDValue PromoteIntBinOp(SDValue Op);
257 SDValue PromoteIntShiftOp(SDValue Op);
258 SDValue PromoteExtend(SDValue Op);
259 bool PromoteLoad(SDValue Op);
260
261 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
262 SDValue OrigLoad, SDValue ExtLoad,
263 const SDLoc &DL,
264 ISD::NodeType ExtType);
265
266 /// Call the node-specific routine that knows how to fold each
267 /// particular type of node. If that doesn't do anything, try the
268 /// target-specific DAG combines.
269 SDValue combine(SDNode *N);
270
271 // Visitation implementation - Implement dag node combining for different
272 // node types. The semantics are as follows:
273 // Return Value:
274 // SDValue.getNode() == 0 - No change was made
275 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
276 // otherwise - N should be replaced by the returned Operand.
277 //
278 SDValue visitTokenFactor(SDNode *N);
279 SDValue visitMERGE_VALUES(SDNode *N);
280 SDValue visitADD(SDNode *N);
281 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
282 SDValue visitSUB(SDNode *N);
283 SDValue visitADDC(SDNode *N);
284 SDValue visitUADDO(SDNode *N);
285 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
286 SDValue visitSUBC(SDNode *N);
287 SDValue visitUSUBO(SDNode *N);
288 SDValue visitADDE(SDNode *N);
289 SDValue visitADDCARRY(SDNode *N);
290 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
291 SDValue visitSUBE(SDNode *N);
292 SDValue visitSUBCARRY(SDNode *N);
293 SDValue visitMUL(SDNode *N);
294 SDValue useDivRem(SDNode *N);
295 SDValue visitSDIV(SDNode *N);
296 SDValue visitUDIV(SDNode *N);
297 SDValue visitREM(SDNode *N);
298 SDValue visitMULHU(SDNode *N);
299 SDValue visitMULHS(SDNode *N);
300 SDValue visitSMUL_LOHI(SDNode *N);
301 SDValue visitUMUL_LOHI(SDNode *N);
302 SDValue visitSMULO(SDNode *N);
303 SDValue visitUMULO(SDNode *N);
304 SDValue visitIMINMAX(SDNode *N);
305 SDValue visitAND(SDNode *N);
306 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
307 SDValue visitOR(SDNode *N);
308 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
309 SDValue visitXOR(SDNode *N);
310 SDValue SimplifyVBinOp(SDNode *N);
311 SDValue visitSHL(SDNode *N);
312 SDValue visitSRA(SDNode *N);
313 SDValue visitSRL(SDNode *N);
314 SDValue visitRotate(SDNode *N);
315 SDValue visitABS(SDNode *N);
316 SDValue visitBSWAP(SDNode *N);
317 SDValue visitBITREVERSE(SDNode *N);
318 SDValue visitCTLZ(SDNode *N);
319 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
320 SDValue visitCTTZ(SDNode *N);
321 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
322 SDValue visitCTPOP(SDNode *N);
323 SDValue visitSELECT(SDNode *N);
324 SDValue visitVSELECT(SDNode *N);
325 SDValue visitSELECT_CC(SDNode *N);
326 SDValue visitSETCC(SDNode *N);
327 SDValue visitSETCCE(SDNode *N);
328 SDValue visitSETCCCARRY(SDNode *N);
329 SDValue visitSIGN_EXTEND(SDNode *N);
330 SDValue visitZERO_EXTEND(SDNode *N);
331 SDValue visitANY_EXTEND(SDNode *N);
332 SDValue visitAssertExt(SDNode *N);
333 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
334 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
335 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
336 SDValue visitTRUNCATE(SDNode *N);
337 SDValue visitBITCAST(SDNode *N);
338 SDValue visitBUILD_PAIR(SDNode *N);
339 SDValue visitFADD(SDNode *N);
340 SDValue visitFSUB(SDNode *N);
341 SDValue visitFMUL(SDNode *N);
342 SDValue visitFMA(SDNode *N);
343 SDValue visitFDIV(SDNode *N);
344 SDValue visitFREM(SDNode *N);
345 SDValue visitFSQRT(SDNode *N);
346 SDValue visitFCOPYSIGN(SDNode *N);
347 SDValue visitSINT_TO_FP(SDNode *N);
348 SDValue visitUINT_TO_FP(SDNode *N);
349 SDValue visitFP_TO_SINT(SDNode *N);
350 SDValue visitFP_TO_UINT(SDNode *N);
351 SDValue visitFP_ROUND(SDNode *N);
352 SDValue visitFP_ROUND_INREG(SDNode *N);
353 SDValue visitFP_EXTEND(SDNode *N);
354 SDValue visitFNEG(SDNode *N);
355 SDValue visitFABS(SDNode *N);
356 SDValue visitFCEIL(SDNode *N);
357 SDValue visitFTRUNC(SDNode *N);
358 SDValue visitFFLOOR(SDNode *N);
359 SDValue visitFMINNUM(SDNode *N);
360 SDValue visitFMAXNUM(SDNode *N);
361 SDValue visitBRCOND(SDNode *N);
362 SDValue visitBR_CC(SDNode *N);
363 SDValue visitLOAD(SDNode *N);
364
365 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
366 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
367
368 SDValue visitSTORE(SDNode *N);
369 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
370 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
371 SDValue visitBUILD_VECTOR(SDNode *N);
372 SDValue visitCONCAT_VECTORS(SDNode *N);
373 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
374 SDValue visitVECTOR_SHUFFLE(SDNode *N);
375 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
376 SDValue visitINSERT_SUBVECTOR(SDNode *N);
377 SDValue visitMLOAD(SDNode *N);
378 SDValue visitMSTORE(SDNode *N);
379 SDValue visitMGATHER(SDNode *N);
380 SDValue visitMSCATTER(SDNode *N);
381 SDValue visitFP_TO_FP16(SDNode *N);
382 SDValue visitFP16_TO_FP(SDNode *N);
383
384 SDValue visitFADDForFMACombine(SDNode *N);
385 SDValue visitFSUBForFMACombine(SDNode *N);
386 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
387
388 SDValue XformToShuffleWithZero(SDNode *N);
389 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
390 SDValue RHS);
391
392 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
393
394 SDValue foldSelectOfConstants(SDNode *N);
395 SDValue foldVSelectOfConstants(SDNode *N);
396 SDValue foldBinOpIntoSelect(SDNode *BO);
397 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
398 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
399 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
400 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
401 SDValue N2, SDValue N3, ISD::CondCode CC,
402 bool NotExtCompare = false);
403 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
404 SDValue N2, SDValue N3, ISD::CondCode CC);
405 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
406 const SDLoc &DL);
407 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
408 const SDLoc &DL, bool foldBooleans = true);
409
410 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
411 SDValue &CC) const;
412 bool isOneUseSetCC(SDValue N) const;
413
414 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
415 unsigned HiOp);
416 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
417 SDValue CombineExtLoad(SDNode *N);
418 SDValue combineRepeatedFPDivisors(SDNode *N);
419 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
420 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
421 SDValue BuildSDIV(SDNode *N);
422 SDValue BuildSDIVPow2(SDNode *N);
423 SDValue BuildUDIV(SDNode *N);
424 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
425 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
426 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
427 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
428 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
429 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
430 SDNodeFlags Flags, bool Reciprocal);
431 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
432 SDNodeFlags Flags, bool Reciprocal);
433 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
434 bool DemandHighBits = true);
435 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
436 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
437 SDValue InnerPos, SDValue InnerNeg,
438 unsigned PosOpcode, unsigned NegOpcode,
439 const SDLoc &DL);
440 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
441 SDValue MatchLoadCombine(SDNode *N);
442 SDValue ReduceLoadWidth(SDNode *N);
443 SDValue ReduceLoadOpStoreWidth(SDNode *N);
444 SDValue splitMergedValStore(StoreSDNode *ST);
445 SDValue TransformFPLoadStorePair(SDNode *N);
446 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
447 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
448 SDValue reduceBuildVecToShuffle(SDNode *N);
449 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
450 ArrayRef<int> VectorMask, SDValue VecIn1,
451 SDValue VecIn2, unsigned LeftIdx);
452 SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
453
454 /// Walk up chain skipping non-aliasing memory nodes,
455 /// looking for aliasing nodes and adding them to the Aliases vector.
456 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
457 SmallVectorImpl<SDValue> &Aliases);
458
459 /// Return true if there is any possibility that the two addresses overlap.
460 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
461
462 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
463 /// chain (aliasing node.)
464 SDValue FindBetterChain(SDNode *N, SDValue Chain);
465
466 /// Try to replace a store and any possibly adjacent stores on
467 /// consecutive chains with better chains. Return true only if St is
468 /// replaced.
469 ///
470 /// Notice that other chains may still be replaced even if the function
471 /// returns false.
472 bool findBetterNeighborChains(StoreSDNode *St);
473
474 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
475 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
476
477 /// Holds a pointer to an LSBaseSDNode as well as information on where it
478 /// is located in a sequence of memory operations connected by a chain.
479 struct MemOpLink {
480 // Ptr to the mem node.
481 LSBaseSDNode *MemNode;
482
483 // Offset from the base ptr.
484 int64_t OffsetFromBase;
485
486 MemOpLink(LSBaseSDNode *N, int64_t Offset)
487 : MemNode(N), OffsetFromBase(Offset) {}
488 };
489
490 /// This is a helper function for visitMUL to check the profitability
491 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
492 /// MulNode is the original multiply, AddNode is (add x, c1),
493 /// and ConstNode is c2.
494 bool isMulAddWithConstProfitable(SDNode *MulNode,
495 SDValue &AddNode,
496 SDValue &ConstNode);
497
498 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
499 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
500 /// the type of the loaded value to be extended.
501 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
502 EVT LoadResultTy, EVT &ExtVT);
503
504 /// Helper function to calculate whether the given Load can have its
505 /// width reduced to ExtVT.
506 bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
507 EVT &ExtVT, unsigned ShAmt = 0);
508
509 /// Used by BackwardsPropagateMask to find suitable loads.
510 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
511 SmallPtrSetImpl<SDNode*> &NodeWithConsts,
512 ConstantSDNode *Mask, SDNode *&UncombinedNode);
513 /// Attempt to propagate a given AND node back to load leaves so that they
514 /// can be combined into narrow loads.
515 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
516
517 /// Helper function for MergeConsecutiveStores which merges the
518 /// component store chains.
519 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
520 unsigned NumStores);
521
522 /// This is a helper function for MergeConsecutiveStores. When the
523 /// source elements of the consecutive stores are all constants or
524 /// all extracted vector elements, try to merge them into one
525 /// larger store introducing bitcasts if necessary. \return True
526 /// if a merged store was created.
527 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
528 EVT MemVT, unsigned NumStores,
529 bool IsConstantSrc, bool UseVector,
530 bool UseTrunc);
531
532 /// This is a helper function for MergeConsecutiveStores. Stores
533 /// that potentially may be merged with St are placed in
534 /// StoreNodes.
535 void getStoreMergeCandidates(StoreSDNode *St,
536 SmallVectorImpl<MemOpLink> &StoreNodes);
537
538 /// Helper function for MergeConsecutiveStores. Checks if
539 /// candidate stores have indirect dependency through their
540 /// operands. \return True if safe to merge.
541 bool checkMergeStoreCandidatesForDependencies(
542 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
543
544 /// Merge consecutive store operations into a wide store.
545 /// This optimization uses wide integers or vectors when possible.
546 /// \return number of stores that were merged into a merged store (the
547 /// affected nodes are stored as a prefix in \p StoreNodes).
548 bool MergeConsecutiveStores(StoreSDNode *N);
549
550 /// \brief Try to transform a truncation where C is a constant:
551 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
552 ///
553 /// \p N needs to be a truncation and its first operand an AND. Other
554 /// requirements are checked by the function (e.g. that trunc is
555 /// single-use) and if missed an empty SDValue is returned.
556 SDValue distributeTruncateThroughAnd(SDNode *N);
557
558 public:
559 /// Runs the dag combiner on all nodes in the work list
560 void Run(CombineLevel AtLevel);
561
562 SelectionDAG &getDAG() const { return DAG; }
563
564 /// Returns a type large enough to hold any valid shift amount - before type
565 /// legalization these can be huge.
566 EVT getShiftAmountTy(EVT LHSTy) {
567 assert(LHSTy.isInteger() && "Shift amount is not an integer type!")(static_cast <bool> (LHSTy.isInteger() && "Shift amount is not an integer type!"
) ? void (0) : __assert_fail ("LHSTy.isInteger() && \"Shift amount is not an integer type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568 if (LHSTy.isVector())
569 return LHSTy;
570 auto &DL = DAG.getDataLayout();
571 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
572 : TLI.getPointerTy(DL);
573 }
574
575 /// This method returns true if we are running before type legalization or
576 /// if the specified VT is legal.
577 bool isTypeLegal(const EVT &VT) {
578 if (!LegalTypes) return true;
579 return TLI.isTypeLegal(VT);
580 }
581
582 /// Convenience wrapper around TargetLowering::getSetCCResultType
583 EVT getSetCCResultType(EVT VT) const {
584 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
585 }
586 };
587
588/// This class is a DAGUpdateListener that removes any deleted
589/// nodes from the worklist.
590class WorklistRemover : public SelectionDAG::DAGUpdateListener {
591 DAGCombiner &DC;
592
593public:
594 explicit WorklistRemover(DAGCombiner &dc)
595 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
596
597 void NodeDeleted(SDNode *N, SDNode *E) override {
598 DC.removeFromWorklist(N);
599 }
600};
601
602} // end anonymous namespace
603
604//===----------------------------------------------------------------------===//
605// TargetLowering::DAGCombinerInfo implementation
606//===----------------------------------------------------------------------===//
607
608void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
609 ((DAGCombiner*)DC)->AddToWorklist(N);
610}
611
612SDValue TargetLowering::DAGCombinerInfo::
613CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
614 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
615}
616
617SDValue TargetLowering::DAGCombinerInfo::
618CombineTo(SDNode *N, SDValue Res, bool AddTo) {
619 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
620}
621
622SDValue TargetLowering::DAGCombinerInfo::
623CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
624 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
625}
626
627void TargetLowering::DAGCombinerInfo::
628CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
629 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
630}
631
632//===----------------------------------------------------------------------===//
633// Helper Functions
634//===----------------------------------------------------------------------===//
635
636void DAGCombiner::deleteAndRecombine(SDNode *N) {
637 removeFromWorklist(N);
638
639 // If the operands of this node are only used by the node, they will now be
640 // dead. Make sure to re-visit them and recursively delete dead nodes.
641 for (const SDValue &Op : N->ops())
642 // For an operand generating multiple values, one of the values may
643 // become dead allowing further simplification (e.g. split index
644 // arithmetic from an indexed load).
645 if (Op->hasOneUse() || Op->getNumValues() > 1)
646 AddToWorklist(Op.getNode());
647
648 DAG.DeleteNode(N);
649}
650
651/// Return 1 if we can compute the negated form of the specified expression for
652/// the same cost as the expression itself, or 2 if we can compute the negated
653/// form more cheaply than the expression itself.
654static char isNegatibleForFree(SDValue Op, bool LegalOperations,
655 const TargetLowering &TLI,
656 const TargetOptions *Options,
657 unsigned Depth = 0) {
658 // fneg is removable even if it has multiple uses.
659 if (Op.getOpcode() == ISD::FNEG) return 2;
660
661 // Don't allow anything with multiple uses.
662 if (!Op.hasOneUse()) return 0;
663
664 // Don't recurse exponentially.
665 if (Depth > 6) return 0;
666
667 switch (Op.getOpcode()) {
668 default: return false;
669 case ISD::ConstantFP: {
670 if (!LegalOperations)
671 return 1;
672
673 // Don't invert constant FP values after legalization unless the target says
674 // the negated constant is legal.
675 EVT VT = Op.getValueType();
676 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
677 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
678 }
679 case ISD::FADD:
680 // FIXME: determine better conditions for this xform.
681 if (!Options->UnsafeFPMath) return 0;
682
683 // After operation legalization, it might not be legal to create new FSUBs.
684 if (LegalOperations &&
685 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
686 return 0;
687
688 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
689 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
690 Options, Depth + 1))
691 return V;
692 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
693 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
694 Depth + 1);
695 case ISD::FSUB:
696 // We can't turn -(A-B) into B-A when we honor signed zeros.
697 if (!Options->NoSignedZerosFPMath &&
698 !Op.getNode()->getFlags().hasNoSignedZeros())
699 return 0;
700
701 // fold (fneg (fsub A, B)) -> (fsub B, A)
702 return 1;
703
704 case ISD::FMUL:
705 case ISD::FDIV:
706 if (Options->HonorSignDependentRoundingFPMath()) return 0;
707
708 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
709 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
710 Options, Depth + 1))
711 return V;
712
713 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
714 Depth + 1);
715
716 case ISD::FP_EXTEND:
717 case ISD::FP_ROUND:
718 case ISD::FSIN:
719 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
720 Depth + 1);
721 }
722}
723
724/// If isNegatibleForFree returns true, return the newly negated expression.
725static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
726 bool LegalOperations, unsigned Depth = 0) {
727 const TargetOptions &Options = DAG.getTarget().Options;
728 // fneg is removable even if it has multiple uses.
729 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
730
731 // Don't allow anything with multiple uses.
732 assert(Op.hasOneUse() && "Unknown reuse!")(static_cast <bool> (Op.hasOneUse() && "Unknown reuse!"
) ? void (0) : __assert_fail ("Op.hasOneUse() && \"Unknown reuse!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 732, __extension__ __PRETTY_FUNCTION__))
;
733
734 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree")(static_cast <bool> (Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"
) ? void (0) : __assert_fail ("Depth <= 6 && \"GetNegatedExpression doesn't match isNegatibleForFree\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 734, __extension__ __PRETTY_FUNCTION__))
;
735
736 const SDNodeFlags Flags = Op.getNode()->getFlags();
737
738 switch (Op.getOpcode()) {
739 default: llvm_unreachable("Unknown code")::llvm::llvm_unreachable_internal("Unknown code", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 739)
;
740 case ISD::ConstantFP: {
741 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
742 V.changeSign();
743 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
744 }
745 case ISD::FADD:
746 // FIXME: determine better conditions for this xform.
747 assert(Options.UnsafeFPMath)(static_cast <bool> (Options.UnsafeFPMath) ? void (0) :
__assert_fail ("Options.UnsafeFPMath", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 747, __extension__ __PRETTY_FUNCTION__))
;
748
749 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
750 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
751 DAG.getTargetLoweringInfo(), &Options, Depth+1))
752 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
753 GetNegatedExpression(Op.getOperand(0), DAG,
754 LegalOperations, Depth+1),
755 Op.getOperand(1), Flags);
756 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
757 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
758 GetNegatedExpression(Op.getOperand(1), DAG,
759 LegalOperations, Depth+1),
760 Op.getOperand(0), Flags);
761 case ISD::FSUB:
762 // fold (fneg (fsub 0, B)) -> B
763 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
764 if (N0CFP->isZero())
765 return Op.getOperand(1);
766
767 // fold (fneg (fsub A, B)) -> (fsub B, A)
768 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
769 Op.getOperand(1), Op.getOperand(0), Flags);
770
771 case ISD::FMUL:
772 case ISD::FDIV:
773 assert(!Options.HonorSignDependentRoundingFPMath())(static_cast <bool> (!Options.HonorSignDependentRoundingFPMath
()) ? void (0) : __assert_fail ("!Options.HonorSignDependentRoundingFPMath()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 773, __extension__ __PRETTY_FUNCTION__))
;
774
775 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
776 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
777 DAG.getTargetLoweringInfo(), &Options, Depth+1))
778 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
779 GetNegatedExpression(Op.getOperand(0), DAG,
780 LegalOperations, Depth+1),
781 Op.getOperand(1), Flags);
782
783 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
784 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
785 Op.getOperand(0),
786 GetNegatedExpression(Op.getOperand(1), DAG,
787 LegalOperations, Depth+1), Flags);
788
789 case ISD::FP_EXTEND:
790 case ISD::FSIN:
791 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
792 GetNegatedExpression(Op.getOperand(0), DAG,
793 LegalOperations, Depth+1));
794 case ISD::FP_ROUND:
795 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
796 GetNegatedExpression(Op.getOperand(0), DAG,
797 LegalOperations, Depth+1),
798 Op.getOperand(1));
799 }
800}
801
802// APInts must be the same size for most operations, this helper
803// function zero extends the shorter of the pair so that they match.
804// We provide an Offset so that we can create bitwidths that won't overflow.
805static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
806 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
807 LHS = LHS.zextOrSelf(Bits);
808 RHS = RHS.zextOrSelf(Bits);
809}
810
811// Return true if this node is a setcc, or is a select_cc
812// that selects between the target values used for true and false, making it
813// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
814// the appropriate nodes based on the type of node we are checking. This
815// simplifies life a bit for the callers.
816bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
817 SDValue &CC) const {
818 if (N.getOpcode() == ISD::SETCC) {
819 LHS = N.getOperand(0);
820 RHS = N.getOperand(1);
821 CC = N.getOperand(2);
822 return true;
823 }
824
825 if (N.getOpcode() != ISD::SELECT_CC ||
826 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
827 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
828 return false;
829
830 if (TLI.getBooleanContents(N.getValueType()) ==
831 TargetLowering::UndefinedBooleanContent)
832 return false;
833
834 LHS = N.getOperand(0);
835 RHS = N.getOperand(1);
836 CC = N.getOperand(4);
837 return true;
838}
839
840/// Return true if this is a SetCC-equivalent operation with only one use.
841/// If this is true, it allows the users to invert the operation for free when
842/// it is profitable to do so.
843bool DAGCombiner::isOneUseSetCC(SDValue N) const {
844 SDValue N0, N1, N2;
845 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
846 return true;
847 return false;
848}
849
850// \brief Returns the SDNode if it is a constant float BuildVector
851// or constant float.
852static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
853 if (isa<ConstantFPSDNode>(N))
854 return N.getNode();
855 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
856 return N.getNode();
857 return nullptr;
858}
859
860// Determines if it is a constant integer or a build vector of constant
861// integers (and undefs).
862// Do not permit build vector implicit truncation.
863static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
864 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
865 return !(Const->isOpaque() && NoOpaques);
866 if (N.getOpcode() != ISD::BUILD_VECTOR)
867 return false;
868 unsigned BitWidth = N.getScalarValueSizeInBits();
869 for (const SDValue &Op : N->op_values()) {
870 if (Op.isUndef())
871 continue;
872 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
873 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
874 (Const->isOpaque() && NoOpaques))
875 return false;
876 }
877 return true;
878}
879
880// Determines if it is a constant null integer or a splatted vector of a
881// constant null integer (with no undefs).
882// Build vector implicit truncation is not an issue for null values.
883static bool isNullConstantOrNullSplatConstant(SDValue N) {
884 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
885 return Splat->isNullValue();
886 return false;
887}
888
889// Determines if it is a constant integer of one or a splatted vector of a
890// constant integer of one (with no undefs).
891// Do not permit build vector implicit truncation.
892static bool isOneConstantOrOneSplatConstant(SDValue N) {
893 unsigned BitWidth = N.getScalarValueSizeInBits();
894 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
895 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
896 return false;
897}
898
899// Determines if it is a constant integer of all ones or a splatted vector of a
900// constant integer of all ones (with no undefs).
901// Do not permit build vector implicit truncation.
902static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
903 unsigned BitWidth = N.getScalarValueSizeInBits();
904 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
905 return Splat->isAllOnesValue() &&
906 Splat->getAPIntValue().getBitWidth() == BitWidth;
907 return false;
908}
909
910// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
911// undef's.
912static bool isAnyConstantBuildVector(const SDNode *N) {
913 return ISD::isBuildVectorOfConstantSDNodes(N) ||
914 ISD::isBuildVectorOfConstantFPSDNodes(N);
915}
916
917// Attempt to match a unary predicate against a scalar/splat constant or
918// every element of a constant BUILD_VECTOR.
919static bool matchUnaryPredicate(SDValue Op,
920 std::function<bool(ConstantSDNode *)> Match) {
921 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
922 return Match(Cst);
923
924 if (ISD::BUILD_VECTOR != Op.getOpcode())
925 return false;
926
927 EVT SVT = Op.getValueType().getScalarType();
928 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
929 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
930 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
931 return false;
932 }
933 return true;
934}
935
936// Attempt to match a binary predicate against a pair of scalar/splat constants
937// or every element of a pair of constant BUILD_VECTORs.
938static bool matchBinaryPredicate(
939 SDValue LHS, SDValue RHS,
940 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
941 if (LHS.getValueType() != RHS.getValueType())
942 return false;
943
944 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
945 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
946 return Match(LHSCst, RHSCst);
947
948 if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
949 ISD::BUILD_VECTOR != RHS.getOpcode())
950 return false;
951
952 EVT SVT = LHS.getValueType().getScalarType();
953 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
954 auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
955 auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
956 if (!LHSCst || !RHSCst)
957 return false;
958 if (LHSCst->getValueType(0) != SVT ||
959 LHSCst->getValueType(0) != RHSCst->getValueType(0))
960 return false;
961 if (!Match(LHSCst, RHSCst))
962 return false;
963 }
964 return true;
965}
966
967SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
968 SDValue N1) {
969 EVT VT = N0.getValueType();
970 if (N0.getOpcode() == Opc) {
971 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
972 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
973 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
974 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
975 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
976 return SDValue();
977 }
978 if (N0.hasOneUse()) {
979 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
980 // use
981 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
982 if (!OpNode.getNode())
983 return SDValue();
984 AddToWorklist(OpNode.getNode());
985 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
986 }
987 }
988 }
989
990 if (N1.getOpcode() == Opc) {
991 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
992 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
993 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
994 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
995 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
996 return SDValue();
997 }
998 if (N1.hasOneUse()) {
999 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
1000 // use
1001 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
1002 if (!OpNode.getNode())
1003 return SDValue();
1004 AddToWorklist(OpNode.getNode());
1005 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
1006 }
1007 }
1008 }
1009
1010 return SDValue();
1011}
1012
1013SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1014 bool AddTo) {
1015 assert(N->getNumValues() == NumTo && "Broken CombineTo call!")(static_cast <bool> (N->getNumValues() == NumTo &&
"Broken CombineTo call!") ? void (0) : __assert_fail ("N->getNumValues() == NumTo && \"Broken CombineTo call!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1015, __extension__ __PRETTY_FUNCTION__))
;
1016 ++NodesCombined;
1017 DEBUG(dbgs() << "\nReplacing.1 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo-1 <<
" other values\n"; } } while (false)
1018 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo-1 <<
" other values\n"; } } while (false)
1019 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo-1 <<
" other values\n"; } } while (false)
1020 To[0].getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo-1 <<
" other values\n"; } } while (false)
1021 dbgs() << " and " << NumTo-1 << " other values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.1 "; N->dump
(&DAG); dbgs() << "\nWith: "; To[0].getNode()->dump
(&DAG); dbgs() << " and " << NumTo-1 <<
" other values\n"; } } while (false)
;
1022 for (unsigned i = 0, e = NumTo; i != e; ++i)
1023 assert((!To[i].getNode() ||(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1025, __extension__ __PRETTY_FUNCTION__))
1024 N->getValueType(i) == To[i].getValueType()) &&(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1025, __extension__ __PRETTY_FUNCTION__))
1025 "Cannot combine value to value of different type!")(static_cast <bool> ((!To[i].getNode() || N->getValueType
(i) == To[i].getValueType()) && "Cannot combine value to value of different type!"
) ? void (0) : __assert_fail ("(!To[i].getNode() || N->getValueType(i) == To[i].getValueType()) && \"Cannot combine value to value of different type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1025, __extension__ __PRETTY_FUNCTION__))
;
1026
1027 WorklistRemover DeadNodes(*this);
1028 DAG.ReplaceAllUsesWith(N, To);
1029 if (AddTo) {
1030 // Push the new nodes and any users onto the worklist
1031 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1032 if (To[i].getNode()) {
1033 AddToWorklist(To[i].getNode());
1034 AddUsersToWorklist(To[i].getNode());
1035 }
1036 }
1037 }
1038
1039 // Finally, if the node is now dead, remove it from the graph. The node
1040 // may not be dead if the replacement process recursively simplified to
1041 // something else needing this node.
1042 if (N->use_empty())
1043 deleteAndRecombine(N);
1044 return SDValue(N, 0);
1045}
1046
1047void DAGCombiner::
1048CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1049 // Replace all uses. If any nodes become isomorphic to other nodes and
1050 // are deleted, make sure to remove them from our worklist.
1051 WorklistRemover DeadNodes(*this);
1052 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1053
1054 // Push the new node and any (possibly new) users onto the worklist.
1055 AddToWorklist(TLO.New.getNode());
1056 AddUsersToWorklist(TLO.New.getNode());
1057
1058 // Finally, if the node is now dead, remove it from the graph. The node
1059 // may not be dead if the replacement process recursively simplified to
1060 // something else needing this node.
1061 if (TLO.Old.getNode()->use_empty())
1062 deleteAndRecombine(TLO.Old.getNode());
1063}
1064
1065/// Check the specified integer node value to see if it can be simplified or if
1066/// things it uses can be simplified by bit propagation. If so, return true.
1067bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1068 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1069 KnownBits Known;
1070 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1071 return false;
1072
1073 // Revisit the node.
1074 AddToWorklist(Op.getNode());
1075
1076 // Replace the old value with the new one.
1077 ++NodesCombined;
1078 DEBUG(dbgs() << "\nReplacing.2 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1079 TLO.Old.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1080 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1081 TLO.New.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
1082 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.2 "; TLO.Old.getNode
()->dump(&DAG); dbgs() << "\nWith: "; TLO.New.getNode
()->dump(&DAG); dbgs() << '\n'; } } while (false
)
;
1083
1084 CommitTargetLoweringOpt(TLO);
1085 return true;
1086}
1087
1088void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1089 SDLoc DL(Load);
1090 EVT VT = Load->getValueType(0);
1091 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1092
1093 DEBUG(dbgs() << "\nReplacing.9 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
1094 Load->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
1095 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
1096 Trunc.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
1097 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.9 "; Load->
dump(&DAG); dbgs() << "\nWith: "; Trunc.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
;
1098 WorklistRemover DeadNodes(*this);
1099 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1100 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1101 deleteAndRecombine(Load);
1102 AddToWorklist(Trunc.getNode());
1103}
1104
1105SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1106 Replace = false;
1107 SDLoc DL(Op);
1108 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1109 LoadSDNode *LD = cast<LoadSDNode>(Op);
1110 EVT MemVT = LD->getMemoryVT();
1111 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1112 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1113 : ISD::EXTLOAD)
1114 : LD->getExtensionType();
1115 Replace = true;
1116 return DAG.getExtLoad(ExtType, DL, PVT,
1117 LD->getChain(), LD->getBasePtr(),
1118 MemVT, LD->getMemOperand());
1119 }
1120
1121 unsigned Opc = Op.getOpcode();
1122 switch (Opc) {
1123 default: break;
1124 case ISD::AssertSext:
1125 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1126 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1127 break;
1128 case ISD::AssertZext:
1129 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1130 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1131 break;
1132 case ISD::Constant: {
1133 unsigned ExtOpc =
1134 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1135 return DAG.getNode(ExtOpc, DL, PVT, Op);
1136 }
1137 }
1138
1139 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1140 return SDValue();
1141 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1142}
1143
1144SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1145 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1146 return SDValue();
1147 EVT OldVT = Op.getValueType();
1148 SDLoc DL(Op);
1149 bool Replace = false;
1150 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1151 if (!NewOp.getNode())
1152 return SDValue();
1153 AddToWorklist(NewOp.getNode());
1154
1155 if (Replace)
1156 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1157 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1158 DAG.getValueType(OldVT));
1159}
1160
1161SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1162 EVT OldVT = Op.getValueType();
1163 SDLoc DL(Op);
1164 bool Replace = false;
1165 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1166 if (!NewOp.getNode())
1167 return SDValue();
1168 AddToWorklist(NewOp.getNode());
1169
1170 if (Replace)
1171 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1172 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1173}
1174
1175/// Promote the specified integer binary operation if the target indicates it is
1176/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1177/// i32 since i16 instructions are longer.
1178SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1179 if (!LegalOperations)
1180 return SDValue();
1181
1182 EVT VT = Op.getValueType();
1183 if (VT.isVector() || !VT.isInteger())
1184 return SDValue();
1185
1186 // If operation type is 'undesirable', e.g. i16 on x86, consider
1187 // promoting it.
1188 unsigned Opc = Op.getOpcode();
1189 if (TLI.isTypeDesirableForOp(Opc, VT))
1190 return SDValue();
1191
1192 EVT PVT = VT;
1193 // Consult target whether it is a good idea to promote this operation and
1194 // what's the right type to promote it to.
1195 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1196 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1196, __extension__ __PRETTY_FUNCTION__))
;
1197
1198 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1199
1200 bool Replace0 = false;
1201 SDValue N0 = Op.getOperand(0);
1202 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1203
1204 bool Replace1 = false;
1205 SDValue N1 = Op.getOperand(1);
1206 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1207 SDLoc DL(Op);
1208
1209 SDValue RV =
1210 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1211
1212 // We are always replacing N0/N1's use in N and only need
1213 // additional replacements if there are additional uses.
1214 Replace0 &= !N0->hasOneUse();
1215 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1216
1217 // Combine Op here so it is preserved past replacements.
1218 CombineTo(Op.getNode(), RV);
1219
1220 // If operands have a use ordering, make sure we deal with
1221 // predecessor first.
1222 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1223 std::swap(N0, N1);
1224 std::swap(NN0, NN1);
1225 }
1226
1227 if (Replace0) {
1228 AddToWorklist(NN0.getNode());
1229 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1230 }
1231 if (Replace1) {
1232 AddToWorklist(NN1.getNode());
1233 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1234 }
1235 return Op;
1236 }
1237 return SDValue();
1238}
1239
1240/// Promote the specified integer shift operation if the target indicates it is
1241/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1242/// i32 since i16 instructions are longer.
1243SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1244 if (!LegalOperations)
1245 return SDValue();
1246
1247 EVT VT = Op.getValueType();
1248 if (VT.isVector() || !VT.isInteger())
1249 return SDValue();
1250
1251 // If operation type is 'undesirable', e.g. i16 on x86, consider
1252 // promoting it.
1253 unsigned Opc = Op.getOpcode();
1254 if (TLI.isTypeDesirableForOp(Opc, VT))
1255 return SDValue();
1256
1257 EVT PVT = VT;
1258 // Consult target whether it is a good idea to promote this operation and
1259 // what's the right type to promote it to.
1260 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1261 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1261, __extension__ __PRETTY_FUNCTION__))
;
1262
1263 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1264
1265 bool Replace = false;
1266 SDValue N0 = Op.getOperand(0);
1267 SDValue N1 = Op.getOperand(1);
1268 if (Opc == ISD::SRA)
1269 N0 = SExtPromoteOperand(N0, PVT);
1270 else if (Opc == ISD::SRL)
1271 N0 = ZExtPromoteOperand(N0, PVT);
1272 else
1273 N0 = PromoteOperand(N0, PVT, Replace);
1274
1275 if (!N0.getNode())
1276 return SDValue();
1277
1278 SDLoc DL(Op);
1279 SDValue RV =
1280 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1281
1282 AddToWorklist(N0.getNode());
1283 if (Replace)
1284 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1285
1286 // Deal with Op being deleted.
1287 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1288 return RV;
1289 }
1290 return SDValue();
1291}
1292
1293SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1294 if (!LegalOperations)
1295 return SDValue();
1296
1297 EVT VT = Op.getValueType();
1298 if (VT.isVector() || !VT.isInteger())
1299 return SDValue();
1300
1301 // If operation type is 'undesirable', e.g. i16 on x86, consider
1302 // promoting it.
1303 unsigned Opc = Op.getOpcode();
1304 if (TLI.isTypeDesirableForOp(Opc, VT))
1305 return SDValue();
1306
1307 EVT PVT = VT;
1308 // Consult target whether it is a good idea to promote this operation and
1309 // what's the right type to promote it to.
1310 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1311 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1311, __extension__ __PRETTY_FUNCTION__))
;
1312 // fold (aext (aext x)) -> (aext x)
1313 // fold (aext (zext x)) -> (zext x)
1314 // fold (aext (sext x)) -> (sext x)
1315 DEBUG(dbgs() << "\nPromoting ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
1316 Op.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; Op.getNode(
)->dump(&DAG); } } while (false)
;
1317 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1318 }
1319 return SDValue();
1320}
1321
1322bool DAGCombiner::PromoteLoad(SDValue Op) {
1323 if (!LegalOperations)
1324 return false;
1325
1326 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1327 return false;
1328
1329 EVT VT = Op.getValueType();
1330 if (VT.isVector() || !VT.isInteger())
1331 return false;
1332
1333 // If operation type is 'undesirable', e.g. i16 on x86, consider
1334 // promoting it.
1335 unsigned Opc = Op.getOpcode();
1336 if (TLI.isTypeDesirableForOp(Opc, VT))
1337 return false;
1338
1339 EVT PVT = VT;
1340 // Consult target whether it is a good idea to promote this operation and
1341 // what's the right type to promote it to.
1342 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1343 assert(PVT != VT && "Don't know what type to promote to!")(static_cast <bool> (PVT != VT && "Don't know what type to promote to!"
) ? void (0) : __assert_fail ("PVT != VT && \"Don't know what type to promote to!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
;
1344
1345 SDLoc DL(Op);
1346 SDNode *N = Op.getNode();
1347 LoadSDNode *LD = cast<LoadSDNode>(N);
1348 EVT MemVT = LD->getMemoryVT();
1349 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1350 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1351 : ISD::EXTLOAD)
1352 : LD->getExtensionType();
1353 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1354 LD->getChain(), LD->getBasePtr(),
1355 MemVT, LD->getMemOperand());
1356 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1357
1358 DEBUG(dbgs() << "\nPromoting ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
1359 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
1360 dbgs() << "\nTo: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
1361 Result.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
1362 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nPromoting "; N->dump(
&DAG); dbgs() << "\nTo: "; Result.getNode()->dump
(&DAG); dbgs() << '\n'; } } while (false)
;
1363 WorklistRemover DeadNodes(*this);
1364 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1365 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1366 deleteAndRecombine(N);
1367 AddToWorklist(Result.getNode());
1368 return true;
1369 }
1370 return false;
1371}
1372
1373/// \brief Recursively delete a node which has no uses and any operands for
1374/// which it is the only use.
1375///
1376/// Note that this both deletes the nodes and removes them from the worklist.
1377/// It also adds any nodes who have had a user deleted to the worklist as they
1378/// may now have only one use and subject to other combines.
1379bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1380 if (!N->use_empty())
1381 return false;
1382
1383 SmallSetVector<SDNode *, 16> Nodes;
1384 Nodes.insert(N);
1385 do {
1386 N = Nodes.pop_back_val();
1387 if (!N)
1388 continue;
1389
1390 if (N->use_empty()) {
1391 for (const SDValue &ChildN : N->op_values())
1392 Nodes.insert(ChildN.getNode());
1393
1394 removeFromWorklist(N);
1395 DAG.DeleteNode(N);
1396 } else {
1397 AddToWorklist(N);
1398 }
1399 } while (!Nodes.empty());
1400 return true;
1401}
1402
1403//===----------------------------------------------------------------------===//
1404// Main DAG Combiner implementation
1405//===----------------------------------------------------------------------===//
1406
1407void DAGCombiner::Run(CombineLevel AtLevel) {
1408 // set the instance variables, so that the various visit routines may use it.
1409 Level = AtLevel;
1410 LegalOperations = Level >= AfterLegalizeVectorOps;
1411 LegalTypes = Level >= AfterLegalizeTypes;
1412
1413 // Add all the dag nodes to the worklist.
1414 for (SDNode &Node : DAG.allnodes())
1415 AddToWorklist(&Node);
1416
1417 // Create a dummy node (which is not added to allnodes), that adds a reference
1418 // to the root node, preventing it from being deleted, and tracking any
1419 // changes of the root.
1420 HandleSDNode Dummy(DAG.getRoot());
1421
1422 // While the worklist isn't empty, find a node and try to combine it.
1423 while (!WorklistMap.empty()) {
1424 SDNode *N;
1425 // The Worklist holds the SDNodes in order, but it may contain null entries.
1426 do {
1427 N = Worklist.pop_back_val();
1428 } while (!N);
1429
1430 bool GoodWorklistEntry = WorklistMap.erase(N);
1431 (void)GoodWorklistEntry;
1432 assert(GoodWorklistEntry &&(static_cast <bool> (GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!"
) ? void (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1433, __extension__ __PRETTY_FUNCTION__))
1433 "Found a worklist entry without a corresponding map entry!")(static_cast <bool> (GoodWorklistEntry && "Found a worklist entry without a corresponding map entry!"
) ? void (0) : __assert_fail ("GoodWorklistEntry && \"Found a worklist entry without a corresponding map entry!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1433, __extension__ __PRETTY_FUNCTION__))
;
1434
1435 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1436 // N is deleted from the DAG, since they too may now be dead or may have a
1437 // reduced number of uses, allowing other xforms.
1438 if (recursivelyDeleteUnusedNodes(N))
1439 continue;
1440
1441 WorklistRemover DeadNodes(*this);
1442
1443 // If this combine is running after legalizing the DAG, re-legalize any
1444 // nodes pulled off the worklist.
1445 if (Level == AfterLegalizeDAG) {
1446 SmallSetVector<SDNode *, 16> UpdatedNodes;
1447 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1448
1449 for (SDNode *LN : UpdatedNodes) {
1450 AddToWorklist(LN);
1451 AddUsersToWorklist(LN);
1452 }
1453 if (!NIsValid)
1454 continue;
1455 }
1456
1457 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nCombining: "; N->dump
(&DAG); } } while (false)
;
1458
1459 // Add any operands of the new node which have not yet been combined to the
1460 // worklist as well. Because the worklist uniques things already, this
1461 // won't repeatedly process the same operand.
1462 CombinedNodes.insert(N);
1463 for (const SDValue &ChildN : N->op_values())
1464 if (!CombinedNodes.count(ChildN.getNode()))
1465 AddToWorklist(ChildN.getNode());
1466
1467 SDValue RV = combine(N);
1468
1469 if (!RV.getNode())
1470 continue;
1471
1472 ++NodesCombined;
1473
1474 // If we get back the same node we passed in, rather than a new node or
1475 // zero, we know that the node must have defined multiple values and
1476 // CombineTo was used. Since CombineTo takes care of the worklist
1477 // mechanics for us, we have no work to do in this case.
1478 if (RV.getNode() == N)
1479 continue;
1480
1481 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1483, __extension__ __PRETTY_FUNCTION__))
1482 RV.getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1483, __extension__ __PRETTY_FUNCTION__))
1483 "Node was deleted but visit returned new node!")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& RV.getOpcode() != ISD::DELETED_NODE && "Node was deleted but visit returned new node!"
) ? void (0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && RV.getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned new node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1483, __extension__ __PRETTY_FUNCTION__))
;
1484
1485 DEBUG(dbgs() << " ... into: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << " ... into: "; RV.getNode()
->dump(&DAG); } } while (false)
1486 RV.getNode()->dump(&DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << " ... into: "; RV.getNode()
->dump(&DAG); } } while (false)
;
1487
1488 if (N->getNumValues() == RV.getNode()->getNumValues())
1489 DAG.ReplaceAllUsesWith(N, RV.getNode());
1490 else {
1491 assert(N->getValueType(0) == RV.getValueType() &&(static_cast <bool> (N->getValueType(0) == RV.getValueType
() && N->getNumValues() == 1 && "Type mismatch"
) ? void (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1492, __extension__ __PRETTY_FUNCTION__))
1492 N->getNumValues() == 1 && "Type mismatch")(static_cast <bool> (N->getValueType(0) == RV.getValueType
() && N->getNumValues() == 1 && "Type mismatch"
) ? void (0) : __assert_fail ("N->getValueType(0) == RV.getValueType() && N->getNumValues() == 1 && \"Type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1492, __extension__ __PRETTY_FUNCTION__))
;
1493 DAG.ReplaceAllUsesWith(N, &RV);
1494 }
1495
1496 // Push the new node and any users onto the worklist
1497 AddToWorklist(RV.getNode());
1498 AddUsersToWorklist(RV.getNode());
1499
1500 // Finally, if the node is now dead, remove it from the graph. The node
1501 // may not be dead if the replacement process recursively simplified to
1502 // something else needing this node. This will also take care of adding any
1503 // operands which have lost a user to the worklist.
1504 recursivelyDeleteUnusedNodes(N);
1505 }
1506
1507 // If the root changed (e.g. it was a dead load, update the root).
1508 DAG.setRoot(Dummy.getValue());
1509 DAG.RemoveDeadNodes();
1510}
1511
1512SDValue DAGCombiner::visit(SDNode *N) {
1513 switch (N->getOpcode()) {
1514 default: break;
1515 case ISD::TokenFactor: return visitTokenFactor(N);
1516 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1517 case ISD::ADD: return visitADD(N);
1518 case ISD::SUB: return visitSUB(N);
1519 case ISD::ADDC: return visitADDC(N);
1520 case ISD::UADDO: return visitUADDO(N);
1521 case ISD::SUBC: return visitSUBC(N);
1522 case ISD::USUBO: return visitUSUBO(N);
1523 case ISD::ADDE: return visitADDE(N);
1524 case ISD::ADDCARRY: return visitADDCARRY(N);
1525 case ISD::SUBE: return visitSUBE(N);
1526 case ISD::SUBCARRY: return visitSUBCARRY(N);
1527 case ISD::MUL: return visitMUL(N);
1528 case ISD::SDIV: return visitSDIV(N);
1529 case ISD::UDIV: return visitUDIV(N);
1530 case ISD::SREM:
1531 case ISD::UREM: return visitREM(N);
1532 case ISD::MULHU: return visitMULHU(N);
1533 case ISD::MULHS: return visitMULHS(N);
1534 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1535 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1536 case ISD::SMULO: return visitSMULO(N);
1537 case ISD::UMULO: return visitUMULO(N);
1538 case ISD::SMIN:
1539 case ISD::SMAX:
1540 case ISD::UMIN:
1541 case ISD::UMAX: return visitIMINMAX(N);
1542 case ISD::AND: return visitAND(N);
1543 case ISD::OR: return visitOR(N);
1544 case ISD::XOR: return visitXOR(N);
1545 case ISD::SHL: return visitSHL(N);
1546 case ISD::SRA: return visitSRA(N);
1547 case ISD::SRL: return visitSRL(N);
1548 case ISD::ROTR:
1549 case ISD::ROTL: return visitRotate(N);
1550 case ISD::ABS: return visitABS(N);
1551 case ISD::BSWAP: return visitBSWAP(N);
1552 case ISD::BITREVERSE: return visitBITREVERSE(N);
1553 case ISD::CTLZ: return visitCTLZ(N);
1554 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1555 case ISD::CTTZ: return visitCTTZ(N);
1556 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1557 case ISD::CTPOP: return visitCTPOP(N);
1558 case ISD::SELECT: return visitSELECT(N);
1559 case ISD::VSELECT: return visitVSELECT(N);
1560 case ISD::SELECT_CC: return visitSELECT_CC(N);
1561 case ISD::SETCC: return visitSETCC(N);
1562 case ISD::SETCCE: return visitSETCCE(N);
1563 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1564 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1565 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1566 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1567 case ISD::AssertSext:
1568 case ISD::AssertZext: return visitAssertExt(N);
1569 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1570 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1571 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1572 case ISD::TRUNCATE: return visitTRUNCATE(N);
1573 case ISD::BITCAST: return visitBITCAST(N);
1574 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1575 case ISD::FADD: return visitFADD(N);
1576 case ISD::FSUB: return visitFSUB(N);
1577 case ISD::FMUL: return visitFMUL(N);
1578 case ISD::FMA: return visitFMA(N);
1579 case ISD::FDIV: return visitFDIV(N);
1580 case ISD::FREM: return visitFREM(N);
1581 case ISD::FSQRT: return visitFSQRT(N);
1582 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1583 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1584 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1585 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1586 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1587 case ISD::FP_ROUND: return visitFP_ROUND(N);
1588 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1589 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1590 case ISD::FNEG: return visitFNEG(N);
1591 case ISD::FABS: return visitFABS(N);
1592 case ISD::FFLOOR: return visitFFLOOR(N);
1593 case ISD::FMINNUM: return visitFMINNUM(N);
1594 case ISD::FMAXNUM: return visitFMAXNUM(N);
1595 case ISD::FCEIL: return visitFCEIL(N);
1596 case ISD::FTRUNC: return visitFTRUNC(N);
1597 case ISD::BRCOND: return visitBRCOND(N);
1598 case ISD::BR_CC: return visitBR_CC(N);
1599 case ISD::LOAD: return visitLOAD(N);
1600 case ISD::STORE: return visitSTORE(N);
1601 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1602 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1603 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1604 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1605 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1606 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1607 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1608 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1609 case ISD::MGATHER: return visitMGATHER(N);
1610 case ISD::MLOAD: return visitMLOAD(N);
1611 case ISD::MSCATTER: return visitMSCATTER(N);
1612 case ISD::MSTORE: return visitMSTORE(N);
1613 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1614 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1615 }
1616 return SDValue();
1617}
1618
1619SDValue DAGCombiner::combine(SDNode *N) {
1620 SDValue RV = visit(N);
1621
1622 // If nothing happened, try a target-specific DAG combine.
1623 if (!RV.getNode()) {
1624 assert(N->getOpcode() != ISD::DELETED_NODE &&(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Node was deleted but visit returned NULL!") ? void
(0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1625, __extension__ __PRETTY_FUNCTION__))
1625 "Node was deleted but visit returned NULL!")(static_cast <bool> (N->getOpcode() != ISD::DELETED_NODE
&& "Node was deleted but visit returned NULL!") ? void
(0) : __assert_fail ("N->getOpcode() != ISD::DELETED_NODE && \"Node was deleted but visit returned NULL!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1625, __extension__ __PRETTY_FUNCTION__))
;
1626
1627 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1628 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1629
1630 // Expose the DAG combiner to the target combiner impls.
1631 TargetLowering::DAGCombinerInfo
1632 DagCombineInfo(DAG, Level, false, this);
1633
1634 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1635 }
1636 }
1637
1638 // If nothing happened still, try promoting the operation.
1639 if (!RV.getNode()) {
1640 switch (N->getOpcode()) {
1641 default: break;
1642 case ISD::ADD:
1643 case ISD::SUB:
1644 case ISD::MUL:
1645 case ISD::AND:
1646 case ISD::OR:
1647 case ISD::XOR:
1648 RV = PromoteIntBinOp(SDValue(N, 0));
1649 break;
1650 case ISD::SHL:
1651 case ISD::SRA:
1652 case ISD::SRL:
1653 RV = PromoteIntShiftOp(SDValue(N, 0));
1654 break;
1655 case ISD::SIGN_EXTEND:
1656 case ISD::ZERO_EXTEND:
1657 case ISD::ANY_EXTEND:
1658 RV = PromoteExtend(SDValue(N, 0));
1659 break;
1660 case ISD::LOAD:
1661 if (PromoteLoad(SDValue(N, 0)))
1662 RV = SDValue(N, 0);
1663 break;
1664 }
1665 }
1666
1667 // If N is a commutative binary node, try eliminate it if the commuted
1668 // version is already present in the DAG.
1669 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1670 N->getNumValues() == 1) {
1671 SDValue N0 = N->getOperand(0);
1672 SDValue N1 = N->getOperand(1);
1673
1674 // Constant operands are canonicalized to RHS.
1675 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1676 SDValue Ops[] = {N1, N0};
1677 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1678 N->getFlags());
1679 if (CSENode)
1680 return SDValue(CSENode, 0);
1681 }
1682 }
1683
1684 return RV;
1685}
1686
1687/// Given a node, return its input chain if it has one, otherwise return a null
1688/// sd operand.
1689static SDValue getInputChainForNode(SDNode *N) {
1690 if (unsigned NumOps = N->getNumOperands()) {
1691 if (N->getOperand(0).getValueType() == MVT::Other)
1692 return N->getOperand(0);
1693 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1694 return N->getOperand(NumOps-1);
1695 for (unsigned i = 1; i < NumOps-1; ++i)
1696 if (N->getOperand(i).getValueType() == MVT::Other)
1697 return N->getOperand(i);
1698 }
1699 return SDValue();
1700}
1701
1702SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1703 // If N has two operands, where one has an input chain equal to the other,
1704 // the 'other' chain is redundant.
1705 if (N->getNumOperands() == 2) {
1706 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1707 return N->getOperand(0);
1708 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1709 return N->getOperand(1);
1710 }
1711
1712 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1713 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1714 SmallPtrSet<SDNode*, 16> SeenOps;
1715 bool Changed = false; // If we should replace this token factor.
1716
1717 // Start out with this token factor.
1718 TFs.push_back(N);
1719
1720 // Iterate through token factors. The TFs grows when new token factors are
1721 // encountered.
1722 for (unsigned i = 0; i < TFs.size(); ++i) {
1723 SDNode *TF = TFs[i];
1724
1725 // Check each of the operands.
1726 for (const SDValue &Op : TF->op_values()) {
1727 switch (Op.getOpcode()) {
1728 case ISD::EntryToken:
1729 // Entry tokens don't need to be added to the list. They are
1730 // redundant.
1731 Changed = true;
1732 break;
1733
1734 case ISD::TokenFactor:
1735 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1736 // Queue up for processing.
1737 TFs.push_back(Op.getNode());
1738 // Clean up in case the token factor is removed.
1739 AddToWorklist(Op.getNode());
1740 Changed = true;
1741 break;
1742 }
1743 LLVM_FALLTHROUGH[[clang::fallthrough]];
1744
1745 default:
1746 // Only add if it isn't already in the list.
1747 if (SeenOps.insert(Op.getNode()).second)
1748 Ops.push_back(Op);
1749 else
1750 Changed = true;
1751 break;
1752 }
1753 }
1754 }
1755
1756 // Remove Nodes that are chained to another node in the list. Do so
1757 // by walking up chains breath-first stopping when we've seen
1758 // another operand. In general we must climb to the EntryNode, but we can exit
1759 // early if we find all remaining work is associated with just one operand as
1760 // no further pruning is possible.
1761
1762 // List of nodes to search through and original Ops from which they originate.
1763 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1764 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1765 SmallPtrSet<SDNode *, 16> SeenChains;
1766 bool DidPruneOps = false;
1767
1768 unsigned NumLeftToConsider = 0;
1769 for (const SDValue &Op : Ops) {
1770 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1771 OpWorkCount.push_back(1);
1772 }
1773
1774 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1775 // If this is an Op, we can remove the op from the list. Remark any
1776 // search associated with it as from the current OpNumber.
1777 if (SeenOps.count(Op) != 0) {
1778 Changed = true;
1779 DidPruneOps = true;
1780 unsigned OrigOpNumber = 0;
1781 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1782 OrigOpNumber++;
1783 assert((OrigOpNumber != Ops.size()) &&(static_cast <bool> ((OrigOpNumber != Ops.size()) &&
"expected to find TokenFactor Operand") ? void (0) : __assert_fail
("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1784, __extension__ __PRETTY_FUNCTION__))
1784 "expected to find TokenFactor Operand")(static_cast <bool> ((OrigOpNumber != Ops.size()) &&
"expected to find TokenFactor Operand") ? void (0) : __assert_fail
("(OrigOpNumber != Ops.size()) && \"expected to find TokenFactor Operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1784, __extension__ __PRETTY_FUNCTION__))
;
1785 // Re-mark worklist from OrigOpNumber to OpNumber
1786 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1787 if (Worklist[i].second == OrigOpNumber) {
1788 Worklist[i].second = OpNumber;
1789 }
1790 }
1791 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1792 OpWorkCount[OrigOpNumber] = 0;
1793 NumLeftToConsider--;
1794 }
1795 // Add if it's a new chain
1796 if (SeenChains.insert(Op).second) {
1797 OpWorkCount[OpNumber]++;
1798 Worklist.push_back(std::make_pair(Op, OpNumber));
1799 }
1800 };
1801
1802 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1803 // We need at least be consider at least 2 Ops to prune.
1804 if (NumLeftToConsider <= 1)
1805 break;
1806 auto CurNode = Worklist[i].first;
1807 auto CurOpNumber = Worklist[i].second;
1808 assert((OpWorkCount[CurOpNumber] > 0) &&(static_cast <bool> ((OpWorkCount[CurOpNumber] > 0) &&
"Node should not appear in worklist") ? void (0) : __assert_fail
("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1809, __extension__ __PRETTY_FUNCTION__))
1809 "Node should not appear in worklist")(static_cast <bool> ((OpWorkCount[CurOpNumber] > 0) &&
"Node should not appear in worklist") ? void (0) : __assert_fail
("(OpWorkCount[CurOpNumber] > 0) && \"Node should not appear in worklist\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1809, __extension__ __PRETTY_FUNCTION__))
;
1810 switch (CurNode->getOpcode()) {
1811 case ISD::EntryToken:
1812 // Hitting EntryToken is the only way for the search to terminate without
1813 // hitting
1814 // another operand's search. Prevent us from marking this operand
1815 // considered.
1816 NumLeftToConsider++;
1817 break;
1818 case ISD::TokenFactor:
1819 for (const SDValue &Op : CurNode->op_values())
1820 AddToWorklist(i, Op.getNode(), CurOpNumber);
1821 break;
1822 case ISD::CopyFromReg:
1823 case ISD::CopyToReg:
1824 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1825 break;
1826 default:
1827 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1828 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1829 break;
1830 }
1831 OpWorkCount[CurOpNumber]--;
1832 if (OpWorkCount[CurOpNumber] == 0)
1833 NumLeftToConsider--;
1834 }
1835
1836 // If we've changed things around then replace token factor.
1837 if (Changed) {
1838 SDValue Result;
1839 if (Ops.empty()) {
1840 // The entry token is the only possible outcome.
1841 Result = DAG.getEntryNode();
1842 } else {
1843 if (DidPruneOps) {
1844 SmallVector<SDValue, 8> PrunedOps;
1845 //
1846 for (const SDValue &Op : Ops) {
1847 if (SeenChains.count(Op.getNode()) == 0)
1848 PrunedOps.push_back(Op);
1849 }
1850 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1851 } else {
1852 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1853 }
1854 }
1855 return Result;
1856 }
1857 return SDValue();
1858}
1859
1860/// MERGE_VALUES can always be eliminated.
1861SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1862 WorklistRemover DeadNodes(*this);
1863 // Replacing results may cause a different MERGE_VALUES to suddenly
1864 // be CSE'd with N, and carry its uses with it. Iterate until no
1865 // uses remain, to ensure that the node can be safely deleted.
1866 // First add the users of this node to the work list so that they
1867 // can be tried again once they have new operands.
1868 AddUsersToWorklist(N);
1869 do {
1870 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1871 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1872 } while (!N->use_empty());
1873 deleteAndRecombine(N);
1874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1875}
1876
1877/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1878/// ConstantSDNode pointer else nullptr.
1879static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1880 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1881 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1882}
1883
1884SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1885 auto BinOpcode = BO->getOpcode();
1886 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1887 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1888 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1889 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1890 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1891 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1892 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1893 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1894 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
1895 "Unexpected binary operator")(static_cast <bool> ((BinOpcode == ISD::ADD || BinOpcode
== ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV
|| BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode
== ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR
|| BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode
== ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD
|| BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode
== ISD::FDIV || BinOpcode == ISD::FREM) && "Unexpected binary operator"
) ? void (0) : __assert_fail ("(BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || BinOpcode == ISD::UREM || BinOpcode == ISD::AND || BinOpcode == ISD::OR || BinOpcode == ISD::XOR || BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && \"Unexpected binary operator\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 1895, __extension__ __PRETTY_FUNCTION__))
;
1896
1897 // Bail out if any constants are opaque because we can't constant fold those.
1898 SDValue C1 = BO->getOperand(1);
1899 if (!isConstantOrConstantVector(C1, true) &&
1900 !isConstantFPBuildVectorOrConstantFP(C1))
1901 return SDValue();
1902
1903 // Don't do this unless the old select is going away. We want to eliminate the
1904 // binary operator, not replace a binop with a select.
1905 // TODO: Handle ISD::SELECT_CC.
1906 SDValue Sel = BO->getOperand(0);
1907 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1908 return SDValue();
1909
1910 SDValue CT = Sel.getOperand(1);
1911 if (!isConstantOrConstantVector(CT, true) &&
1912 !isConstantFPBuildVectorOrConstantFP(CT))
1913 return SDValue();
1914
1915 SDValue CF = Sel.getOperand(2);
1916 if (!isConstantOrConstantVector(CF, true) &&
1917 !isConstantFPBuildVectorOrConstantFP(CF))
1918 return SDValue();
1919
1920 // We have a select-of-constants followed by a binary operator with a
1921 // constant. Eliminate the binop by pulling the constant math into the select.
1922 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1923 EVT VT = Sel.getValueType();
1924 SDLoc DL(Sel);
1925 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1926 if (!NewCT.isUndef() &&
1927 !isConstantOrConstantVector(NewCT, true) &&
1928 !isConstantFPBuildVectorOrConstantFP(NewCT))
1929 return SDValue();
1930
1931 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1932 if (!NewCF.isUndef() &&
1933 !isConstantOrConstantVector(NewCF, true) &&
1934 !isConstantFPBuildVectorOrConstantFP(NewCF))
1935 return SDValue();
1936
1937 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1938}
1939
1940SDValue DAGCombiner::visitADD(SDNode *N) {
1941 SDValue N0 = N->getOperand(0);
1942 SDValue N1 = N->getOperand(1);
1943 EVT VT = N0.getValueType();
1944 SDLoc DL(N);
1945
1946 // fold vector ops
1947 if (VT.isVector()) {
1948 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1949 return FoldedVOp;
1950
1951 // fold (add x, 0) -> x, vector edition
1952 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1953 return N0;
1954 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1955 return N1;
1956 }
1957
1958 // fold (add x, undef) -> undef
1959 if (N0.isUndef())
1960 return N0;
1961
1962 if (N1.isUndef())
1963 return N1;
1964
1965 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1966 // canonicalize constant to RHS
1967 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1968 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1969 // fold (add c1, c2) -> c1+c2
1970 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1971 N1.getNode());
1972 }
1973
1974 // fold (add x, 0) -> x
1975 if (isNullConstant(N1))
1976 return N0;
1977
1978 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1979 // fold ((c1-A)+c2) -> (c1+c2)-A
1980 if (N0.getOpcode() == ISD::SUB &&
1981 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1982 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1983 return DAG.getNode(ISD::SUB, DL, VT,
1984 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1985 N0.getOperand(1));
1986 }
1987
1988 // add (sext i1 X), 1 -> zext (not i1 X)
1989 // We don't transform this pattern:
1990 // add (zext i1 X), -1 -> sext (not i1 X)
1991 // because most (?) targets generate better code for the zext form.
1992 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1993 isOneConstantOrOneSplatConstant(N1)) {
1994 SDValue X = N0.getOperand(0);
1995 if ((!LegalOperations ||
1996 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1997 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1998 X.getScalarValueSizeInBits() == 1) {
1999 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2000 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2001 }
2002 }
2003
2004 // Undo the add -> or combine to merge constant offsets from a frame index.
2005 if (N0.getOpcode() == ISD::OR &&
2006 isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2007 isa<ConstantSDNode>(N0.getOperand(1)) &&
2008 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2009 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2010 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2011 }
2012 }
2013
2014 if (SDValue NewSel = foldBinOpIntoSelect(N))
2015 return NewSel;
2016
2017 // reassociate add
2018 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2019 return RADD;
2020
2021 // fold ((0-A) + B) -> B-A
2022 if (N0.getOpcode() == ISD::SUB &&
2023 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2024 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2025
2026 // fold (A + (0-B)) -> A-B
2027 if (N1.getOpcode() == ISD::SUB &&
2028 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2029 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2030
2031 // fold (A+(B-A)) -> B
2032 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2033 return N1.getOperand(0);
2034
2035 // fold ((B-A)+A) -> B
2036 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2037 return N0.getOperand(0);
2038
2039 // fold (A+(B-(A+C))) to (B-C)
2040 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2041 N0 == N1.getOperand(1).getOperand(0))
2042 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2043 N1.getOperand(1).getOperand(1));
2044
2045 // fold (A+(B-(C+A))) to (B-C)
2046 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2047 N0 == N1.getOperand(1).getOperand(1))
2048 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2049 N1.getOperand(1).getOperand(0));
2050
2051 // fold (A+((B-A)+or-C)) to (B+or-C)
2052 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2053 N1.getOperand(0).getOpcode() == ISD::SUB &&
2054 N0 == N1.getOperand(0).getOperand(1))
2055 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2056 N1.getOperand(1));
2057
2058 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2059 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2060 SDValue N00 = N0.getOperand(0);
2061 SDValue N01 = N0.getOperand(1);
2062 SDValue N10 = N1.getOperand(0);
2063 SDValue N11 = N1.getOperand(1);
2064
2065 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2066 return DAG.getNode(ISD::SUB, DL, VT,
2067 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2068 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2069 }
2070
2071 if (SimplifyDemandedBits(SDValue(N, 0)))
2072 return SDValue(N, 0);
2073
2074 // fold (a+b) -> (a|b) iff a and b share no bits.
2075 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2076 DAG.haveNoCommonBitsSet(N0, N1))
2077 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2078
2079 if (SDValue Combined = visitADDLike(N0, N1, N))
2080 return Combined;
2081
2082 if (SDValue Combined = visitADDLike(N1, N0, N))
2083 return Combined;
2084
2085 return SDValue();
2086}
2087
2088static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2089 bool Masked = false;
2090
2091 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2092 while (true) {
2093 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2094 V = V.getOperand(0);
2095 continue;
2096 }
2097
2098 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2099 Masked = true;
2100 V = V.getOperand(0);
2101 continue;
2102 }
2103
2104 break;
2105 }
2106
2107 // If this is not a carry, return.
2108 if (V.getResNo() != 1)
2109 return SDValue();
2110
2111 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2112 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2113 return SDValue();
2114
2115 // If the result is masked, then no matter what kind of bool it is we can
2116 // return. If it isn't, then we need to make sure the bool type is either 0 or
2117 // 1 and not other values.
2118 if (Masked ||
2119 TLI.getBooleanContents(V.getValueType()) ==
2120 TargetLoweringBase::ZeroOrOneBooleanContent)
2121 return V;
2122
2123 return SDValue();
2124}
2125
2126SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2127 EVT VT = N0.getValueType();
2128 SDLoc DL(LocReference);
2129
2130 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2131 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2132 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2133 return DAG.getNode(ISD::SUB, DL, VT, N0,
2134 DAG.getNode(ISD::SHL, DL, VT,
2135 N1.getOperand(0).getOperand(1),
2136 N1.getOperand(1)));
2137
2138 if (N1.getOpcode() == ISD::AND) {
2139 SDValue AndOp0 = N1.getOperand(0);
2140 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2141 unsigned DestBits = VT.getScalarSizeInBits();
2142
2143 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2144 // and similar xforms where the inner op is either ~0 or 0.
2145 if (NumSignBits == DestBits &&
2146 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2147 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2148 }
2149
2150 // add (sext i1), X -> sub X, (zext i1)
2151 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2152 N0.getOperand(0).getValueType() == MVT::i1 &&
2153 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2154 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2155 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2156 }
2157
2158 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2159 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2160 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2161 if (TN->getVT() == MVT::i1) {
2162 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2163 DAG.getConstant(1, DL, VT));
2164 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2165 }
2166 }
2167
2168 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2169 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2170 N1.getResNo() == 0)
2171 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2172 N0, N1.getOperand(0), N1.getOperand(2));
2173
2174 // (add X, Carry) -> (addcarry X, 0, Carry)
2175 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2176 if (SDValue Carry = getAsCarry(TLI, N1))
2177 return DAG.getNode(ISD::ADDCARRY, DL,
2178 DAG.getVTList(VT, Carry.getValueType()), N0,
2179 DAG.getConstant(0, DL, VT), Carry);
2180
2181 return SDValue();
2182}
2183
2184SDValue DAGCombiner::visitADDC(SDNode *N) {
2185 SDValue N0 = N->getOperand(0);
2186 SDValue N1 = N->getOperand(1);
2187 EVT VT = N0.getValueType();
2188 SDLoc DL(N);
2189
2190 // If the flag result is dead, turn this into an ADD.
2191 if (!N->hasAnyUseOfValue(1))
2192 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2193 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2194
2195 // canonicalize constant to RHS.
2196 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2197 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2198 if (N0C && !N1C)
2199 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2200
2201 // fold (addc x, 0) -> x + no carry out
2202 if (isNullConstant(N1))
2203 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2204 DL, MVT::Glue));
2205
2206 // If it cannot overflow, transform into an add.
2207 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2208 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2209 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2210
2211 return SDValue();
2212}
2213
2214SDValue DAGCombiner::visitUADDO(SDNode *N) {
2215 SDValue N0 = N->getOperand(0);
2216 SDValue N1 = N->getOperand(1);
2217 EVT VT = N0.getValueType();
2218 if (VT.isVector())
2219 return SDValue();
2220
2221 EVT CarryVT = N->getValueType(1);
2222 SDLoc DL(N);
2223
2224 // If the flag result is dead, turn this into an ADD.
2225 if (!N->hasAnyUseOfValue(1))
2226 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2227 DAG.getUNDEF(CarryVT));
2228
2229 // canonicalize constant to RHS.
2230 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2231 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2232 if (N0C && !N1C)
2233 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2234
2235 // fold (uaddo x, 0) -> x + no carry out
2236 if (isNullConstant(N1))
2237 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2238
2239 // If it cannot overflow, transform into an add.
2240 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2241 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2242 DAG.getConstant(0, DL, CarryVT));
2243
2244 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2245 return Combined;
2246
2247 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2248 return Combined;
2249
2250 return SDValue();
2251}
2252
2253SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2254 auto VT = N0.getValueType();
2255
2256 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2257 // If Y + 1 cannot overflow.
2258 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2259 SDValue Y = N1.getOperand(0);
2260 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2261 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2262 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2263 N1.getOperand(2));
2264 }
2265
2266 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2267 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2268 if (SDValue Carry = getAsCarry(TLI, N1))
2269 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2270 DAG.getConstant(0, SDLoc(N), VT), Carry);
2271
2272 return SDValue();
2273}
2274
2275SDValue DAGCombiner::visitADDE(SDNode *N) {
2276 SDValue N0 = N->getOperand(0);
2277 SDValue N1 = N->getOperand(1);
2278 SDValue CarryIn = N->getOperand(2);
2279
2280 // canonicalize constant to RHS
2281 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2282 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2283 if (N0C && !N1C)
2284 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2285 N1, N0, CarryIn);
2286
2287 // fold (adde x, y, false) -> (addc x, y)
2288 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2289 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2290
2291 return SDValue();
2292}
2293
2294SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2295 SDValue N0 = N->getOperand(0);
2296 SDValue N1 = N->getOperand(1);
2297 SDValue CarryIn = N->getOperand(2);
2298 SDLoc DL(N);
2299
2300 // canonicalize constant to RHS
2301 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2302 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2303 if (N0C && !N1C)
2304 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2305
2306 // fold (addcarry x, y, false) -> (uaddo x, y)
2307 if (isNullConstant(CarryIn))
2308 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2309
2310 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2311 if (isNullConstant(N0) && isNullConstant(N1)) {
2312 EVT VT = N0.getValueType();
2313 EVT CarryVT = CarryIn.getValueType();
2314 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2315 AddToWorklist(CarryExt.getNode());
2316 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2317 DAG.getConstant(1, DL, VT)),
2318 DAG.getConstant(0, DL, CarryVT));
2319 }
2320
2321 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2322 return Combined;
2323
2324 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2325 return Combined;
2326
2327 return SDValue();
2328}
2329
2330SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2331 SDNode *N) {
2332 // Iff the flag result is dead:
2333 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2334 if ((N0.getOpcode() == ISD::ADD ||
2335 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2336 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2337 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2338 N0.getOperand(0), N0.getOperand(1), CarryIn);
2339
2340 /**
2341 * When one of the addcarry argument is itself a carry, we may be facing
2342 * a diamond carry propagation. In which case we try to transform the DAG
2343 * to ensure linear carry propagation if that is possible.
2344 *
2345 * We are trying to get:
2346 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2347 */
2348 if (auto Y = getAsCarry(TLI, N1)) {
2349 /**
2350 * (uaddo A, B)
2351 * / \
2352 * Carry Sum
2353 * | \
2354 * | (addcarry *, 0, Z)
2355 * | /
2356 * \ Carry
2357 * | /
2358 * (addcarry X, *, *)
2359 */
2360 if (Y.getOpcode() == ISD::UADDO &&
2361 CarryIn.getResNo() == 1 &&
2362 CarryIn.getOpcode() == ISD::ADDCARRY &&
2363 isNullConstant(CarryIn.getOperand(1)) &&
2364 CarryIn.getOperand(0) == Y.getValue(0)) {
2365 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2366 Y.getOperand(0), Y.getOperand(1),
2367 CarryIn.getOperand(2));
2368 AddToWorklist(NewY.getNode());
2369 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2370 DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2371 NewY.getValue(1));
2372 }
2373 }
2374
2375 return SDValue();
2376}
2377
2378// Since it may not be valid to emit a fold to zero for vector initializers
2379// check if we can before folding.
2380static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2381 SelectionDAG &DAG, bool LegalOperations,
2382 bool LegalTypes) {
2383 if (!VT.isVector())
2384 return DAG.getConstant(0, DL, VT);
2385 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2386 return DAG.getConstant(0, DL, VT);
2387 return SDValue();
2388}
2389
2390SDValue DAGCombiner::visitSUB(SDNode *N) {
2391 SDValue N0 = N->getOperand(0);
2392 SDValue N1 = N->getOperand(1);
2393 EVT VT = N0.getValueType();
2394 SDLoc DL(N);
2395
2396 // fold vector ops
2397 if (VT.isVector()) {
2398 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2399 return FoldedVOp;
2400
2401 // fold (sub x, 0) -> x, vector edition
2402 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2403 return N0;
2404 }
2405
2406 // fold (sub x, x) -> 0
2407 // FIXME: Refactor this and xor and other similar operations together.
2408 if (N0 == N1)
2409 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2410 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2411 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2412 // fold (sub c1, c2) -> c1-c2
2413 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2414 N1.getNode());
2415 }
2416
2417 if (SDValue NewSel = foldBinOpIntoSelect(N))
2418 return NewSel;
2419
2420 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2421
2422 // fold (sub x, c) -> (add x, -c)
2423 if (N1C) {
2424 return DAG.getNode(ISD::ADD, DL, VT, N0,
2425 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2426 }
2427
2428 if (isNullConstantOrNullSplatConstant(N0)) {
2429 unsigned BitWidth = VT.getScalarSizeInBits();
2430 // Right-shifting everything out but the sign bit followed by negation is
2431 // the same as flipping arithmetic/logical shift type without the negation:
2432 // -(X >>u 31) -> (X >>s 31)
2433 // -(X >>s 31) -> (X >>u 31)
2434 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2435 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2436 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2437 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2438 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2439 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2440 }
2441 }
2442
2443 // 0 - X --> 0 if the sub is NUW.
2444 if (N->getFlags().hasNoUnsignedWrap())
2445 return N0;
2446
2447 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2448 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2449 // N1 must be 0 because negating the minimum signed value is undefined.
2450 if (N->getFlags().hasNoSignedWrap())
2451 return N0;
2452
2453 // 0 - X --> X if X is 0 or the minimum signed value.
2454 return N1;
2455 }
2456 }
2457
2458 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2459 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2460 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2461
2462 // fold A-(A-B) -> B
2463 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2464 return N1.getOperand(1);
2465
2466 // fold (A+B)-A -> B
2467 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2468 return N0.getOperand(1);
2469
2470 // fold (A+B)-B -> A
2471 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2472 return N0.getOperand(0);
2473
2474 // fold C2-(A+C1) -> (C2-C1)-A
2475 if (N1.getOpcode() == ISD::ADD) {
2476 SDValue N11 = N1.getOperand(1);
2477 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2478 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2479 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2480 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2481 }
2482 }
2483
2484 // fold ((A+(B+or-C))-B) -> A+or-C
2485 if (N0.getOpcode() == ISD::ADD &&
2486 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2487 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2488 N0.getOperand(1).getOperand(0) == N1)
2489 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2490 N0.getOperand(1).getOperand(1));
2491
2492 // fold ((A+(C+B))-B) -> A+C
2493 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2494 N0.getOperand(1).getOperand(1) == N1)
2495 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2496 N0.getOperand(1).getOperand(0));
2497
2498 // fold ((A-(B-C))-C) -> A-B
2499 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2500 N0.getOperand(1).getOperand(1) == N1)
2501 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2502 N0.getOperand(1).getOperand(0));
2503
2504 // If either operand of a sub is undef, the result is undef
2505 if (N0.isUndef())
2506 return N0;
2507 if (N1.isUndef())
2508 return N1;
2509
2510 // If the relocation model supports it, consider symbol offsets.
2511 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2512 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2513 // fold (sub Sym, c) -> Sym-c
2514 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2515 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2516 GA->getOffset() -
2517 (uint64_t)N1C->getSExtValue());
2518 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2519 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2520 if (GA->getGlobal() == GB->getGlobal())
2521 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2522 DL, VT);
2523 }
2524
2525 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2526 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2527 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2528 if (TN->getVT() == MVT::i1) {
2529 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2530 DAG.getConstant(1, DL, VT));
2531 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2532 }
2533 }
2534
2535 return SDValue();
2536}
2537
2538SDValue DAGCombiner::visitSUBC(SDNode *N) {
2539 SDValue N0 = N->getOperand(0);
2540 SDValue N1 = N->getOperand(1);
2541 EVT VT = N0.getValueType();
2542 SDLoc DL(N);
2543
2544 // If the flag result is dead, turn this into an SUB.
2545 if (!N->hasAnyUseOfValue(1))
2546 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2547 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2548
2549 // fold (subc x, x) -> 0 + no borrow
2550 if (N0 == N1)
2551 return CombineTo(N, DAG.getConstant(0, DL, VT),
2552 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2553
2554 // fold (subc x, 0) -> x + no borrow
2555 if (isNullConstant(N1))
2556 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2557
2558 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2559 if (isAllOnesConstant(N0))
2560 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2561 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2562
2563 return SDValue();
2564}
2565
2566SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2567 SDValue N0 = N->getOperand(0);
2568 SDValue N1 = N->getOperand(1);
2569 EVT VT = N0.getValueType();
2570 if (VT.isVector())
2571 return SDValue();
2572
2573 EVT CarryVT = N->getValueType(1);
2574 SDLoc DL(N);
2575
2576 // If the flag result is dead, turn this into an SUB.
2577 if (!N->hasAnyUseOfValue(1))
2578 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2579 DAG.getUNDEF(CarryVT));
2580
2581 // fold (usubo x, x) -> 0 + no borrow
2582 if (N0 == N1)
2583 return CombineTo(N, DAG.getConstant(0, DL, VT),
2584 DAG.getConstant(0, DL, CarryVT));
2585
2586 // fold (usubo x, 0) -> x + no borrow
2587 if (isNullConstant(N1))
2588 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2589
2590 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2591 if (isAllOnesConstant(N0))
2592 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2593 DAG.getConstant(0, DL, CarryVT));
2594
2595 return SDValue();
2596}
2597
2598SDValue DAGCombiner::visitSUBE(SDNode *N) {
2599 SDValue N0 = N->getOperand(0);
2600 SDValue N1 = N->getOperand(1);
2601 SDValue CarryIn = N->getOperand(2);
2602
2603 // fold (sube x, y, false) -> (subc x, y)
2604 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2605 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2606
2607 return SDValue();
2608}
2609
2610SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2611 SDValue N0 = N->getOperand(0);
2612 SDValue N1 = N->getOperand(1);
2613 SDValue CarryIn = N->getOperand(2);
2614
2615 // fold (subcarry x, y, false) -> (usubo x, y)
2616 if (isNullConstant(CarryIn))
2617 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2618
2619 return SDValue();
2620}
2621
2622SDValue DAGCombiner::visitMUL(SDNode *N) {
2623 SDValue N0 = N->getOperand(0);
2624 SDValue N1 = N->getOperand(1);
2625 EVT VT = N0.getValueType();
2626
2627 // fold (mul x, undef) -> 0
2628 if (N0.isUndef() || N1.isUndef())
2629 return DAG.getConstant(0, SDLoc(N), VT);
2630
2631 bool N0IsConst = false;
2632 bool N1IsConst = false;
2633 bool N1IsOpaqueConst = false;
2634 bool N0IsOpaqueConst = false;
2635 APInt ConstValue0, ConstValue1;
2636 // fold vector ops
2637 if (VT.isVector()) {
2638 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2639 return FoldedVOp;
2640
2641 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2642 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2643 assert((!N0IsConst ||(static_cast <bool> ((!N0IsConst || ConstValue0.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N0IsConst || ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2645, __extension__ __PRETTY_FUNCTION__))
2644 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&(static_cast <bool> ((!N0IsConst || ConstValue0.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N0IsConst || ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2645, __extension__ __PRETTY_FUNCTION__))
2645 "Splat APInt should be element width")(static_cast <bool> ((!N0IsConst || ConstValue0.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N0IsConst || ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2645, __extension__ __PRETTY_FUNCTION__))
;
2646 assert((!N1IsConst ||(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2648, __extension__ __PRETTY_FUNCTION__))
2647 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2648, __extension__ __PRETTY_FUNCTION__))
2648 "Splat APInt should be element width")(static_cast <bool> ((!N1IsConst || ConstValue1.getBitWidth
() == VT.getScalarSizeInBits()) && "Splat APInt should be element width"
) ? void (0) : __assert_fail ("(!N1IsConst || ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && \"Splat APInt should be element width\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2648, __extension__ __PRETTY_FUNCTION__))
;
2649 } else {
2650 N0IsConst = isa<ConstantSDNode>(N0);
2651 if (N0IsConst) {
2652 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2653 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2654 }
2655 N1IsConst = isa<ConstantSDNode>(N1);
2656 if (N1IsConst) {
2657 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2658 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2659 }
2660 }
2661
2662 // fold (mul c1, c2) -> c1*c2
2663 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2664 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2665 N0.getNode(), N1.getNode());
2666
2667 // canonicalize constant to RHS (vector doesn't have to splat)
2668 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2669 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2670 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2671 // fold (mul x, 0) -> 0
2672 if (N1IsConst && ConstValue1.isNullValue())
2673 return N1;
2674 // fold (mul x, 1) -> x
2675 if (N1IsConst && ConstValue1.isOneValue())
2676 return N0;
2677
2678 if (SDValue NewSel = foldBinOpIntoSelect(N))
2679 return NewSel;
2680
2681 // fold (mul x, -1) -> 0-x
2682 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2683 SDLoc DL(N);
2684 return DAG.getNode(ISD::SUB, DL, VT,
2685 DAG.getConstant(0, DL, VT), N0);
2686 }
2687 // fold (mul x, (1 << c)) -> x << c
2688 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2689 DAG.isKnownToBeAPowerOfTwo(N1) &&
2690 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2691 SDLoc DL(N);
2692 SDValue LogBase2 = BuildLogBase2(N1, DL);
2693 AddToWorklist(LogBase2.getNode());
2694
2695 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2696 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2697 AddToWorklist(Trunc.getNode());
2698 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2699 }
2700 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2701 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2702 unsigned Log2Val = (-ConstValue1).logBase2();
2703 SDLoc DL(N);
2704 // FIXME: If the input is something that is easily negated (e.g. a
2705 // single-use add), we should put the negate there.
2706 return DAG.getNode(ISD::SUB, DL, VT,
2707 DAG.getConstant(0, DL, VT),
2708 DAG.getNode(ISD::SHL, DL, VT, N0,
2709 DAG.getConstant(Log2Val, DL,
2710 getShiftAmountTy(N0.getValueType()))));
2711 }
2712
2713 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2714 if (N0.getOpcode() == ISD::SHL &&
2715 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2716 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2717 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2718 if (isConstantOrConstantVector(C3))
2719 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2720 }
2721
2722 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2723 // use.
2724 {
2725 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2726
2727 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2728 if (N0.getOpcode() == ISD::SHL &&
2729 isConstantOrConstantVector(N0.getOperand(1)) &&
2730 N0.getNode()->hasOneUse()) {
2731 Sh = N0; Y = N1;
2732 } else if (N1.getOpcode() == ISD::SHL &&
2733 isConstantOrConstantVector(N1.getOperand(1)) &&
2734 N1.getNode()->hasOneUse()) {
2735 Sh = N1; Y = N0;
2736 }
2737
2738 if (Sh.getNode()) {
2739 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2740 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2741 }
2742 }
2743
2744 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2745 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2746 N0.getOpcode() == ISD::ADD &&
2747 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2748 isMulAddWithConstProfitable(N, N0, N1))
2749 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2750 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2751 N0.getOperand(0), N1),
2752 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2753 N0.getOperand(1), N1));
2754
2755 // reassociate mul
2756 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2757 return RMUL;
2758
2759 return SDValue();
2760}
2761
2762/// Return true if divmod libcall is available.
2763static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2764 const TargetLowering &TLI) {
2765 RTLIB::Libcall LC;
2766 EVT NodeType = Node->getValueType(0);
2767 if (!NodeType.isSimple())
2768 return false;
2769 switch (NodeType.getSimpleVT().SimpleTy) {
2770 default: return false; // No libcall for vector types.
2771 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2772 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2773 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2774 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2775 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2776 }
2777
2778 return TLI.getLibcallName(LC) != nullptr;
2779}
2780
2781/// Issue divrem if both quotient and remainder are needed.
2782SDValue DAGCombiner::useDivRem(SDNode *Node) {
2783 if (Node->use_empty())
2784 return SDValue(); // This is a dead node, leave it alone.
2785
2786 unsigned Opcode = Node->getOpcode();
2787 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2788 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2789
2790 // DivMod lib calls can still work on non-legal types if using lib-calls.
2791 EVT VT = Node->getValueType(0);
2792 if (VT.isVector() || !VT.isInteger())
2793 return SDValue();
2794
2795 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2796 return SDValue();
2797
2798 // If DIVREM is going to get expanded into a libcall,
2799 // but there is no libcall available, then don't combine.
2800 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2801 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2802 return SDValue();
2803
2804 // If div is legal, it's better to do the normal expansion
2805 unsigned OtherOpcode = 0;
2806 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2807 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2808 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2809 return SDValue();
2810 } else {
2811 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2812 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2813 return SDValue();
2814 }
2815
2816 SDValue Op0 = Node->getOperand(0);
2817 SDValue Op1 = Node->getOperand(1);
2818 SDValue combined;
2819 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2820 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2821 SDNode *User = *UI;
2822 if (User == Node || User->use_empty())
2823 continue;
2824 // Convert the other matching node(s), too;
2825 // otherwise, the DIVREM may get target-legalized into something
2826 // target-specific that we won't be able to recognize.
2827 unsigned UserOpc = User->getOpcode();
2828 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2829 User->getOperand(0) == Op0 &&
2830 User->getOperand(1) == Op1) {
2831 if (!combined) {
2832 if (UserOpc == OtherOpcode) {
2833 SDVTList VTs = DAG.getVTList(VT, VT);
2834 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2835 } else if (UserOpc == DivRemOpc) {
2836 combined = SDValue(User, 0);
2837 } else {
2838 assert(UserOpc == Opcode)(static_cast <bool> (UserOpc == Opcode) ? void (0) : __assert_fail
("UserOpc == Opcode", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 2838, __extension__ __PRETTY_FUNCTION__))
;
2839 continue;
2840 }
2841 }
2842 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2843 CombineTo(User, combined);
2844 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2845 CombineTo(User, combined.getValue(1));
2846 }
2847 }
2848 return combined;
2849}
2850
2851static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2852 SDValue N0 = N->getOperand(0);
2853 SDValue N1 = N->getOperand(1);
2854 EVT VT = N->getValueType(0);
2855 SDLoc DL(N);
2856
2857 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2858 return DAG.getUNDEF(VT);
2859
2860 // undef / X -> 0
2861 // undef % X -> 0
2862 if (N0.isUndef())
2863 return DAG.getConstant(0, DL, VT);
2864
2865 return SDValue();
2866}
2867
2868SDValue DAGCombiner::visitSDIV(SDNode *N) {
2869 SDValue N0 = N->getOperand(0);
2870 SDValue N1 = N->getOperand(1);
2871 EVT VT = N->getValueType(0);
2872
2873 // fold vector ops
2874 if (VT.isVector())
2875 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2876 return FoldedVOp;
2877
2878 SDLoc DL(N);
2879
2880 // fold (sdiv c1, c2) -> c1/c2
2881 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2882 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2883 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2884 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2885 // fold (sdiv X, 1) -> X
2886 if (N1C && N1C->isOne())
2887 return N0;
2888 // fold (sdiv X, -1) -> 0-X
2889 if (N1C && N1C->isAllOnesValue())
2890 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2891
2892 if (SDValue V = simplifyDivRem(N, DAG))
2893 return V;
2894
2895 if (SDValue NewSel = foldBinOpIntoSelect(N))
2896 return NewSel;
2897
2898 // If we know the sign bits of both operands are zero, strength reduce to a
2899 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2900 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2901 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2902
2903 // fold (sdiv X, pow2) -> simple ops after legalize
2904 // FIXME: We check for the exact bit here because the generic lowering gives
2905 // better results in that case. The target-specific lowering should learn how
2906 // to handle exact sdivs efficiently.
2907 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2908 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2909 (-N1C->getAPIntValue()).isPowerOf2())) {
2910 // Target-specific implementation of sdiv x, pow2.
2911 if (SDValue Res = BuildSDIVPow2(N))
2912 return Res;
2913
2914 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2915
2916 // Splat the sign bit into the register
2917 SDValue SGN =
2918 DAG.getNode(ISD::SRA, DL, VT, N0,
2919 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2920 getShiftAmountTy(N0.getValueType())));
2921 AddToWorklist(SGN.getNode());
2922
2923 // Add (N0 < 0) ? abs2 - 1 : 0;
2924 SDValue SRL =
2925 DAG.getNode(ISD::SRL, DL, VT, SGN,
2926 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2927 getShiftAmountTy(SGN.getValueType())));
2928 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2929 AddToWorklist(SRL.getNode());
2930 AddToWorklist(ADD.getNode()); // Divide by pow2
2931 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2932 DAG.getConstant(lg2, DL,
2933 getShiftAmountTy(ADD.getValueType())));
2934
2935 // If we're dividing by a positive value, we're done. Otherwise, we must
2936 // negate the result.
2937 if (N1C->getAPIntValue().isNonNegative())
2938 return SRA;
2939
2940 AddToWorklist(SRA.getNode());
2941 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2942 }
2943
2944 // If integer divide is expensive and we satisfy the requirements, emit an
2945 // alternate sequence. Targets may check function attributes for size/speed
2946 // trade-offs.
2947 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2948 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2949 if (SDValue Op = BuildSDIV(N))
2950 return Op;
2951
2952 // sdiv, srem -> sdivrem
2953 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2954 // true. Otherwise, we break the simplification logic in visitREM().
2955 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2956 if (SDValue DivRem = useDivRem(N))
2957 return DivRem;
2958
2959 return SDValue();
2960}
2961
2962SDValue DAGCombiner::visitUDIV(SDNode *N) {
2963 SDValue N0 = N->getOperand(0);
2964 SDValue N1 = N->getOperand(1);
2965 EVT VT = N->getValueType(0);
2966
2967 // fold vector ops
2968 if (VT.isVector())
2969 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2970 return FoldedVOp;
2971
2972 SDLoc DL(N);
2973
2974 // fold (udiv c1, c2) -> c1/c2
2975 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2976 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2977 if (N0C && N1C)
2978 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2979 N0C, N1C))
2980 return Folded;
2981
2982 if (SDValue V = simplifyDivRem(N, DAG))
2983 return V;
2984
2985 if (SDValue NewSel = foldBinOpIntoSelect(N))
2986 return NewSel;
2987
2988 // fold (udiv x, (1 << c)) -> x >>u c
2989 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2990 DAG.isKnownToBeAPowerOfTwo(N1)) {
2991 SDValue LogBase2 = BuildLogBase2(N1, DL);
2992 AddToWorklist(LogBase2.getNode());
2993
2994 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2995 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2996 AddToWorklist(Trunc.getNode());
2997 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2998 }
2999
3000 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3001 if (N1.getOpcode() == ISD::SHL) {
3002 SDValue N10 = N1.getOperand(0);
3003 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3004 DAG.isKnownToBeAPowerOfTwo(N10)) {
3005 SDValue LogBase2 = BuildLogBase2(N10, DL);
3006 AddToWorklist(LogBase2.getNode());
3007
3008 EVT ADDVT = N1.getOperand(1).getValueType();
3009 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3010 AddToWorklist(Trunc.getNode());
3011 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3012 AddToWorklist(Add.getNode());
3013 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3014 }
3015 }
3016
3017 // fold (udiv x, c) -> alternate
3018 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3019 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3020 if (SDValue Op = BuildUDIV(N))
3021 return Op;
3022
3023 // sdiv, srem -> sdivrem
3024 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3025 // true. Otherwise, we break the simplification logic in visitREM().
3026 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3027 if (SDValue DivRem = useDivRem(N))
3028 return DivRem;
3029
3030 return SDValue();
3031}
3032
3033// handles ISD::SREM and ISD::UREM
3034SDValue DAGCombiner::visitREM(SDNode *N) {
3035 unsigned Opcode = N->getOpcode();
3036 SDValue N0 = N->getOperand(0);
3037 SDValue N1 = N->getOperand(1);
3038 EVT VT = N->getValueType(0);
3039 bool isSigned = (Opcode == ISD::SREM);
3040 SDLoc DL(N);
3041
3042 // fold (rem c1, c2) -> c1%c2
3043 ConstantSDNode *N0C = isConstOrConstSplat(N0);
3044 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3045 if (N0C && N1C)
3046 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3047 return Folded;
3048
3049 if (SDValue V = simplifyDivRem(N, DAG))
3050 return V;
3051
3052 if (SDValue NewSel = foldBinOpIntoSelect(N))
3053 return NewSel;
3054
3055 if (isSigned) {
3056 // If we know the sign bits of both operands are zero, strength reduce to a
3057 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3058 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3059 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3060 } else {
3061 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3062 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3063 // fold (urem x, pow2) -> (and x, pow2-1)
3064 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3065 AddToWorklist(Add.getNode());
3066 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3067 }
3068 if (N1.getOpcode() == ISD::SHL &&
3069 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3070 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3071 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3072 AddToWorklist(Add.getNode());
3073 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3074 }
3075 }
3076
3077 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3078
3079 // If X/C can be simplified by the division-by-constant logic, lower
3080 // X%C to the equivalent of X-X/C*C.
3081 // To avoid mangling nodes, this simplification requires that the combine()
3082 // call for the speculative DIV must not cause a DIVREM conversion. We guard
3083 // against this by skipping the simplification if isIntDivCheap(). When
3084 // div is not cheap, combine will not return a DIVREM. Regardless,
3085 // checking cheapness here makes sense since the simplification results in
3086 // fatter code.
3087 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3088 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3089 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3090 AddToWorklist(Div.getNode());
3091 SDValue OptimizedDiv = combine(Div.getNode());
3092 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3093 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&(static_cast <bool> ((OptimizedDiv.getOpcode() != ISD::
UDIVREM) && (OptimizedDiv.getOpcode() != ISD::SDIVREM
)) ? void (0) : __assert_fail ("(OptimizedDiv.getOpcode() != ISD::UDIVREM) && (OptimizedDiv.getOpcode() != ISD::SDIVREM)"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
3094 (OptimizedDiv.getOpcode() != ISD::SDIVREM))(static_cast <bool> ((OptimizedDiv.getOpcode() != ISD::
UDIVREM) && (OptimizedDiv.getOpcode() != ISD::SDIVREM
)) ? void (0) : __assert_fail ("(OptimizedDiv.getOpcode() != ISD::UDIVREM) && (OptimizedDiv.getOpcode() != ISD::SDIVREM)"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
;
3095 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3096 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3097 AddToWorklist(Mul.getNode());
3098 return Sub;
3099 }
3100 }
3101
3102 // sdiv, srem -> sdivrem
3103 if (SDValue DivRem = useDivRem(N))
3104 return DivRem.getValue(1);
3105
3106 return SDValue();
3107}
3108
3109SDValue DAGCombiner::visitMULHS(SDNode *N) {
3110 SDValue N0 = N->getOperand(0);
3111 SDValue N1 = N->getOperand(1);
3112 EVT VT = N->getValueType(0);
3113 SDLoc DL(N);
3114
3115 if (VT.isVector()) {
3116 // fold (mulhs x, 0) -> 0
3117 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3118 return N1;
3119 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3120 return N0;
3121 }
3122
3123 // fold (mulhs x, 0) -> 0
3124 if (isNullConstant(N1))
3125 return N1;
3126 // fold (mulhs x, 1) -> (sra x, size(x)-1)
3127 if (isOneConstant(N1))
3128 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3129 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3130 getShiftAmountTy(N0.getValueType())));
3131
3132 // fold (mulhs x, undef) -> 0
3133 if (N0.isUndef() || N1.isUndef())
3134 return DAG.getConstant(0, DL, VT);
3135
3136 // If the type twice as wide is legal, transform the mulhs to a wider multiply
3137 // plus a shift.
3138 if (VT.isSimple() && !VT.isVector()) {
3139 MVT Simple = VT.getSimpleVT();
3140 unsigned SimpleSize = Simple.getSizeInBits();
3141 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3142 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3143 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3144 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3145 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3146 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3147 DAG.getConstant(SimpleSize, DL,
3148 getShiftAmountTy(N1.getValueType())));
3149 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3150 }
3151 }
3152
3153 return SDValue();
3154}
3155
3156SDValue DAGCombiner::visitMULHU(SDNode *N) {
3157 SDValue N0 = N->getOperand(0);
3158 SDValue N1 = N->getOperand(1);
3159 EVT VT = N->getValueType(0);
3160 SDLoc DL(N);
3161
3162 if (VT.isVector()) {
3163 // fold (mulhu x, 0) -> 0
3164 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3165 return N1;
3166 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3167 return N0;
3168 }
3169
3170 // fold (mulhu x, 0) -> 0
3171 if (isNullConstant(N1))
3172 return N1;
3173 // fold (mulhu x, 1) -> 0
3174 if (isOneConstant(N1))
3175 return DAG.getConstant(0, DL, N0.getValueType());
3176 // fold (mulhu x, undef) -> 0
3177 if (N0.isUndef() || N1.isUndef())
3178 return DAG.getConstant(0, DL, VT);
3179
3180 // If the type twice as wide is legal, transform the mulhu to a wider multiply
3181 // plus a shift.
3182 if (VT.isSimple() && !VT.isVector()) {
3183 MVT Simple = VT.getSimpleVT();
3184 unsigned SimpleSize = Simple.getSizeInBits();
3185 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3186 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3187 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3188 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3189 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3190 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3191 DAG.getConstant(SimpleSize, DL,
3192 getShiftAmountTy(N1.getValueType())));
3193 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3194 }
3195 }
3196
3197 return SDValue();
3198}
3199
3200/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3201/// give the opcodes for the two computations that are being performed. Return
3202/// true if a simplification was made.
3203SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3204 unsigned HiOp) {
3205 // If the high half is not needed, just compute the low half.
3206 bool HiExists = N->hasAnyUseOfValue(1);
3207 if (!HiExists &&
3208 (!LegalOperations ||
3209 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3210 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3211 return CombineTo(N, Res, Res);
3212 }
3213
3214 // If the low half is not needed, just compute the high half.
3215 bool LoExists = N->hasAnyUseOfValue(0);
3216 if (!LoExists &&
3217 (!LegalOperations ||
3218 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3219 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3220 return CombineTo(N, Res, Res);
3221 }
3222
3223 // If both halves are used, return as it is.
3224 if (LoExists && HiExists)
3225 return SDValue();
3226
3227 // If the two computed results can be simplified separately, separate them.
3228 if (LoExists) {
3229 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3230 AddToWorklist(Lo.getNode());
3231 SDValue LoOpt = combine(Lo.getNode());
3232 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3233 (!LegalOperations ||
3234 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3235 return CombineTo(N, LoOpt, LoOpt);
3236 }
3237
3238 if (HiExists) {
3239 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3240 AddToWorklist(Hi.getNode());
3241 SDValue HiOpt = combine(Hi.getNode());
3242 if (HiOpt.getNode() && HiOpt != Hi &&
3243 (!LegalOperations ||
3244 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3245 return CombineTo(N, HiOpt, HiOpt);
3246 }
3247
3248 return SDValue();
3249}
3250
3251SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3252 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3253 return Res;
3254
3255 EVT VT = N->getValueType(0);
3256 SDLoc DL(N);
3257
3258 // If the type is twice as wide is legal, transform the mulhu to a wider
3259 // multiply plus a shift.
3260 if (VT.isSimple() && !VT.isVector()) {
3261 MVT Simple = VT.getSimpleVT();
3262 unsigned SimpleSize = Simple.getSizeInBits();
3263 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3264 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3265 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3266 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3267 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3268 // Compute the high part as N1.
3269 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3270 DAG.getConstant(SimpleSize, DL,
3271 getShiftAmountTy(Lo.getValueType())));
3272 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3273 // Compute the low part as N0.
3274 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3275 return CombineTo(N, Lo, Hi);
3276 }
3277 }
3278
3279 return SDValue();
3280}
3281
3282SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3283 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3284 return Res;
3285
3286 EVT VT = N->getValueType(0);
3287 SDLoc DL(N);
3288
3289 // If the type is twice as wide is legal, transform the mulhu to a wider
3290 // multiply plus a shift.
3291 if (VT.isSimple() && !VT.isVector()) {
3292 MVT Simple = VT.getSimpleVT();
3293 unsigned SimpleSize = Simple.getSizeInBits();
3294 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3295 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3296 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3297 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3298 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3299 // Compute the high part as N1.
3300 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3301 DAG.getConstant(SimpleSize, DL,
3302 getShiftAmountTy(Lo.getValueType())));
3303 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3304 // Compute the low part as N0.
3305 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3306 return CombineTo(N, Lo, Hi);
3307 }
3308 }
3309
3310 return SDValue();
3311}
3312
3313SDValue DAGCombiner::visitSMULO(SDNode *N) {
3314 // (smulo x, 2) -> (saddo x, x)
3315 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3316 if (C2->getAPIntValue() == 2)
3317 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3318 N->getOperand(0), N->getOperand(0));
3319
3320 return SDValue();
3321}
3322
3323SDValue DAGCombiner::visitUMULO(SDNode *N) {
3324 // (umulo x, 2) -> (uaddo x, x)
3325 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3326 if (C2->getAPIntValue() == 2)
3327 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3328 N->getOperand(0), N->getOperand(0));
3329
3330 return SDValue();
3331}
3332
3333SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3334 SDValue N0 = N->getOperand(0);
3335 SDValue N1 = N->getOperand(1);
3336 EVT VT = N0.getValueType();
3337
3338 // fold vector ops
3339 if (VT.isVector())
3340 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3341 return FoldedVOp;
3342
3343 // fold operation with constant operands.
3344 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3345 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3346 if (N0C && N1C)
3347 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3348
3349 // canonicalize constant to RHS
3350 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3351 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3352 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3353
3354 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
3355 // Only do this if the current op isn't legal and the flipped is.
3356 unsigned Opcode = N->getOpcode();
3357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3358 if (!TLI.isOperationLegal(Opcode, VT) &&
3359 (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
3360 (N1.isUndef() || DAG.SignBitIsZero(N1))) {
3361 unsigned AltOpcode;
3362 switch (Opcode) {
3363 case ISD::SMIN: AltOpcode = ISD::UMIN; break;
3364 case ISD::SMAX: AltOpcode = ISD::UMAX; break;
3365 case ISD::UMIN: AltOpcode = ISD::SMIN; break;
3366 case ISD::UMAX: AltOpcode = ISD::SMAX; break;
3367 default: llvm_unreachable("Unknown MINMAX opcode")::llvm::llvm_unreachable_internal("Unknown MINMAX opcode", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3367)
;
3368 }
3369 if (TLI.isOperationLegal(AltOpcode, VT))
3370 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
3371 }
3372
3373 return SDValue();
3374}
3375
3376/// If this is a binary operator with two operands of the same opcode, try to
3377/// simplify it.
3378SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3379 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3380 EVT VT = N0.getValueType();
3381 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!")(static_cast <bool> (N0.getOpcode() == N1.getOpcode() &&
"Bad input!") ? void (0) : __assert_fail ("N0.getOpcode() == N1.getOpcode() && \"Bad input!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3381, __extension__ __PRETTY_FUNCTION__))
;
3382
3383 // Bail early if none of these transforms apply.
3384 if (N0.getNumOperands() == 0) return SDValue();
3385
3386 // For each of OP in AND/OR/XOR:
3387 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3388 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3389 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3390 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3391 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3392 //
3393 // do not sink logical op inside of a vector extend, since it may combine
3394 // into a vsetcc.
3395 EVT Op0VT = N0.getOperand(0).getValueType();
3396 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3397 N0.getOpcode() == ISD::SIGN_EXTEND ||
3398 N0.getOpcode() == ISD::BSWAP ||
3399 // Avoid infinite looping with PromoteIntBinOp.
3400 (N0.getOpcode() == ISD::ANY_EXTEND &&
3401 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3402 (N0.getOpcode() == ISD::TRUNCATE &&
3403 (!TLI.isZExtFree(VT, Op0VT) ||
3404 !TLI.isTruncateFree(Op0VT, VT)) &&
3405 TLI.isTypeLegal(Op0VT))) &&
3406 !VT.isVector() &&
3407 Op0VT == N1.getOperand(0).getValueType() &&
3408 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3409 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3410 N0.getOperand(0).getValueType(),
3411 N0.getOperand(0), N1.getOperand(0));
3412 AddToWorklist(ORNode.getNode());
3413 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3414 }
3415
3416 // For each of OP in SHL/SRL/SRA/AND...
3417 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3418 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3419 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3420 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3421 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3422 N0.getOperand(1) == N1.getOperand(1)) {
3423 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3424 N0.getOperand(0).getValueType(),
3425 N0.getOperand(0), N1.getOperand(0));
3426 AddToWorklist(ORNode.getNode());
3427 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3428 ORNode, N0.getOperand(1));
3429 }
3430
3431 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3432 // Only perform this optimization up until type legalization, before
3433 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3434 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3435 // we don't want to undo this promotion.
3436 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3437 // on scalars.
3438 if ((N0.getOpcode() == ISD::BITCAST ||
3439 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3440 Level <= AfterLegalizeTypes) {
3441 SDValue In0 = N0.getOperand(0);
3442 SDValue In1 = N1.getOperand(0);
3443 EVT In0Ty = In0.getValueType();
3444 EVT In1Ty = In1.getValueType();
3445 SDLoc DL(N);
3446 // If both incoming values are integers, and the original types are the
3447 // same.
3448 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3449 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3450 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3451 AddToWorklist(Op.getNode());
3452 return BC;
3453 }
3454 }
3455
3456 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3457 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3458 // If both shuffles use the same mask, and both shuffle within a single
3459 // vector, then it is worthwhile to move the swizzle after the operation.
3460 // The type-legalizer generates this pattern when loading illegal
3461 // vector types from memory. In many cases this allows additional shuffle
3462 // optimizations.
3463 // There are other cases where moving the shuffle after the xor/and/or
3464 // is profitable even if shuffles don't perform a swizzle.
3465 // If both shuffles use the same mask, and both shuffles have the same first
3466 // or second operand, then it might still be profitable to move the shuffle
3467 // after the xor/and/or operation.
3468 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3469 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3470 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3471
3472 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&(static_cast <bool> (N0.getOperand(0).getValueType() ==
N1.getOperand(0).getValueType() && "Inputs to shuffles are not the same type"
) ? void (0) : __assert_fail ("N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && \"Inputs to shuffles are not the same type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3473, __extension__ __PRETTY_FUNCTION__))
3473 "Inputs to shuffles are not the same type")(static_cast <bool> (N0.getOperand(0).getValueType() ==
N1.getOperand(0).getValueType() && "Inputs to shuffles are not the same type"
) ? void (0) : __assert_fail ("N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && \"Inputs to shuffles are not the same type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3473, __extension__ __PRETTY_FUNCTION__))
;
3474
3475 // Check that both shuffles use the same mask. The masks are known to be of
3476 // the same length because the result vector type is the same.
3477 // Check also that shuffles have only one use to avoid introducing extra
3478 // instructions.
3479 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3480 SVN0->getMask().equals(SVN1->getMask())) {
3481 SDValue ShOp = N0->getOperand(1);
3482
3483 // Don't try to fold this node if it requires introducing a
3484 // build vector of all zeros that might be illegal at this stage.
3485 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3486 if (!LegalTypes)
3487 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3488 else
3489 ShOp = SDValue();
3490 }
3491
3492 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3493 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3494 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3495 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3496 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3497 N0->getOperand(0), N1->getOperand(0));
3498 AddToWorklist(NewNode.getNode());
3499 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3500 SVN0->getMask());
3501 }
3502
3503 // Don't try to fold this node if it requires introducing a
3504 // build vector of all zeros that might be illegal at this stage.
3505 ShOp = N0->getOperand(0);
3506 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3507 if (!LegalTypes)
3508 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3509 else
3510 ShOp = SDValue();
3511 }
3512
3513 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3514 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3515 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3516 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3517 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3518 N0->getOperand(1), N1->getOperand(1));
3519 AddToWorklist(NewNode.getNode());
3520 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3521 SVN0->getMask());
3522 }
3523 }
3524 }
3525
3526 return SDValue();
3527}
3528
3529/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3530SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3531 const SDLoc &DL) {
3532 SDValue LL, LR, RL, RR, N0CC, N1CC;
3533 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3534 !isSetCCEquivalent(N1, RL, RR, N1CC))
3535 return SDValue();
3536
3537 assert(N0.getValueType() == N1.getValueType() &&(static_cast <bool> (N0.getValueType() == N1.getValueType
() && "Unexpected operand types for bitwise logic op"
) ? void (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3538, __extension__ __PRETTY_FUNCTION__))
3538 "Unexpected operand types for bitwise logic op")(static_cast <bool> (N0.getValueType() == N1.getValueType
() && "Unexpected operand types for bitwise logic op"
) ? void (0) : __assert_fail ("N0.getValueType() == N1.getValueType() && \"Unexpected operand types for bitwise logic op\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3538, __extension__ __PRETTY_FUNCTION__))
;
3539 assert(LL.getValueType() == LR.getValueType() &&(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3541, __extension__ __PRETTY_FUNCTION__))
3540 RL.getValueType() == RR.getValueType() &&(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3541, __extension__ __PRETTY_FUNCTION__))
3541 "Unexpected operand types for setcc")(static_cast <bool> (LL.getValueType() == LR.getValueType
() && RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc") ? void (0) : __assert_fail
("LL.getValueType() == LR.getValueType() && RL.getValueType() == RR.getValueType() && \"Unexpected operand types for setcc\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3541, __extension__ __PRETTY_FUNCTION__))
;
3542
3543 // If we're here post-legalization or the logic op type is not i1, the logic
3544 // op type must match a setcc result type. Also, all folds require new
3545 // operations on the left and right operands, so those types must match.
3546 EVT VT = N0.getValueType();
3547 EVT OpVT = LL.getValueType();
3548 if (LegalOperations || VT.getScalarType() != MVT::i1)
3549 if (VT != getSetCCResultType(OpVT))
3550 return SDValue();
3551 if (OpVT != RL.getValueType())
3552 return SDValue();
3553
3554 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3555 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3556 bool IsInteger = OpVT.isInteger();
3557 if (LR == RR && CC0 == CC1 && IsInteger) {
3558 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3559 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3560
3561 // All bits clear?
3562 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3563 // All sign bits clear?
3564 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3565 // Any bits set?
3566 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3567 // Any sign bits set?
3568 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3569
3570 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3571 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3572 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3573 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3574 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3575 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3576 AddToWorklist(Or.getNode());
3577 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3578 }
3579
3580 // All bits set?
3581 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3582 // All sign bits set?
3583 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3584 // Any bits clear?
3585 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3586 // Any sign bits clear?
3587 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3588
3589 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3590 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3591 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3592 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3593 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3594 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3595 AddToWorklist(And.getNode());
3596 return DAG.getSetCC(DL, VT, And, LR, CC1);
3597 }
3598 }
3599
3600 // TODO: What is the 'or' equivalent of this fold?
3601 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3602 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
3603 IsInteger && CC0 == ISD::SETNE &&
3604 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3605 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3606 SDValue One = DAG.getConstant(1, DL, OpVT);
3607 SDValue Two = DAG.getConstant(2, DL, OpVT);
3608 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3609 AddToWorklist(Add.getNode());
3610 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3611 }
3612
3613 // Try more general transforms if the predicates match and the only user of
3614 // the compares is the 'and' or 'or'.
3615 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3616 N0.hasOneUse() && N1.hasOneUse()) {
3617 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3618 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3619 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3620 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3621 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3622 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3623 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3624 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3625 }
3626 }
3627
3628 // Canonicalize equivalent operands to LL == RL.
3629 if (LL == RR && LR == RL) {
3630 CC1 = ISD::getSetCCSwappedOperands(CC1);
3631 std::swap(RL, RR);
3632 }
3633
3634 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3635 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3636 if (LL == RL && LR == RR) {
3637 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3638 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3639 if (NewCC != ISD::SETCC_INVALID &&
3640 (!LegalOperations ||
3641 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3642 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3643 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3644 }
3645
3646 return SDValue();
3647}
3648
3649/// This contains all DAGCombine rules which reduce two values combined by
3650/// an And operation to a single value. This makes them reusable in the context
3651/// of visitSELECT(). Rules involving constants are not included as
3652/// visitSELECT() already handles those cases.
3653SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3654 EVT VT = N1.getValueType();
3655 SDLoc DL(N);
3656
3657 // fold (and x, undef) -> 0
3658 if (N0.isUndef() || N1.isUndef())
3659 return DAG.getConstant(0, DL, VT);
3660
3661 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3662 return V;
3663
3664 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3665 VT.getSizeInBits() <= 64) {
3666 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3667 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3668 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3669 // immediate for an add, but it is legal if its top c2 bits are set,
3670 // transform the ADD so the immediate doesn't need to be materialized
3671 // in a register.
3672 APInt ADDC = ADDI->getAPIntValue();
3673 APInt SRLC = SRLI->getAPIntValue();
3674 if (ADDC.getMinSignedBits() <= 64 &&
3675 SRLC.ult(VT.getSizeInBits()) &&
3676 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3677 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3678 SRLC.getZExtValue());
3679 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3680 ADDC |= Mask;
3681 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3682 SDLoc DL0(N0);
3683 SDValue NewAdd =
3684 DAG.getNode(ISD::ADD, DL0, VT,
3685 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3686 CombineTo(N0.getNode(), NewAdd);
3687 // Return N so it doesn't get rechecked!
3688 return SDValue(N, 0);
3689 }
3690 }
3691 }
3692 }
3693 }
3694 }
3695
3696 // Reduce bit extract of low half of an integer to the narrower type.
3697 // (and (srl i64:x, K), KMask) ->
3698 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3699 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3700 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3701 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3702 unsigned Size = VT.getSizeInBits();
3703 const APInt &AndMask = CAnd->getAPIntValue();
3704 unsigned ShiftBits = CShift->getZExtValue();
3705
3706 // Bail out, this node will probably disappear anyway.
3707 if (ShiftBits == 0)
3708 return SDValue();
3709
3710 unsigned MaskBits = AndMask.countTrailingOnes();
3711 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3712
3713 if (AndMask.isMask() &&
3714 // Required bits must not span the two halves of the integer and
3715 // must fit in the half size type.
3716 (ShiftBits + MaskBits <= Size / 2) &&
3717 TLI.isNarrowingProfitable(VT, HalfVT) &&
3718 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3719 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3720 TLI.isTruncateFree(VT, HalfVT) &&
3721 TLI.isZExtFree(HalfVT, VT)) {
3722 // The isNarrowingProfitable is to avoid regressions on PPC and
3723 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3724 // on downstream users of this. Those patterns could probably be
3725 // extended to handle extensions mixed in.
3726
3727 SDValue SL(N0);
3728 assert(MaskBits <= Size)(static_cast <bool> (MaskBits <= Size) ? void (0) : __assert_fail
("MaskBits <= Size", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3728, __extension__ __PRETTY_FUNCTION__))
;
3729
3730 // Extracting the highest bit of the low half.
3731 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3732 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3733 N0.getOperand(0));
3734
3735 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3736 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3737 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3738 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3739 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3740 }
3741 }
3742 }
3743 }
3744
3745 return SDValue();
3746}
3747
3748bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3749 EVT LoadResultTy, EVT &ExtVT) {
3750 if (!AndC->getAPIntValue().isMask())
3751 return false;
3752
3753 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3754
3755 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3756 EVT LoadedVT = LoadN->getMemoryVT();
3757
3758 if (ExtVT == LoadedVT &&
3759 (!LegalOperations ||
3760 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3761 // ZEXTLOAD will match without needing to change the size of the value being
3762 // loaded.
3763 return true;
3764 }
3765
3766 // Do not change the width of a volatile load.
3767 if (LoadN->isVolatile())
3768 return false;
3769
3770 // Do not generate loads of non-round integer types since these can
3771 // be expensive (and would be wrong if the type is not byte sized).
3772 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3773 return false;
3774
3775 if (LegalOperations &&
3776 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3777 return false;
3778
3779 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3780 return false;
3781
3782 return true;
3783}
3784
3785bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3786 EVT &ExtVT, unsigned ShAmt) {
3787 // Don't transform one with multiple uses, this would require adding a new
3788 // load.
3789 if (!SDValue(LoadN, 0).hasOneUse())
3790 return false;
3791
3792 if (LegalOperations &&
3793 !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3794 return false;
3795
3796 // Do not generate loads of non-round integer types since these can
3797 // be expensive (and would be wrong if the type is not byte sized).
3798 if (!ExtVT.isRound())
3799 return false;
3800
3801 // Don't change the width of a volatile load.
3802 if (LoadN->isVolatile())
3803 return false;
3804
3805 // Verify that we are actually reducing a load width here.
3806 if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3807 return false;
3808
3809 // For the transform to be legal, the load must produce only two values
3810 // (the value loaded and the chain). Don't transform a pre-increment
3811 // load, for example, which produces an extra value. Otherwise the
3812 // transformation is not equivalent, and the downstream logic to replace
3813 // uses gets things wrong.
3814 if (LoadN->getNumValues() > 2)
3815 return false;
3816
3817 // If the load that we're shrinking is an extload and we're not just
3818 // discarding the extension we can't simply shrink the load. Bail.
3819 // TODO: It would be possible to merge the extensions in some cases.
3820 if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3821 LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3822 return false;
3823
3824 if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3825 return false;
3826
3827 // It's not possible to generate a constant of extended or untyped type.
3828 EVT PtrType = LoadN->getOperand(1).getValueType();
3829 if (PtrType == MVT::Untyped || PtrType.isExtended())
3830 return false;
3831
3832 return true;
3833}
3834
3835bool DAGCombiner::SearchForAndLoads(SDNode *N,
3836 SmallPtrSetImpl<LoadSDNode*> &Loads,
3837 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3838 ConstantSDNode *Mask,
3839 SDNode *&NodeToMask) {
3840 // Recursively search for the operands, looking for loads which can be
3841 // narrowed.
3842 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3843 SDValue Op = N->getOperand(i);
3844
3845 if (Op.getValueType().isVector())
3846 return false;
3847
3848 // Some constants may need fixing up later if they are too large.
3849 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3850 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3851 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3852 NodesWithConsts.insert(N);
3853 continue;
3854 }
3855
3856 if (!Op.hasOneUse())
3857 return false;
3858
3859 switch(Op.getOpcode()) {
3860 case ISD::LOAD: {
3861 auto *Load = cast<LoadSDNode>(Op);
3862 EVT ExtVT;
3863 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3864 isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3865
3866 // ZEXTLOAD is already small enough.
3867 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
3868 ExtVT.bitsGE(Load->getMemoryVT()))
3869 continue;
3870
3871 // Use LE to convert equal sized loads to zext.
3872 if (ExtVT.bitsLE(Load->getMemoryVT()))
3873 Loads.insert(Load);
3874
3875 continue;
3876 }
3877 return false;
3878 }
3879 case ISD::ZERO_EXTEND:
3880 case ISD::AssertZext: {
3881 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3882 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3883 EVT VT = Op.getOpcode() == ISD::AssertZext ?
3884 cast<VTSDNode>(Op.getOperand(1))->getVT() :
3885 Op.getOperand(0).getValueType();
3886
3887 // We can accept extending nodes if the mask is wider or an equal
3888 // width to the original type.
3889 if (ExtVT.bitsGE(VT))
3890 continue;
3891 break;
3892 }
3893 case ISD::OR:
3894 case ISD::XOR:
3895 case ISD::AND:
3896 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3897 NodeToMask))
3898 return false;
3899 continue;
3900 }
3901
3902 // Allow one node which will masked along with any loads found.
3903 if (NodeToMask)
3904 return false;
3905 NodeToMask = Op.getNode();
3906 }
3907 return true;
3908}
3909
3910bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3911 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3912 if (!Mask)
3913 return false;
3914
3915 if (!Mask->getAPIntValue().isMask())
3916 return false;
3917
3918 // No need to do anything if the and directly uses a load.
3919 if (isa<LoadSDNode>(N->getOperand(0)))
3920 return false;
3921
3922 SmallPtrSet<LoadSDNode*, 8> Loads;
3923 SmallPtrSet<SDNode*, 2> NodesWithConsts;
3924 SDNode *FixupNode = nullptr;
3925 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3926 if (Loads.size() == 0)
3927 return false;
3928
3929 DEBUG(dbgs() << "Backwards propagate AND: "; N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "Backwards propagate AND: "
; N->dump(); } } while (false)
;
3930 SDValue MaskOp = N->getOperand(1);
3931
3932 // If it exists, fixup the single node we allow in the tree that needs
3933 // masking.
3934 if (FixupNode) {
3935 DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "First, need to fix up: "; FixupNode
->dump(); } } while (false)
;
3936 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3937 FixupNode->getValueType(0),
3938 SDValue(FixupNode, 0), MaskOp);
3939 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3940 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3941 MaskOp);
3942 }
3943
3944 // Narrow any constants that need it.
3945 for (auto *LogicN : NodesWithConsts) {
3946 SDValue Op0 = LogicN->getOperand(0);
3947 SDValue Op1 = LogicN->getOperand(1);
3948
3949 if (isa<ConstantSDNode>(Op0))
3950 std::swap(Op0, Op1);
3951
3952 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
3953 Op1, MaskOp);
3954
3955 DAG.UpdateNodeOperands(LogicN, Op0, And);
3956 }
3957
3958 // Create narrow loads.
3959 for (auto *Load : Loads) {
3960 DEBUG(dbgs() << "Propagate AND back to: "; Load->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "Propagate AND back to: "; Load
->dump(); } } while (false)
;
3961 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3962 SDValue(Load, 0), MaskOp);
3963 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3964 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3965 SDValue NewLoad = ReduceLoadWidth(And.getNode());
3966 assert(NewLoad &&(static_cast <bool> (NewLoad && "Shouldn't be masking the load if it can't be narrowed"
) ? void (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3967, __extension__ __PRETTY_FUNCTION__))
3967 "Shouldn't be masking the load if it can't be narrowed")(static_cast <bool> (NewLoad && "Shouldn't be masking the load if it can't be narrowed"
) ? void (0) : __assert_fail ("NewLoad && \"Shouldn't be masking the load if it can't be narrowed\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 3967, __extension__ __PRETTY_FUNCTION__))
;
3968 CombineTo(Load, NewLoad, NewLoad.getValue(1));
3969 }
3970 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
3971 return true;
3972 }
3973 return false;
3974}
3975
3976SDValue DAGCombiner::visitAND(SDNode *N) {
3977 SDValue N0 = N->getOperand(0);
3978 SDValue N1 = N->getOperand(1);
3979 EVT VT = N1.getValueType();
3980
3981 // x & x --> x
3982 if (N0 == N1)
3983 return N0;
3984
3985 // fold vector ops
3986 if (VT.isVector()) {
3987 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3988 return FoldedVOp;
3989
3990 // fold (and x, 0) -> 0, vector edition
3991 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3992 // do not return N0, because undef node may exist in N0
3993 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3994 SDLoc(N), N0.getValueType());
3995 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3996 // do not return N1, because undef node may exist in N1
3997 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3998 SDLoc(N), N1.getValueType());
3999
4000 // fold (and x, -1) -> x, vector edition
4001 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4002 return N1;
4003 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4004 return N0;
4005 }
4006
4007 // fold (and c1, c2) -> c1&c2
4008 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4009 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4010 if (N0C && N1C && !N1C->isOpaque())
4011 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
4012 // canonicalize constant to RHS
4013 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4014 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4015 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
4016 // fold (and x, -1) -> x
4017 if (isAllOnesConstant(N1))
4018 return N0;
4019 // if (and x, c) is known to be zero, return 0
4020 unsigned BitWidth = VT.getScalarSizeInBits();
4021 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4022 APInt::getAllOnesValue(BitWidth)))
4023 return DAG.getConstant(0, SDLoc(N), VT);
4024
4025 if (SDValue NewSel = foldBinOpIntoSelect(N))
4026 return NewSel;
4027
4028 // reassociate and
4029 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
4030 return RAND;
4031
4032 // Try to convert a constant mask AND into a shuffle clear mask.
4033 if (VT.isVector())
4034 if (SDValue Shuffle = XformToShuffleWithZero(N))
4035 return Shuffle;
4036
4037 // fold (and (or x, C), D) -> D if (C & D) == D
4038 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4039 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4040 };
4041 if (N0.getOpcode() == ISD::OR &&
4042 matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4043 return N1;
4044 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4045 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4046 SDValue N0Op0 = N0.getOperand(0);
4047 APInt Mask = ~N1C->getAPIntValue();
4048 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4049 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4050 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4051 N0.getValueType(), N0Op0);
4052
4053 // Replace uses of the AND with uses of the Zero extend node.
4054 CombineTo(N, Zext);
4055
4056 // We actually want to replace all uses of the any_extend with the
4057 // zero_extend, to avoid duplicating things. This will later cause this
4058 // AND to be folded.
4059 CombineTo(N0.getNode(), Zext);
4060 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4061 }
4062 }
4063 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4064 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4065 // already be zero by virtue of the width of the base type of the load.
4066 //
4067 // the 'X' node here can either be nothing or an extract_vector_elt to catch
4068 // more cases.
4069 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4070 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4071 N0.getOperand(0).getOpcode() == ISD::LOAD &&
4072 N0.getOperand(0).getResNo() == 0) ||
4073 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4074 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4075 N0 : N0.getOperand(0) );
4076
4077 // Get the constant (if applicable) the zero'th operand is being ANDed with.
4078 // This can be a pure constant or a vector splat, in which case we treat the
4079 // vector as a scalar and use the splat value.
4080 APInt Constant = APInt::getNullValue(1);
4081 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4082 Constant = C->getAPIntValue();
4083 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4084 APInt SplatValue, SplatUndef;
4085 unsigned SplatBitSize;
4086 bool HasAnyUndefs;
4087 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4088 SplatBitSize, HasAnyUndefs);
4089 if (IsSplat) {
4090 // Undef bits can contribute to a possible optimisation if set, so
4091 // set them.
4092 SplatValue |= SplatUndef;
4093
4094 // The splat value may be something like "0x00FFFFFF", which means 0 for
4095 // the first vector value and FF for the rest, repeating. We need a mask
4096 // that will apply equally to all members of the vector, so AND all the
4097 // lanes of the constant together.
4098 EVT VT = Vector->getValueType(0);
4099 unsigned BitWidth = VT.getScalarSizeInBits();
4100
4101 // If the splat value has been compressed to a bitlength lower
4102 // than the size of the vector lane, we need to re-expand it to
4103 // the lane size.
4104 if (BitWidth > SplatBitSize)
4105 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4106 SplatBitSize < BitWidth;
4107 SplatBitSize = SplatBitSize * 2)
4108 SplatValue |= SplatValue.shl(SplatBitSize);
4109
4110 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4111 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4112 if (SplatBitSize % BitWidth == 0) {
4113 Constant = APInt::getAllOnesValue(BitWidth);
4114 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4115 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4116 }
4117 }
4118 }
4119
4120 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4121 // actually legal and isn't going to get expanded, else this is a false
4122 // optimisation.
4123 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4124 Load->getValueType(0),
4125 Load->getMemoryVT());
4126
4127 // Resize the constant to the same size as the original memory access before
4128 // extension. If it is still the AllOnesValue then this AND is completely
4129 // unneeded.
4130 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4131
4132 bool B;
4133 switch (Load->getExtensionType()) {
4134 default: B = false; break;
4135 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4136 case ISD::ZEXTLOAD:
4137 case ISD::NON_EXTLOAD: B = true; break;
4138 }
4139
4140 if (B && Constant.isAllOnesValue()) {
4141 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4142 // preserve semantics once we get rid of the AND.
4143 SDValue NewLoad(Load, 0);
4144
4145 // Fold the AND away. NewLoad may get replaced immediately.
4146 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4147
4148 if (Load->getExtensionType() == ISD::EXTLOAD) {
4149 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4150 Load->getValueType(0), SDLoc(Load),
4151 Load->getChain(), Load->getBasePtr(),
4152 Load->getOffset(), Load->getMemoryVT(),
4153 Load->getMemOperand());
4154 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4155 if (Load->getNumValues() == 3) {
4156 // PRE/POST_INC loads have 3 values.
4157 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4158 NewLoad.getValue(2) };
4159 CombineTo(Load, To, 3, true);
4160 } else {
4161 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4162 }
4163 }
4164
4165 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4166 }
4167 }
4168
4169 // fold (and (load x), 255) -> (zextload x, i8)
4170 // fold (and (extload x, i16), 255) -> (zextload x, i8)
4171 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4172 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4173 (N0.getOpcode() == ISD::ANY_EXTEND &&
4174 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4175 if (SDValue Res = ReduceLoadWidth(N)) {
4176 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4177 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4178
4179 AddToWorklist(N);
4180 CombineTo(LN0, Res, Res.getValue(1));
4181 return SDValue(N, 0);
4182 }
4183 }
4184
4185 if (Level >= AfterLegalizeTypes) {
4186 // Attempt to propagate the AND back up to the leaves which, if they're
4187 // loads, can be combined to narrow loads and the AND node can be removed.
4188 // Perform after legalization so that extend nodes will already be
4189 // combined into the loads.
4190 if (BackwardsPropagateMask(N, DAG)) {
4191 return SDValue(N, 0);
4192 }
4193 }
4194
4195 if (SDValue Combined = visitANDLike(N0, N1, N))
4196 return Combined;
4197
4198 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
4199 if (N0.getOpcode() == N1.getOpcode())
4200 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4201 return Tmp;
4202
4203 // Masking the negated extension of a boolean is just the zero-extended
4204 // boolean:
4205 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4206 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4207 //
4208 // Note: the SimplifyDemandedBits fold below can make an information-losing
4209 // transform, and then we have no way to find this better fold.
4210 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4211 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4212 SDValue SubRHS = N0.getOperand(1);
4213 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4214 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4215 return SubRHS;
4216 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4217 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4218 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4219 }
4220 }
4221
4222 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4223 // fold (and (sra)) -> (and (srl)) when possible.
4224 if (SimplifyDemandedBits(SDValue(N, 0)))
4225 return SDValue(N, 0);
4226
4227 // fold (zext_inreg (extload x)) -> (zextload x)
4228 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4229 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4230 EVT MemVT = LN0->getMemoryVT();
4231 // If we zero all the possible extended bits, then we can turn this into
4232 // a zextload if we are running before legalize or the operation is legal.
4233 unsigned BitWidth = N1.getScalarValueSizeInBits();
4234 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4235 BitWidth - MemVT.getScalarSizeInBits())) &&
4236 ((!LegalOperations && !LN0->isVolatile()) ||
4237 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4238 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4239 LN0->getChain(), LN0->getBasePtr(),
4240 MemVT, LN0->getMemOperand());
4241 AddToWorklist(N);
4242 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4244 }
4245 }
4246 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4247 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4248 N0.hasOneUse()) {
4249 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4250 EVT MemVT = LN0->getMemoryVT();
4251 // If we zero all the possible extended bits, then we can turn this into
4252 // a zextload if we are running before legalize or the operation is legal.
4253 unsigned BitWidth = N1.getScalarValueSizeInBits();
4254 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4255 BitWidth - MemVT.getScalarSizeInBits())) &&
4256 ((!LegalOperations && !LN0->isVolatile()) ||
4257 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4258 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4259 LN0->getChain(), LN0->getBasePtr(),
4260 MemVT, LN0->getMemOperand());
4261 AddToWorklist(N);
4262 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4263 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4264 }
4265 }
4266 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4267 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4268 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4269 N0.getOperand(1), false))
4270 return BSwap;
4271 }
4272
4273 return SDValue();
4274}
4275
4276/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4277SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4278 bool DemandHighBits) {
4279 if (!LegalOperations)
4280 return SDValue();
4281
4282 EVT VT = N->getValueType(0);
4283 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4284 return SDValue();
4285 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4286 return SDValue();
4287
4288 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4289 bool LookPassAnd0 = false;
4290 bool LookPassAnd1 = false;
4291 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4292 std::swap(N0, N1);
4293 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4294 std::swap(N0, N1);
4295 if (N0.getOpcode() == ISD::AND) {
4296 if (!N0.getNode()->hasOneUse())
4297 return SDValue();
4298 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4299 if (!N01C || N01C->getZExtValue() != 0xFF00)
4300 return SDValue();
4301 N0 = N0.getOperand(0);
4302 LookPassAnd0 = true;
4303 }
4304
4305 if (N1.getOpcode() == ISD::AND) {
4306 if (!N1.getNode()->hasOneUse())
4307 return SDValue();
4308 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4309 if (!N11C || N11C->getZExtValue() != 0xFF)
4310 return SDValue();
4311 N1 = N1.getOperand(0);
4312 LookPassAnd1 = true;
4313 }
4314
4315 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4316 std::swap(N0, N1);
4317 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4318 return SDValue();
4319 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4320 return SDValue();
4321
4322 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4323 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4324 if (!N01C || !N11C)
4325 return SDValue();
4326 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4327 return SDValue();
4328
4329 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4330 SDValue N00 = N0->getOperand(0);
4331 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4332 if (!N00.getNode()->hasOneUse())
4333 return SDValue();
4334 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4335 if (!N001C || N001C->getZExtValue() != 0xFF)
4336 return SDValue();
4337 N00 = N00.getOperand(0);
4338 LookPassAnd0 = true;
4339 }
4340
4341 SDValue N10 = N1->getOperand(0);
4342 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4343 if (!N10.getNode()->hasOneUse())
4344 return SDValue();
4345 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4346 if (!N101C || N101C->getZExtValue() != 0xFF00)
4347 return SDValue();
4348 N10 = N10.getOperand(0);
4349 LookPassAnd1 = true;
4350 }
4351
4352 if (N00 != N10)
4353 return SDValue();
4354
4355 // Make sure everything beyond the low halfword gets set to zero since the SRL
4356 // 16 will clear the top bits.
4357 unsigned OpSizeInBits = VT.getSizeInBits();
4358 if (DemandHighBits && OpSizeInBits > 16) {
4359 // If the left-shift isn't masked out then the only way this is a bswap is
4360 // if all bits beyond the low 8 are 0. In that case the entire pattern
4361 // reduces to a left shift anyway: leave it for other parts of the combiner.
4362 if (!LookPassAnd0)
4363 return SDValue();
4364
4365 // However, if the right shift isn't masked out then it might be because
4366 // it's not needed. See if we can spot that too.
4367 if (!LookPassAnd1 &&
4368 !DAG.MaskedValueIsZero(
4369 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4370 return SDValue();
4371 }
4372
4373 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4374 if (OpSizeInBits > 16) {
4375 SDLoc DL(N);
4376 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4377 DAG.getConstant(OpSizeInBits - 16, DL,
4378 getShiftAmountTy(VT)));
4379 }
4380 return Res;
4381}
4382
4383/// Return true if the specified node is an element that makes up a 32-bit
4384/// packed halfword byteswap.
4385/// ((x & 0x000000ff) << 8) |
4386/// ((x & 0x0000ff00) >> 8) |
4387/// ((x & 0x00ff0000) << 8) |
4388/// ((x & 0xff000000) >> 8)
4389static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4390 if (!N.getNode()->hasOneUse())
4391 return false;
4392
4393 unsigned Opc = N.getOpcode();
4394 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4395 return false;
4396
4397 SDValue N0 = N.getOperand(0);
4398 unsigned Opc0 = N0.getOpcode();
4399 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4400 return false;
4401
4402 ConstantSDNode *N1C = nullptr;
4403 // SHL or SRL: look upstream for AND mask operand
4404 if (Opc == ISD::AND)
4405 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4406 else if (Opc0 == ISD::AND)
4407 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4408 if (!N1C)
4409 return false;
4410
4411 unsigned MaskByteOffset;
4412 switch (N1C->getZExtValue()) {
4413 default:
4414 return false;
4415 case 0xFF: MaskByteOffset = 0; break;
4416 case 0xFF00: MaskByteOffset = 1; break;
4417 case 0xFF0000: MaskByteOffset = 2; break;
4418 case 0xFF000000: MaskByteOffset = 3; break;
4419 }
4420
4421 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4422 if (Opc == ISD::AND) {
4423 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4424 // (x >> 8) & 0xff
4425 // (x >> 8) & 0xff0000
4426 if (Opc0 != ISD::SRL)
4427 return false;
4428 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4429 if (!C || C->getZExtValue() != 8)
4430 return false;
4431 } else {
4432 // (x << 8) & 0xff00
4433 // (x << 8) & 0xff000000
4434 if (Opc0 != ISD::SHL)
4435 return false;
4436 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4437 if (!C || C->getZExtValue() != 8)
4438 return false;
4439 }
4440 } else if (Opc == ISD::SHL) {
4441 // (x & 0xff) << 8
4442 // (x & 0xff0000) << 8
4443 if (MaskByteOffset != 0 && MaskByteOffset != 2)
4444 return false;
4445 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4446 if (!C || C->getZExtValue() != 8)
4447 return false;
4448 } else { // Opc == ISD::SRL
4449 // (x & 0xff00) >> 8
4450 // (x & 0xff000000) >> 8
4451 if (MaskByteOffset != 1 && MaskByteOffset != 3)
4452 return false;
4453 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4454 if (!C || C->getZExtValue() != 8)
4455 return false;
4456 }
4457
4458 if (Parts[MaskByteOffset])
4459 return false;
4460
4461 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4462 return true;
4463}
4464
4465/// Match a 32-bit packed halfword bswap. That is
4466/// ((x & 0x000000ff) << 8) |
4467/// ((x & 0x0000ff00) >> 8) |
4468/// ((x & 0x00ff0000) << 8) |
4469/// ((x & 0xff000000) >> 8)
4470/// => (rotl (bswap x), 16)
4471SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4472 if (!LegalOperations)
4473 return SDValue();
4474
4475 EVT VT = N->getValueType(0);
4476 if (VT != MVT::i32)
4477 return SDValue();
4478 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4479 return SDValue();
4480
4481 // Look for either
4482 // (or (or (and), (and)), (or (and), (and)))
4483 // (or (or (or (and), (and)), (and)), (and))
4484 if (N0.getOpcode() != ISD::OR)
4485 return SDValue();
4486 SDValue N00 = N0.getOperand(0);
4487 SDValue N01 = N0.getOperand(1);
4488 SDNode *Parts[4] = {};
4489
4490 if (N1.getOpcode() == ISD::OR &&
4491 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4492 // (or (or (and), (and)), (or (and), (and)))
4493 if (!isBSwapHWordElement(N00, Parts))
4494 return SDValue();
4495
4496 if (!isBSwapHWordElement(N01, Parts))
4497 return SDValue();
4498 SDValue N10 = N1.getOperand(0);
4499 if (!isBSwapHWordElement(N10, Parts))
4500 return SDValue();
4501 SDValue N11 = N1.getOperand(1);
4502 if (!isBSwapHWordElement(N11, Parts))
4503 return SDValue();
4504 } else {
4505 // (or (or (or (and), (and)), (and)), (and))
4506 if (!isBSwapHWordElement(N1, Parts))
4507 return SDValue();
4508 if (!isBSwapHWordElement(N01, Parts))
4509 return SDValue();
4510 if (N00.getOpcode() != ISD::OR)
4511 return SDValue();
4512 SDValue N000 = N00.getOperand(0);
4513 if (!isBSwapHWordElement(N000, Parts))
4514 return SDValue();
4515 SDValue N001 = N00.getOperand(1);
4516 if (!isBSwapHWordElement(N001, Parts))
4517 return SDValue();
4518 }
4519
4520 // Make sure the parts are all coming from the same node.
4521 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4522 return SDValue();
4523
4524 SDLoc DL(N);
4525 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4526 SDValue(Parts[0], 0));
4527
4528 // Result of the bswap should be rotated by 16. If it's not legal, then
4529 // do (x << 16) | (x >> 16).
4530 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4531 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4532 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4533 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4534 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4535 return DAG.getNode(ISD::OR, DL, VT,
4536 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4537 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4538}
4539
4540/// This contains all DAGCombine rules which reduce two values combined by
4541/// an Or operation to a single value \see visitANDLike().
4542SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4543 EVT VT = N1.getValueType();
4544 SDLoc DL(N);
4545
4546 // fold (or x, undef) -> -1
4547 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4548 return DAG.getAllOnesConstant(DL, VT);
4549
4550 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4551 return V;
4552
4553 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4554 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4555 // Don't increase # computations.
4556 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4557 // We can only do this xform if we know that bits from X that are set in C2
4558 // but not in C1 are already zero. Likewise for Y.
4559 if (const ConstantSDNode *N0O1C =
4560 getAsNonOpaqueConstant(N0.getOperand(1))) {
4561 if (const ConstantSDNode *N1O1C =
4562 getAsNonOpaqueConstant(N1.getOperand(1))) {
4563 // We can only do this xform if we know that bits from X that are set in
4564 // C2 but not in C1 are already zero. Likewise for Y.
4565 const APInt &LHSMask = N0O1C->getAPIntValue();
4566 const APInt &RHSMask = N1O1C->getAPIntValue();
4567
4568 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4569 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4570 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4571 N0.getOperand(0), N1.getOperand(0));
4572 return DAG.getNode(ISD::AND, DL, VT, X,
4573 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4574 }
4575 }
4576 }
4577 }
4578
4579 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4580 if (N0.getOpcode() == ISD::AND &&
4581 N1.getOpcode() == ISD::AND &&
4582 N0.getOperand(0) == N1.getOperand(0) &&
4583 // Don't increase # computations.
4584 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4585 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4586 N0.getOperand(1), N1.getOperand(1));
4587 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4588 }
4589
4590 return SDValue();
4591}
4592
4593SDValue DAGCombiner::visitOR(SDNode *N) {
4594 SDValue N0 = N->getOperand(0);
4595 SDValue N1 = N->getOperand(1);
4596 EVT VT = N1.getValueType();
4597
4598 // x | x --> x
4599 if (N0 == N1)
4600 return N0;
4601
4602 // fold vector ops
4603 if (VT.isVector()) {
4604 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4605 return FoldedVOp;
4606
4607 // fold (or x, 0) -> x, vector edition
4608 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4609 return N1;
4610 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4611 return N0;
4612
4613 // fold (or x, -1) -> -1, vector edition
4614 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4615 // do not return N0, because undef node may exist in N0
4616 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4617 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4618 // do not return N1, because undef node may exist in N1
4619 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4620
4621 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4622 // Do this only if the resulting shuffle is legal.
4623 if (isa<ShuffleVectorSDNode>(N0) &&
4624 isa<ShuffleVectorSDNode>(N1) &&
4625 // Avoid folding a node with illegal type.
4626 TLI.isTypeLegal(VT)) {
4627 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4628 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4629 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4630 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4631 // Ensure both shuffles have a zero input.
4632 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4633 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!")(static_cast <bool> ((!ZeroN00 || !ZeroN01) && "Both inputs zero!"
) ? void (0) : __assert_fail ("(!ZeroN00 || !ZeroN01) && \"Both inputs zero!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4633, __extension__ __PRETTY_FUNCTION__))
;
4634 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!")(static_cast <bool> ((!ZeroN10 || !ZeroN11) && "Both inputs zero!"
) ? void (0) : __assert_fail ("(!ZeroN10 || !ZeroN11) && \"Both inputs zero!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4634, __extension__ __PRETTY_FUNCTION__))
;
4635 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4636 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4637 bool CanFold = true;
4638 int NumElts = VT.getVectorNumElements();
4639 SmallVector<int, 4> Mask(NumElts);
4640
4641 for (int i = 0; i != NumElts; ++i) {
4642 int M0 = SV0->getMaskElt(i);
4643 int M1 = SV1->getMaskElt(i);
4644
4645 // Determine if either index is pointing to a zero vector.
4646 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4647 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4648
4649 // If one element is zero and the otherside is undef, keep undef.
4650 // This also handles the case that both are undef.
4651 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4652 Mask[i] = -1;
4653 continue;
4654 }
4655
4656 // Make sure only one of the elements is zero.
4657 if (M0Zero == M1Zero) {
4658 CanFold = false;
4659 break;
4660 }
4661
4662 assert((M0 >= 0 || M1 >= 0) && "Undef index!")(static_cast <bool> ((M0 >= 0 || M1 >= 0) &&
"Undef index!") ? void (0) : __assert_fail ("(M0 >= 0 || M1 >= 0) && \"Undef index!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4662, __extension__ __PRETTY_FUNCTION__))
;
4663
4664 // We have a zero and non-zero element. If the non-zero came from
4665 // SV0 make the index a LHS index. If it came from SV1, make it
4666 // a RHS index. We need to mod by NumElts because we don't care
4667 // which operand it came from in the original shuffles.
4668 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4669 }
4670
4671 if (CanFold) {
4672 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4673 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4674
4675 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4676 if (!LegalMask) {
4677 std::swap(NewLHS, NewRHS);
4678 ShuffleVectorSDNode::commuteMask(Mask);
4679 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4680 }
4681
4682 if (LegalMask)
4683 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4684 }
4685 }
4686 }
4687 }
4688
4689 // fold (or c1, c2) -> c1|c2
4690 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4692 if (N0C && N1C && !N1C->isOpaque())
4693 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4694 // canonicalize constant to RHS
4695 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4696 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4697 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4698 // fold (or x, 0) -> x
4699 if (isNullConstant(N1))
4700 return N0;
4701 // fold (or x, -1) -> -1
4702 if (isAllOnesConstant(N1))
4703 return N1;
4704
4705 if (SDValue NewSel = foldBinOpIntoSelect(N))
4706 return NewSel;
4707
4708 // fold (or x, c) -> c iff (x & ~c) == 0
4709 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4710 return N1;
4711
4712 if (SDValue Combined = visitORLike(N0, N1, N))
4713 return Combined;
4714
4715 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4716 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4717 return BSwap;
4718 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4719 return BSwap;
4720
4721 // reassociate or
4722 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4723 return ROR;
4724
4725 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4726 // iff (c1 & c2) != 0.
4727 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4728 return LHS->getAPIntValue().intersects(RHS->getAPIntValue());
4729 };
4730 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4731 matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) {
4732 if (SDValue COR = DAG.FoldConstantArithmetic(
4733 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
4734 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
4735 AddToWorklist(IOR.getNode());
4736 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
4737 }
4738 }
4739
4740 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4741 if (N0.getOpcode() == N1.getOpcode())
4742 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4743 return Tmp;
4744
4745 // See if this is some rotate idiom.
4746 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4747 return SDValue(Rot, 0);
4748
4749 if (SDValue Load = MatchLoadCombine(N))
4750 return Load;
4751
4752 // Simplify the operands using demanded-bits information.
4753 if (SimplifyDemandedBits(SDValue(N, 0)))
4754 return SDValue(N, 0);
4755
4756 return SDValue();
4757}
4758
4759/// Match "(X shl/srl V1) & V2" where V2 may not be present.
4760bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4761 if (Op.getOpcode() == ISD::AND) {
4762 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4763 Mask = Op.getOperand(1);
4764 Op = Op.getOperand(0);
4765 } else {
4766 return false;
4767 }
4768 }
4769
4770 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4771 Shift = Op;
4772 return true;
4773 }
4774
4775 return false;
4776}
4777
4778// Return true if we can prove that, whenever Neg and Pos are both in the
4779// range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4780// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4781//
4782// (or (shift1 X, Neg), (shift2 X, Pos))
4783//
4784// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4785// in direction shift1 by Neg. The range [0, EltSize) means that we only need
4786// to consider shift amounts with defined behavior.
4787static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4788 // If EltSize is a power of 2 then:
4789 //
4790 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4791 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4792 //
4793 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4794 // for the stronger condition:
4795 //
4796 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4797 //
4798 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4799 // we can just replace Neg with Neg' for the rest of the function.
4800 //
4801 // In other cases we check for the even stronger condition:
4802 //
4803 // Neg == EltSize - Pos [B]
4804 //
4805 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4806 // behavior if Pos == 0 (and consequently Neg == EltSize).
4807 //
4808 // We could actually use [A] whenever EltSize is a power of 2, but the
4809 // only extra cases that it would match are those uninteresting ones
4810 // where Neg and Pos are never in range at the same time. E.g. for
4811 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4812 // as well as (sub 32, Pos), but:
4813 //
4814 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4815 //
4816 // always invokes undefined behavior for 32-bit X.
4817 //
4818 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4819 unsigned MaskLoBits = 0;
4820 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4821 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4822 if (NegC->getAPIntValue() == EltSize - 1) {
4823 Neg = Neg.getOperand(0);
4824 MaskLoBits = Log2_64(EltSize);
4825 }
4826 }
4827 }
4828
4829 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4830 if (Neg.getOpcode() != ISD::SUB)
4831 return false;
4832 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4833 if (!NegC)
4834 return false;
4835 SDValue NegOp1 = Neg.getOperand(1);
4836
4837 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4838 // Pos'. The truncation is redundant for the purpose of the equality.
4839 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4840 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4841 if (PosC->getAPIntValue() == EltSize - 1)
4842 Pos = Pos.getOperand(0);
4843
4844 // The condition we need is now:
4845 //
4846 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4847 //
4848 // If NegOp1 == Pos then we need:
4849 //
4850 // EltSize & Mask == NegC & Mask
4851 //
4852 // (because "x & Mask" is a truncation and distributes through subtraction).
4853 APInt Width;
4854 if (Pos == NegOp1)
4855 Width = NegC->getAPIntValue();
4856
4857 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4858 // Then the condition we want to prove becomes:
4859 //
4860 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4861 //
4862 // which, again because "x & Mask" is a truncation, becomes:
4863 //
4864 // NegC & Mask == (EltSize - PosC) & Mask
4865 // EltSize & Mask == (NegC + PosC) & Mask
4866 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4867 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4868 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4869 else
4870 return false;
4871 } else
4872 return false;
4873
4874 // Now we just need to check that EltSize & Mask == Width & Mask.
4875 if (MaskLoBits)
4876 // EltSize & Mask is 0 since Mask is EltSize - 1.
4877 return Width.getLoBits(MaskLoBits) == 0;
4878 return Width == EltSize;
4879}
4880
4881// A subroutine of MatchRotate used once we have found an OR of two opposite
4882// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4883// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4884// former being preferred if supported. InnerPos and InnerNeg are Pos and
4885// Neg with outer conversions stripped away.
4886SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4887 SDValue Neg, SDValue InnerPos,
4888 SDValue InnerNeg, unsigned PosOpcode,
4889 unsigned NegOpcode, const SDLoc &DL) {
4890 // fold (or (shl x, (*ext y)),
4891 // (srl x, (*ext (sub 32, y)))) ->
4892 // (rotl x, y) or (rotr x, (sub 32, y))
4893 //
4894 // fold (or (shl x, (*ext (sub 32, y))),
4895 // (srl x, (*ext y))) ->
4896 // (rotr x, y) or (rotl x, (sub 32, y))
4897 EVT VT = Shifted.getValueType();
4898 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4899 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4900 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4901 HasPos ? Pos : Neg).getNode();
4902 }
4903
4904 return nullptr;
4905}
4906
4907// MatchRotate - Handle an 'or' of two operands. If this is one of the many
4908// idioms for rotate, and if the target supports rotation instructions, generate
4909// a rot[lr].
4910SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4911 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4912 EVT VT = LHS.getValueType();
4913 if (!TLI.isTypeLegal(VT)) return nullptr;
4914
4915 // The target must have at least one rotate flavor.
4916 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4917 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4918 if (!HasROTL && !HasROTR) return nullptr;
4919
4920 // Check for truncated rotate.
4921 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4922 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4923 assert(LHS.getValueType() == RHS.getValueType())(static_cast <bool> (LHS.getValueType() == RHS.getValueType
()) ? void (0) : __assert_fail ("LHS.getValueType() == RHS.getValueType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
;
4924 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4925 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4926 SDValue(Rot, 0)).getNode();
4927 }
4928 }
4929
4930 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4931 SDValue LHSShift; // The shift.
4932 SDValue LHSMask; // AND value if any.
4933 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4934 return nullptr; // Not part of a rotate.
4935
4936 SDValue RHSShift; // The shift.
4937 SDValue RHSMask; // AND value if any.
4938 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4939 return nullptr; // Not part of a rotate.
4940
4941 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4942 return nullptr; // Not shifting the same value.
4943
4944 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4945 return nullptr; // Shifts must disagree.
4946
4947 // Canonicalize shl to left side in a shl/srl pair.
4948 if (RHSShift.getOpcode() == ISD::SHL) {
4949 std::swap(LHS, RHS);
4950 std::swap(LHSShift, RHSShift);
4951 std::swap(LHSMask, RHSMask);
4952 }
4953
4954 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4955 SDValue LHSShiftArg = LHSShift.getOperand(0);
4956 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4957 SDValue RHSShiftArg = RHSShift.getOperand(0);
4958 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4959
4960 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4961 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4962 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4963 ConstantSDNode *RHS) {
4964 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4965 };
4966 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4967 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4968 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4969
4970 // If there is an AND of either shifted operand, apply it to the result.
4971 if (LHSMask.getNode() || RHSMask.getNode()) {
4972 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4973 SDValue Mask = AllOnes;
4974
4975 if (LHSMask.getNode()) {
4976 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4977 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4978 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4979 }
4980 if (RHSMask.getNode()) {
4981 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4982 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4983 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4984 }
4985
4986 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4987 }
4988
4989 return Rot.getNode();
4990 }
4991
4992 // If there is a mask here, and we have a variable shift, we can't be sure
4993 // that we're masking out the right stuff.
4994 if (LHSMask.getNode() || RHSMask.getNode())
4995 return nullptr;
4996
4997 // If the shift amount is sign/zext/any-extended just peel it off.
4998 SDValue LExtOp0 = LHSShiftAmt;
4999 SDValue RExtOp0 = RHSShiftAmt;
5000 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5001 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5002 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5003 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
5004 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5005 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5006 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5007 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
5008 LExtOp0 = LHSShiftAmt.getOperand(0);
5009 RExtOp0 = RHSShiftAmt.getOperand(0);
5010 }
5011
5012 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
5013 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
5014 if (TryL)
5015 return TryL;
5016
5017 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
5018 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
5019 if (TryR)
5020 return TryR;
5021
5022 return nullptr;
5023}
5024
5025namespace {
5026
5027/// Represents known origin of an individual byte in load combine pattern. The
5028/// value of the byte is either constant zero or comes from memory.
5029struct ByteProvider {
5030 // For constant zero providers Load is set to nullptr. For memory providers
5031 // Load represents the node which loads the byte from memory.
5032 // ByteOffset is the offset of the byte in the value produced by the load.
5033 LoadSDNode *Load = nullptr;
5034 unsigned ByteOffset = 0;
5035
5036 ByteProvider() = default;
5037
5038 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
5039 return ByteProvider(Load, ByteOffset);
5040 }
5041
5042 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
5043
5044 bool isConstantZero() const { return !Load; }
5045 bool isMemory() const { return Load; }
5046
5047 bool operator==(const ByteProvider &Other) const {
5048 return Other.Load == Load && Other.ByteOffset == ByteOffset;
5049 }
5050
5051private:
5052 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5053 : Load(Load), ByteOffset(ByteOffset) {}
5054};
5055
5056} // end anonymous namespace
5057
5058/// Recursively traverses the expression calculating the origin of the requested
5059/// byte of the given value. Returns None if the provider can't be calculated.
5060///
5061/// For all the values except the root of the expression verifies that the value
5062/// has exactly one use and if it's not true return None. This way if the origin
5063/// of the byte is returned it's guaranteed that the values which contribute to
5064/// the byte are not used outside of this expression.
5065///
5066/// Because the parts of the expression are not allowed to have more than one
5067/// use this function iterates over trees, not DAGs. So it never visits the same
5068/// node more than once.
5069static const Optional<ByteProvider>
5070calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5071 bool Root = false) {
5072 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5073 if (Depth == 10)
5074 return None;
5075
5076 if (!Root && !Op.hasOneUse())
5077 return None;
5078
5079 assert(Op.getValueType().isScalarInteger() && "can't handle other types")(static_cast <bool> (Op.getValueType().isScalarInteger(
) && "can't handle other types") ? void (0) : __assert_fail
("Op.getValueType().isScalarInteger() && \"can't handle other types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5079, __extension__ __PRETTY_FUNCTION__))
;
5080 unsigned BitWidth = Op.getValueSizeInBits();
5081 if (BitWidth % 8 != 0)
5082 return None;
5083 unsigned ByteWidth = BitWidth / 8;
5084 assert(Index < ByteWidth && "invalid index requested")(static_cast <bool> (Index < ByteWidth && "invalid index requested"
) ? void (0) : __assert_fail ("Index < ByteWidth && \"invalid index requested\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5084, __extension__ __PRETTY_FUNCTION__))
;
5085 (void) ByteWidth;
5086
5087 switch (Op.getOpcode()) {
5088 case ISD::OR: {
5089 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5090 if (!LHS)
5091 return None;
5092 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5093 if (!RHS)
5094 return None;
5095
5096 if (LHS->isConstantZero())
5097 return RHS;
5098 if (RHS->isConstantZero())
5099 return LHS;
5100 return None;
5101 }
5102 case ISD::SHL: {
5103 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5104 if (!ShiftOp)
5105 return None;
5106
5107 uint64_t BitShift = ShiftOp->getZExtValue();
5108 if (BitShift % 8 != 0)
5109 return None;
5110 uint64_t ByteShift = BitShift / 8;
5111
5112 return Index < ByteShift
5113 ? ByteProvider::getConstantZero()
5114 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5115 Depth + 1);
5116 }
5117 case ISD::ANY_EXTEND:
5118 case ISD::SIGN_EXTEND:
5119 case ISD::ZERO_EXTEND: {
5120 SDValue NarrowOp = Op->getOperand(0);
5121 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5122 if (NarrowBitWidth % 8 != 0)
5123 return None;
5124 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5125
5126 if (Index >= NarrowByteWidth)
5127 return Op.getOpcode() == ISD::ZERO_EXTEND
5128 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5129 : None;
5130 return calculateByteProvider(NarrowOp, Index, Depth + 1);
5131 }
5132 case ISD::BSWAP:
5133 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5134 Depth + 1);
5135 case ISD::LOAD: {
5136 auto L = cast<LoadSDNode>(Op.getNode());
5137 if (L->isVolatile() || L->isIndexed())
5138 return None;
5139
5140 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5141 if (NarrowBitWidth % 8 != 0)
5142 return None;
5143 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5144
5145 if (Index >= NarrowByteWidth)
5146 return L->getExtensionType() == ISD::ZEXTLOAD
5147 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5148 : None;
5149 return ByteProvider::getMemory(L, Index);
5150 }
5151 }
5152
5153 return None;
5154}
5155
5156/// Match a pattern where a wide type scalar value is loaded by several narrow
5157/// loads and combined by shifts and ors. Fold it into a single load or a load
5158/// and a BSWAP if the targets supports it.
5159///
5160/// Assuming little endian target:
5161/// i8 *a = ...
5162/// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5163/// =>
5164/// i32 val = *((i32)a)
5165///
5166/// i8 *a = ...
5167/// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5168/// =>
5169/// i32 val = BSWAP(*((i32)a))
5170///
5171/// TODO: This rule matches complex patterns with OR node roots and doesn't
5172/// interact well with the worklist mechanism. When a part of the pattern is
5173/// updated (e.g. one of the loads) its direct users are put into the worklist,
5174/// but the root node of the pattern which triggers the load combine is not
5175/// necessarily a direct user of the changed node. For example, once the address
5176/// of t28 load is reassociated load combine won't be triggered:
5177/// t25: i32 = add t4, Constant:i32<2>
5178/// t26: i64 = sign_extend t25
5179/// t27: i64 = add t2, t26
5180/// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5181/// t29: i32 = zero_extend t28
5182/// t32: i32 = shl t29, Constant:i8<8>
5183/// t33: i32 = or t23, t32
5184/// As a possible fix visitLoad can check if the load can be a part of a load
5185/// combine pattern and add corresponding OR roots to the worklist.
5186SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5187 assert(N->getOpcode() == ISD::OR &&(static_cast <bool> (N->getOpcode() == ISD::OR &&
"Can only match load combining against OR nodes") ? void (0)
: __assert_fail ("N->getOpcode() == ISD::OR && \"Can only match load combining against OR nodes\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
5188 "Can only match load combining against OR nodes")(static_cast <bool> (N->getOpcode() == ISD::OR &&
"Can only match load combining against OR nodes") ? void (0)
: __assert_fail ("N->getOpcode() == ISD::OR && \"Can only match load combining against OR nodes\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
;
5189
5190 // Handles simple types only
5191 EVT VT = N->getValueType(0);
5192 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5193 return SDValue();
5194 unsigned ByteWidth = VT.getSizeInBits() / 8;
5195
5196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5197 // Before legalize we can introduce too wide illegal loads which will be later
5198 // split into legal sized loads. This enables us to combine i64 load by i8
5199 // patterns to a couple of i32 loads on 32 bit targets.
5200 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5201 return SDValue();
5202
5203 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5204 unsigned BW, unsigned i) { return i; };
5205 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5206 unsigned BW, unsigned i) { return BW - i - 1; };
5207
5208 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5209 auto MemoryByteOffset = [&] (ByteProvider P) {
5210 assert(P.isMemory() && "Must be a memory byte provider")(static_cast <bool> (P.isMemory() && "Must be a memory byte provider"
) ? void (0) : __assert_fail ("P.isMemory() && \"Must be a memory byte provider\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5210, __extension__ __PRETTY_FUNCTION__))
;
5211 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5212 assert(LoadBitWidth % 8 == 0 &&(static_cast <bool> (LoadBitWidth % 8 == 0 && "can only analyze providers for individual bytes not bit"
) ? void (0) : __assert_fail ("LoadBitWidth % 8 == 0 && \"can only analyze providers for individual bytes not bit\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5213, __extension__ __PRETTY_FUNCTION__))
5213 "can only analyze providers for individual bytes not bit")(static_cast <bool> (LoadBitWidth % 8 == 0 && "can only analyze providers for individual bytes not bit"
) ? void (0) : __assert_fail ("LoadBitWidth % 8 == 0 && \"can only analyze providers for individual bytes not bit\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5213, __extension__ __PRETTY_FUNCTION__))
;
5214 unsigned LoadByteWidth = LoadBitWidth / 8;
5215 return IsBigEndianTarget
5216 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5217 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5218 };
5219
5220 Optional<BaseIndexOffset> Base;
5221 SDValue Chain;
5222
5223 SmallSet<LoadSDNode *, 8> Loads;
5224 Optional<ByteProvider> FirstByteProvider;
5225 int64_t FirstOffset = INT64_MAX(9223372036854775807L);
5226
5227 // Check if all the bytes of the OR we are looking at are loaded from the same
5228 // base address. Collect bytes offsets from Base address in ByteOffsets.
5229 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5230 for (unsigned i = 0; i < ByteWidth; i++) {
5231 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5232 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5233 return SDValue();
5234
5235 LoadSDNode *L = P->Load;
5236 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&(static_cast <bool> (L->hasNUsesOfValue(1, 0) &&
!L->isVolatile() && !L->isIndexed() &&
"Must be enforced by calculateByteProvider") ? void (0) : __assert_fail
("L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && \"Must be enforced by calculateByteProvider\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5237, __extension__ __PRETTY_FUNCTION__))
5237 "Must be enforced by calculateByteProvider")(static_cast <bool> (L->hasNUsesOfValue(1, 0) &&
!L->isVolatile() && !L->isIndexed() &&
"Must be enforced by calculateByteProvider") ? void (0) : __assert_fail
("L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && \"Must be enforced by calculateByteProvider\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5237, __extension__ __PRETTY_FUNCTION__))
;
5238 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset")(static_cast <bool> (L->getOffset().isUndef() &&
"Unindexed load must have undef offset") ? void (0) : __assert_fail
("L->getOffset().isUndef() && \"Unindexed load must have undef offset\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5238, __extension__ __PRETTY_FUNCTION__))
;
5239
5240 // All loads must share the same chain
5241 SDValue LChain = L->getChain();
5242 if (!Chain)
5243 Chain = LChain;
5244 else if (Chain != LChain)
5245 return SDValue();
5246
5247 // Loads must share the same base address
5248 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
5249 int64_t ByteOffsetFromBase = 0;
5250 if (!Base)
5251 Base = Ptr;
5252 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5253 return SDValue();
5254
5255 // Calculate the offset of the current byte from the base address
5256 ByteOffsetFromBase += MemoryByteOffset(*P);
5257 ByteOffsets[i] = ByteOffsetFromBase;
5258
5259 // Remember the first byte load
5260 if (ByteOffsetFromBase < FirstOffset) {
5261 FirstByteProvider = P;
5262 FirstOffset = ByteOffsetFromBase;
5263 }
5264
5265 Loads.insert(L);
5266 }
5267 assert(!Loads.empty() && "All the bytes of the value must be loaded from "(static_cast <bool> (!Loads.empty() && "All the bytes of the value must be loaded from "
"memory, so there must be at least one load which produces the value"
) ? void (0) : __assert_fail ("!Loads.empty() && \"All the bytes of the value must be loaded from \" \"memory, so there must be at least one load which produces the value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5268, __extension__ __PRETTY_FUNCTION__))
5268 "memory, so there must be at least one load which produces the value")(static_cast <bool> (!Loads.empty() && "All the bytes of the value must be loaded from "
"memory, so there must be at least one load which produces the value"
) ? void (0) : __assert_fail ("!Loads.empty() && \"All the bytes of the value must be loaded from \" \"memory, so there must be at least one load which produces the value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5268, __extension__ __PRETTY_FUNCTION__))
;
5269 assert(Base && "Base address of the accessed memory location must be set")(static_cast <bool> (Base && "Base address of the accessed memory location must be set"
) ? void (0) : __assert_fail ("Base && \"Base address of the accessed memory location must be set\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5269, __extension__ __PRETTY_FUNCTION__))
;
5270 assert(FirstOffset != INT64_MAX && "First byte offset must be set")(static_cast <bool> (FirstOffset != (9223372036854775807L
) && "First byte offset must be set") ? void (0) : __assert_fail
("FirstOffset != INT64_MAX && \"First byte offset must be set\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5270, __extension__ __PRETTY_FUNCTION__))
;
5271
5272 // Check if the bytes of the OR we are looking at match with either big or
5273 // little endian value load
5274 bool BigEndian = true, LittleEndian = true;
5275 for (unsigned i = 0; i < ByteWidth; i++) {
5276 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5277 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5278 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5279 if (!BigEndian && !LittleEndian)
5280 return SDValue();
5281 }
5282 assert((BigEndian != LittleEndian) && "should be either or")(static_cast <bool> ((BigEndian != LittleEndian) &&
"should be either or") ? void (0) : __assert_fail ("(BigEndian != LittleEndian) && \"should be either or\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5282, __extension__ __PRETTY_FUNCTION__))
;
5283 assert(FirstByteProvider && "must be set")(static_cast <bool> (FirstByteProvider && "must be set"
) ? void (0) : __assert_fail ("FirstByteProvider && \"must be set\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5283, __extension__ __PRETTY_FUNCTION__))
;
5284
5285 // Ensure that the first byte is loaded from zero offset of the first load.
5286 // So the combined value can be loaded from the first load address.
5287 if (MemoryByteOffset(*FirstByteProvider) != 0)
5288 return SDValue();
5289 LoadSDNode *FirstLoad = FirstByteProvider->Load;
5290
5291 // The node we are looking at matches with the pattern, check if we can
5292 // replace it with a single load and bswap if needed.
5293
5294 // If the load needs byte swap check if the target supports it
5295 bool NeedsBswap = IsBigEndianTarget != BigEndian;
5296
5297 // Before legalize we can introduce illegal bswaps which will be later
5298 // converted to an explicit bswap sequence. This way we end up with a single
5299 // load and byte shuffling instead of several loads and byte shuffling.
5300 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5301 return SDValue();
5302
5303 // Check that a load of the wide type is both allowed and fast on the target
5304 bool Fast = false;
5305 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5306 VT, FirstLoad->getAddressSpace(),
5307 FirstLoad->getAlignment(), &Fast);
5308 if (!Allowed || !Fast)
5309 return SDValue();
5310
5311 SDValue NewLoad =
5312 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5313 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5314
5315 // Transfer chain users from old loads to the new load.
5316 for (LoadSDNode *L : Loads)
5317 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5318
5319 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5320}
5321
5322SDValue DAGCombiner::visitXOR(SDNode *N) {
5323 SDValue N0 = N->getOperand(0);
5324 SDValue N1 = N->getOperand(1);
5325 EVT VT = N0.getValueType();
5326
5327 // fold vector ops
5328 if (VT.isVector()) {
5329 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5330 return FoldedVOp;
5331
5332 // fold (xor x, 0) -> x, vector edition
5333 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5334 return N1;
5335 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5336 return N0;
5337 }
5338
5339 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5340 if (N0.isUndef() && N1.isUndef())
5341 return DAG.getConstant(0, SDLoc(N), VT);
5342 // fold (xor x, undef) -> undef
5343 if (N0.isUndef())
5344 return N0;
5345 if (N1.isUndef())
5346 return N1;
5347 // fold (xor c1, c2) -> c1^c2
5348 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5349 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5350 if (N0C && N1C)
5351 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5352 // canonicalize constant to RHS
5353 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5354 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5355 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5356 // fold (xor x, 0) -> x
5357 if (isNullConstant(N1))
5358 return N0;
5359
5360 if (SDValue NewSel = foldBinOpIntoSelect(N))
5361 return NewSel;
5362
5363 // reassociate xor
5364 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5365 return RXOR;
5366
5367 // fold !(x cc y) -> (x !cc y)
5368 SDValue LHS, RHS, CC;
5369 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5370 bool isInt = LHS.getValueType().isInteger();
5371 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5372 isInt);
5373
5374 if (!LegalOperations ||
5375 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5376 switch (N0.getOpcode()) {
5377 default:
5378 llvm_unreachable("Unhandled SetCC Equivalent!")::llvm::llvm_unreachable_internal("Unhandled SetCC Equivalent!"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5378)
;
5379 case ISD::SETCC:
5380 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5381 case ISD::SELECT_CC:
5382 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5383 N0.getOperand(3), NotCC);
5384 }
5385 }
5386 }
5387
5388 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5389 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5390 N0.getNode()->hasOneUse() &&
5391 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5392 SDValue V = N0.getOperand(0);
5393 SDLoc DL(N0);
5394 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5395 DAG.getConstant(1, DL, V.getValueType()));
5396 AddToWorklist(V.getNode());
5397 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5398 }
5399
5400 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5401 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
5402 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5403 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5404 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5405 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5406 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5407 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5408 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5409 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5410 }
5411 }
5412 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5413 if (isAllOnesConstant(N1) && N0.hasOneUse() &&
5414 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5415 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5416 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5417 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5418 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5419 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5420 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5421 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5422 }
5423 }
5424 // fold (xor (and x, y), y) -> (and (not x), y)
5425 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5426 N0->getOperand(1) == N1) {
5427 SDValue X = N0->getOperand(0);
5428 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5429 AddToWorklist(NotX.getNode());
5430 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5431 }
5432
5433 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5434 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5435 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5436 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5437 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5438 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5439 if (C->getAPIntValue() == (OpSizeInBits - 1))
5440 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5441 }
5442
5443 // fold (xor x, x) -> 0
5444 if (N0 == N1)
5445 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5446
5447 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5448 // Here is a concrete example of this equivalence:
5449 // i16 x == 14
5450 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5451 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5452 //
5453 // =>
5454 //
5455 // i16 ~1 == 0b1111111111111110
5456 // i16 rol(~1, 14) == 0b1011111111111111
5457 //
5458 // Some additional tips to help conceptualize this transform:
5459 // - Try to see the operation as placing a single zero in a value of all ones.
5460 // - There exists no value for x which would allow the result to contain zero.
5461 // - Values of x larger than the bitwidth are undefined and do not require a
5462 // consistent result.
5463 // - Pushing the zero left requires shifting one bits in from the right.
5464 // A rotate left of ~1 is a nice way of achieving the desired result.
5465 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5466 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5467 SDLoc DL(N);
5468 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5469 N0.getOperand(1));
5470 }
5471
5472 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5473 if (N0.getOpcode() == N1.getOpcode())
5474 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5475 return Tmp;
5476
5477 // Simplify the expression using non-local knowledge.
5478 if (SimplifyDemandedBits(SDValue(N, 0)))
5479 return SDValue(N, 0);
5480
5481 return SDValue();
5482}
5483
5484/// Handle transforms common to the three shifts, when the shift amount is a
5485/// constant.
5486SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5487 SDNode *LHS = N->getOperand(0).getNode();
5488 if (!LHS->hasOneUse()) return SDValue();
5489
5490 // We want to pull some binops through shifts, so that we have (and (shift))
5491 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5492 // thing happens with address calculations, so it's important to canonicalize
5493 // it.
5494 bool HighBitSet = false; // Can we transform this if the high bit is set?
5495
5496 switch (LHS->getOpcode()) {
5497 default: return SDValue();
5498 case ISD::OR:
5499 case ISD::XOR:
5500 HighBitSet = false; // We can only transform sra if the high bit is clear.
5501 break;
5502 case ISD::AND:
5503 HighBitSet = true; // We can only transform sra if the high bit is set.
5504 break;
5505 case ISD::ADD:
5506 if (N->getOpcode() != ISD::SHL)
5507 return SDValue(); // only shl(add) not sr[al](add).
5508 HighBitSet = false; // We can only transform sra if the high bit is clear.
5509 break;
5510 }
5511
5512 // We require the RHS of the binop to be a constant and not opaque as well.
5513 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5514 if (!BinOpCst) return SDValue();
5515
5516 // FIXME: disable this unless the input to the binop is a shift by a constant
5517 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5518 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5519 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5520 BinOpLHSVal->getOpcode() == ISD::SRA ||
5521 BinOpLHSVal->getOpcode() == ISD::SRL;
5522 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5523 BinOpLHSVal->getOpcode() == ISD::SELECT;
5524
5525 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5526 !isCopyOrSelect)
5527 return SDValue();
5528
5529 if (isCopyOrSelect && N->hasOneUse())
5530 return SDValue();
5531
5532 EVT VT = N->getValueType(0);
5533
5534 // If this is a signed shift right, and the high bit is modified by the
5535 // logical operation, do not perform the transformation. The highBitSet
5536 // boolean indicates the value of the high bit of the constant which would
5537 // cause it to be modified for this operation.
5538 if (N->getOpcode() == ISD::SRA) {
5539 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5540 if (BinOpRHSSignSet != HighBitSet)
5541 return SDValue();
5542 }
5543
5544 if (!TLI.isDesirableToCommuteWithShift(LHS))
5545 return SDValue();
5546
5547 // Fold the constants, shifting the binop RHS by the shift amount.
5548 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5549 N->getValueType(0),
5550 LHS->getOperand(1), N->getOperand(1));
5551 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!")(static_cast <bool> (isa<ConstantSDNode>(NewRHS) &&
"Folding was not successful!") ? void (0) : __assert_fail ("isa<ConstantSDNode>(NewRHS) && \"Folding was not successful!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5551, __extension__ __PRETTY_FUNCTION__))
;
5552
5553 // Create the new shift.
5554 SDValue NewShift = DAG.getNode(N->getOpcode(),
5555 SDLoc(LHS->getOperand(0)),
5556 VT, LHS->getOperand(0), N->getOperand(1));
5557
5558 // Create the new binop.
5559 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5560}
5561
5562SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5563 assert(N->getOpcode() == ISD::TRUNCATE)(static_cast <bool> (N->getOpcode() == ISD::TRUNCATE
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::TRUNCATE"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5563, __extension__ __PRETTY_FUNCTION__))
;
5564 assert(N->getOperand(0).getOpcode() == ISD::AND)(static_cast <bool> (N->getOperand(0).getOpcode() ==
ISD::AND) ? void (0) : __assert_fail ("N->getOperand(0).getOpcode() == ISD::AND"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 5564, __extension__ __PRETTY_FUNCTION__))
;
5565
5566 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5567 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5568 SDValue N01 = N->getOperand(0).getOperand(1);
5569 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5570 SDLoc DL(N);
5571 EVT TruncVT = N->getValueType(0);
5572 SDValue N00 = N->getOperand(0).getOperand(0);
5573 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5574 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5575 AddToWorklist(Trunc00.getNode());
5576 AddToWorklist(Trunc01.getNode());
5577 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5578 }
5579 }
5580
5581 return SDValue();
5582}
5583
5584SDValue DAGCombiner::visitRotate(SDNode *N) {
5585 SDLoc dl(N);
5586 SDValue N0 = N->getOperand(0);
5587 SDValue N1 = N->getOperand(1);
5588 EVT VT = N->getValueType(0);
5589 unsigned Bitsize = VT.getScalarSizeInBits();
5590
5591 // fold (rot x, 0) -> x
5592 if (isNullConstantOrNullSplatConstant(N1))
5593 return N0;
5594
5595 // fold (rot x, c) -> (rot x, c % BitSize)
5596 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5597 if (Cst->getAPIntValue().uge(Bitsize)) {
5598 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5599 return DAG.getNode(N->getOpcode(), dl, VT, N0,
5600 DAG.getConstant(RotAmt, dl, N1.getValueType()));
5601 }
5602 }
5603
5604 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5605 if (N1.getOpcode() == ISD::TRUNCATE &&
5606 N1.getOperand(0).getOpcode() == ISD::AND) {
5607 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5608 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5609 }
5610
5611 unsigned NextOp = N0.getOpcode();
5612 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5613 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5614 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5615 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5616 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5617 EVT ShiftVT = C1->getValueType(0);
5618 bool SameSide = (N->getOpcode() == NextOp);
5619 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5620 if (SDValue CombinedShift =
5621 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5622 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5623 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5624 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5625 BitsizeC.getNode());
5626 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5627 CombinedShiftNorm);
5628 }
5629 }
5630 }
5631 return SDValue();
5632}
5633
5634SDValue DAGCombiner::visitSHL(SDNode *N) {
5635 SDValue N0 = N->getOperand(0);
5636 SDValue N1 = N->getOperand(1);
5637 EVT VT = N0.getValueType();
5638 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5639
5640 // fold vector ops
5641 if (VT.isVector()) {
5642 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5643 return FoldedVOp;
5644
5645 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5646 // If setcc produces all-one true value then:
5647 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5648 if (N1CV && N1CV->isConstant()) {
5649 if (N0.getOpcode() == ISD::AND) {
5650 SDValue N00 = N0->getOperand(0);
5651 SDValue N01 = N0->getOperand(1);
5652 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5653
5654 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5655 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5656 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5657 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5658 N01CV, N1CV))
5659 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5660 }
5661 }
5662 }
5663 }
5664
5665 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5666
5667 // fold (shl c1, c2) -> c1<<c2
5668 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5669 if (N0C && N1C && !N1C->isOpaque())
5670 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5671 // fold (shl 0, x) -> 0
5672 if (isNullConstantOrNullSplatConstant(N0))
5673 return N0;
5674 // fold (shl x, c >= size(x)) -> undef
5675 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5676 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5677 return Val->getAPIntValue().uge(OpSizeInBits);
5678 };
5679 if (matchUnaryPredicate(N1, MatchShiftTooBig))
5680 return DAG.getUNDEF(VT);
5681 // fold (shl x, 0) -> x
5682 if (N1C && N1C->isNullValue())
5683 return N0;
5684 // fold (shl undef, x) -> 0
5685 if (N0.isUndef())
5686 return DAG.getConstant(0, SDLoc(N), VT);
5687
5688 if (SDValue NewSel = foldBinOpIntoSelect(N))
5689 return NewSel;
5690
5691 // if (shl x, c) is known to be zero, return 0
5692 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5693 APInt::getAllOnesValue(OpSizeInBits)))
5694 return DAG.getConstant(0, SDLoc(N), VT);
5695 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5696 if (N1.getOpcode() == ISD::TRUNCATE &&
5697 N1.getOperand(0).getOpcode() == ISD::AND) {
5698 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5699 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5700 }
5701
5702 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5703 return SDValue(N, 0);
5704
5705 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5706 if (N0.getOpcode() == ISD::SHL) {
5707 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5708 ConstantSDNode *RHS) {
5709 APInt c1 = LHS->getAPIntValue();
5710 APInt c2 = RHS->getAPIntValue();
5711 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5712 return (c1 + c2).uge(OpSizeInBits);
5713 };
5714 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5715 return DAG.getConstant(0, SDLoc(N), VT);
5716
5717 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5718 ConstantSDNode *RHS) {
5719 APInt c1 = LHS->getAPIntValue();
5720 APInt c2 = RHS->getAPIntValue();
5721 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5722 return (c1 + c2).ult(OpSizeInBits);
5723 };
5724 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5725 SDLoc DL(N);
5726 EVT ShiftVT = N1.getValueType();
5727 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5728 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5729 }
5730 }
5731
5732 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5733 // For this to be valid, the second form must not preserve any of the bits
5734 // that are shifted out by the inner shift in the first form. This means
5735 // the outer shift size must be >= the number of bits added by the ext.
5736 // As a corollary, we don't care what kind of ext it is.
5737 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5738 N0.getOpcode() == ISD::ANY_EXTEND ||
5739 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5740 N0.getOperand(0).getOpcode() == ISD::SHL) {
5741 SDValue N0Op0 = N0.getOperand(0);
5742 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5743 APInt c1 = N0Op0C1->getAPIntValue();
5744 APInt c2 = N1C->getAPIntValue();
5745 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5746
5747 EVT InnerShiftVT = N0Op0.getValueType();
5748 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5749 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5750 SDLoc DL(N0);
5751 APInt Sum = c1 + c2;
5752 if (Sum.uge(OpSizeInBits))
5753 return DAG.getConstant(0, DL, VT);
5754
5755 return DAG.getNode(
5756 ISD::SHL, DL, VT,
5757 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5758 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5759 }
5760 }
5761 }
5762
5763 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5764 // Only fold this if the inner zext has no other uses to avoid increasing
5765 // the total number of instructions.
5766 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5767 N0.getOperand(0).getOpcode() == ISD::SRL) {
5768 SDValue N0Op0 = N0.getOperand(0);
5769 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5770 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5771 uint64_t c1 = N0Op0C1->getZExtValue();
5772 uint64_t c2 = N1C->getZExtValue();
5773 if (c1 == c2) {
5774 SDValue NewOp0 = N0.getOperand(0);
5775 EVT CountVT = NewOp0.getOperand(1).getValueType();
5776 SDLoc DL(N);
5777 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5778 NewOp0,
5779 DAG.getConstant(c2, DL, CountVT));
5780 AddToWorklist(NewSHL.getNode());
5781 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5782 }
5783 }
5784 }
5785 }
5786
5787 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5788 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5789 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5790 N0->getFlags().hasExact()) {
5791 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5792 uint64_t C1 = N0C1->getZExtValue();
5793 uint64_t C2 = N1C->getZExtValue();
5794 SDLoc DL(N);
5795 if (C1 <= C2)
5796 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5797 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5798 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5799 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5800 }
5801 }
5802
5803 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5804 // (and (srl x, (sub c1, c2), MASK)
5805 // Only fold this if the inner shift has no other uses -- if it does, folding
5806 // this will increase the total number of instructions.
5807 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5808 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5809 uint64_t c1 = N0C1->getZExtValue();
5810 if (c1 < OpSizeInBits) {
5811 uint64_t c2 = N1C->getZExtValue();
5812 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5813 SDValue Shift;
5814 if (c2 > c1) {
5815 Mask <<= c2 - c1;
5816 SDLoc DL(N);
5817 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5818 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5819 } else {
5820 Mask.lshrInPlace(c1 - c2);
5821 SDLoc DL(N);
5822 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5823 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5824 }
5825 SDLoc DL(N0);
5826 return DAG.getNode(ISD::AND, DL, VT, Shift,
5827 DAG.getConstant(Mask, DL, VT));
5828 }
5829 }
5830 }
5831
5832 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5833 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5834 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5835 SDLoc DL(N);
5836 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5837 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5838 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5839 }
5840
5841 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5842 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5843 // Variant of version done on multiply, except mul by a power of 2 is turned
5844 // into a shift.
5845 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5846 N0.getNode()->hasOneUse() &&
5847 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5848 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5849 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5850 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5851 AddToWorklist(Shl0.getNode());
5852 AddToWorklist(Shl1.getNode());
5853 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5854 }
5855
5856 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5857 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5858 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5859 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5860 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5861 if (isConstantOrConstantVector(Shl))
5862 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5863 }
5864
5865 if (N1C && !N1C->isOpaque())
5866 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5867 return NewSHL;
5868
5869 return SDValue();
5870}
5871
5872SDValue DAGCombiner::visitSRA(SDNode *N) {
5873 SDValue N0 = N->getOperand(0);
5874 SDValue N1 = N->getOperand(1);
5875 EVT VT = N0.getValueType();
5876 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5877
5878 // Arithmetic shifting an all-sign-bit value is a no-op.
5879 // fold (sra 0, x) -> 0
5880 // fold (sra -1, x) -> -1
5881 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5882 return N0;
5883
5884 // fold vector ops
5885 if (VT.isVector())
5886 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5887 return FoldedVOp;
5888
5889 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5890
5891 // fold (sra c1, c2) -> (sra c1, c2)
5892 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5893 if (N0C && N1C && !N1C->isOpaque())
5894 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5895 // fold (sra x, c >= size(x)) -> undef
5896 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5897 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5898 return Val->getAPIntValue().uge(OpSizeInBits);
5899 };
5900 if (matchUnaryPredicate(N1, MatchShiftTooBig))
5901 return DAG.getUNDEF(VT);
5902 // fold (sra x, 0) -> x
5903 if (N1C && N1C->isNullValue())
5904 return N0;
5905
5906 if (SDValue NewSel = foldBinOpIntoSelect(N))
5907 return NewSel;
5908
5909 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5910 // sext_inreg.
5911 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5912 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5913 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5914 if (VT.isVector())
5915 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5916 ExtVT, VT.getVectorNumElements());
5917 if ((!LegalOperations ||
5918 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5920 N0.getOperand(0), DAG.getValueType(ExtVT));
5921 }
5922
5923 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5924 if (N0.getOpcode() == ISD::SRA) {
5925 SDLoc DL(N);
5926 EVT ShiftVT = N1.getValueType();
5927
5928 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5929 ConstantSDNode *RHS) {
5930 APInt c1 = LHS->getAPIntValue();
5931 APInt c2 = RHS->getAPIntValue();
5932 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5933 return (c1 + c2).uge(OpSizeInBits);
5934 };
5935 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5936 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5937 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5938
5939 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5940 ConstantSDNode *RHS) {
5941 APInt c1 = LHS->getAPIntValue();
5942 APInt c2 = RHS->getAPIntValue();
5943 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5944 return (c1 + c2).ult(OpSizeInBits);
5945 };
5946 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5947 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5948 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5949 }
5950 }
5951
5952 // fold (sra (shl X, m), (sub result_size, n))
5953 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5954 // result_size - n != m.
5955 // If truncate is free for the target sext(shl) is likely to result in better
5956 // code.
5957 if (N0.getOpcode() == ISD::SHL && N1C) {
5958 // Get the two constanst of the shifts, CN0 = m, CN = n.
5959 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5960 if (N01C) {
5961 LLVMContext &Ctx = *DAG.getContext();
5962 // Determine what the truncate's result bitsize and type would be.
5963 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5964
5965 if (VT.isVector())
5966 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5967
5968 // Determine the residual right-shift amount.
5969 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5970
5971 // If the shift is not a no-op (in which case this should be just a sign
5972 // extend already), the truncated to type is legal, sign_extend is legal
5973 // on that type, and the truncate to that type is both legal and free,
5974 // perform the transform.
5975 if ((ShiftAmt > 0) &&
5976 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5977 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5978 TLI.isTruncateFree(VT, TruncVT)) {
5979 SDLoc DL(N);
5980 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5981 getShiftAmountTy(N0.getOperand(0).getValueType()));
5982 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5983 N0.getOperand(0), Amt);
5984 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5985 Shift);
5986 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5987 N->getValueType(0), Trunc);
5988 }
5989 }
5990 }
5991
5992 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5993 if (N1.getOpcode() == ISD::TRUNCATE &&
5994 N1.getOperand(0).getOpcode() == ISD::AND) {
5995 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5996 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5997 }
5998
5999 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
6000 // if c1 is equal to the number of bits the trunc removes
6001 if (N0.getOpcode() == ISD::TRUNCATE &&
6002 (N0.getOperand(0).getOpcode() == ISD::SRL ||
6003 N0.getOperand(0).getOpcode() == ISD::SRA) &&
6004 N0.getOperand(0).hasOneUse() &&
6005 N0.getOperand(0).getOperand(1).hasOneUse() &&
6006 N1C) {
6007 SDValue N0Op0 = N0.getOperand(0);
6008 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
6009 unsigned LargeShiftVal = LargeShift->getZExtValue();
6010 EVT LargeVT = N0Op0.getValueType();
6011
6012 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
6013 SDLoc DL(N);
6014 SDValue Amt =
6015 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
6016 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
6017 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
6018 N0Op0.getOperand(0), Amt);
6019 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
6020 }
6021 }
6022 }
6023
6024 // Simplify, based on bits shifted out of the LHS.
6025 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6026 return SDValue(N, 0);
6027
6028 // If the sign bit is known to be zero, switch this to a SRL.
6029 if (DAG.SignBitIsZero(N0))
6030 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
6031
6032 if (N1C && !N1C->isOpaque())
6033 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6034 return NewSRA;
6035
6036 return SDValue();
6037}
6038
6039SDValue DAGCombiner::visitSRL(SDNode *N) {
6040 SDValue N0 = N->getOperand(0);
6041 SDValue N1 = N->getOperand(1);
6042 EVT VT = N0.getValueType();
6043 unsigned OpSizeInBits = VT.getScalarSizeInBits();
6044
6045 // fold vector ops
6046 if (VT.isVector())
6047 if (SDValue FoldedVOp = SimplifyVBinOp(N))
6048 return FoldedVOp;
6049
6050 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6051
6052 // fold (srl c1, c2) -> c1 >>u c2
6053 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6054 if (N0C && N1C && !N1C->isOpaque())
6055 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6056 // fold (srl 0, x) -> 0
6057 if (isNullConstantOrNullSplatConstant(N0))
6058 return N0;
6059 // fold (srl x, c >= size(x)) -> undef
6060 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6061 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6062 return Val->getAPIntValue().uge(OpSizeInBits);
6063 };
6064 if (matchUnaryPredicate(N1, MatchShiftTooBig))
6065 return DAG.getUNDEF(VT);
6066 // fold (srl x, 0) -> x
6067 if (N1C && N1C->isNullValue())
6068 return N0;
6069
6070 if (SDValue NewSel = foldBinOpIntoSelect(N))
6071 return NewSel;
6072
6073 // if (srl x, c) is known to be zero, return 0
6074 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6075 APInt::getAllOnesValue(OpSizeInBits)))
6076 return DAG.getConstant(0, SDLoc(N), VT);
6077
6078 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6079 if (N0.getOpcode() == ISD::SRL) {
6080 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6081 ConstantSDNode *RHS) {
6082 APInt c1 = LHS->getAPIntValue();
6083 APInt c2 = RHS->getAPIntValue();
6084 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6085 return (c1 + c2).uge(OpSizeInBits);
6086 };
6087 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6088 return DAG.getConstant(0, SDLoc(N), VT);
6089
6090 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6091 ConstantSDNode *RHS) {
6092 APInt c1 = LHS->getAPIntValue();
6093 APInt c2 = RHS->getAPIntValue();
6094 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6095 return (c1 + c2).ult(OpSizeInBits);
6096 };
6097 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6098 SDLoc DL(N);
6099 EVT ShiftVT = N1.getValueType();
6100 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6101 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6102 }
6103 }
6104
6105 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6106 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6107 N0.getOperand(0).getOpcode() == ISD::SRL) {
6108 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6109 uint64_t c1 = N001C->getZExtValue();
6110 uint64_t c2 = N1C->getZExtValue();
6111 EVT InnerShiftVT = N0.getOperand(0).getValueType();
6112 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6113 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6114 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6115 if (c1 + OpSizeInBits == InnerShiftSize) {
6116 SDLoc DL(N0);
6117 if (c1 + c2 >= InnerShiftSize)
6118 return DAG.getConstant(0, DL, VT);
6119 return DAG.getNode(ISD::TRUNCATE, DL, VT,
6120 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6121 N0.getOperand(0).getOperand(0),
6122 DAG.getConstant(c1 + c2, DL,
6123 ShiftCountVT)));
6124 }
6125 }
6126 }
6127
6128 // fold (srl (shl x, c), c) -> (and x, cst2)
6129 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6130 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6131 SDLoc DL(N);
6132 SDValue Mask =
6133 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6134 AddToWorklist(Mask.getNode());
6135 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6136 }
6137
6138 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6139 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6140 // Shifting in all undef bits?
6141 EVT SmallVT = N0.getOperand(0).getValueType();
6142 unsigned BitSize = SmallVT.getScalarSizeInBits();
6143 if (N1C->getZExtValue() >= BitSize)
6144 return DAG.getUNDEF(VT);
6145
6146 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6147 uint64_t ShiftAmt = N1C->getZExtValue();
6148 SDLoc DL0(N0);
6149 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6150 N0.getOperand(0),
6151 DAG.getConstant(ShiftAmt, DL0,
6152 getShiftAmountTy(SmallVT)));
6153 AddToWorklist(SmallShift.getNode());
6154 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6155 SDLoc DL(N);
6156 return DAG.getNode(ISD::AND, DL, VT,
6157 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6158 DAG.getConstant(Mask, DL, VT));
6159 }
6160 }
6161
6162 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
6163 // bit, which is unmodified by sra.
6164 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6165 if (N0.getOpcode() == ISD::SRA)
6166 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6167 }
6168
6169 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
6170 if (N1C && N0.getOpcode() == ISD::CTLZ &&
6171 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6172 KnownBits Known;
6173 DAG.computeKnownBits(N0.getOperand(0), Known);
6174
6175 // If any of the input bits are KnownOne, then the input couldn't be all
6176 // zeros, thus the result of the srl will always be zero.
6177 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6178
6179 // If all of the bits input the to ctlz node are known to be zero, then
6180 // the result of the ctlz is "32" and the result of the shift is one.
6181 APInt UnknownBits = ~Known.Zero;
6182 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6183
6184 // Otherwise, check to see if there is exactly one bit input to the ctlz.
6185 if (UnknownBits.isPowerOf2()) {
6186 // Okay, we know that only that the single bit specified by UnknownBits
6187 // could be set on input to the CTLZ node. If this bit is set, the SRL
6188 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6189 // to an SRL/XOR pair, which is likely to simplify more.
6190 unsigned ShAmt = UnknownBits.countTrailingZeros();
6191 SDValue Op = N0.getOperand(0);
6192
6193 if (ShAmt) {
6194 SDLoc DL(N0);
6195 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6196 DAG.getConstant(ShAmt, DL,
6197 getShiftAmountTy(Op.getValueType())));
6198 AddToWorklist(Op.getNode());
6199 }
6200
6201 SDLoc DL(N);
6202 return DAG.getNode(ISD::XOR, DL, VT,
6203 Op, DAG.getConstant(1, DL, VT));
6204 }
6205 }
6206
6207 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6208 if (N1.getOpcode() == ISD::TRUNCATE &&
6209 N1.getOperand(0).getOpcode() == ISD::AND) {
6210 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6211 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6212 }
6213
6214 // fold operands of srl based on knowledge that the low bits are not
6215 // demanded.
6216 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6217 return SDValue(N, 0);
6218
6219 if (N1C && !N1C->isOpaque())
6220 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6221 return NewSRL;
6222
6223 // Attempt to convert a srl of a load into a narrower zero-extending load.
6224 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6225 return NarrowLoad;
6226
6227 // Here is a common situation. We want to optimize:
6228 //
6229 // %a = ...
6230 // %b = and i32 %a, 2
6231 // %c = srl i32 %b, 1
6232 // brcond i32 %c ...
6233 //
6234 // into
6235 //
6236 // %a = ...
6237 // %b = and %a, 2
6238 // %c = setcc eq %b, 0
6239 // brcond %c ...
6240 //
6241 // However when after the source operand of SRL is optimized into AND, the SRL
6242 // itself may not be optimized further. Look for it and add the BRCOND into
6243 // the worklist.
6244 if (N->hasOneUse()) {
6245 SDNode *Use = *N->use_begin();
6246 if (Use->getOpcode() == ISD::BRCOND)
6247 AddToWorklist(Use);
6248 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6249 // Also look pass the truncate.
6250 Use = *Use->use_begin();
6251 if (Use->getOpcode() == ISD::BRCOND)
6252 AddToWorklist(Use);
6253 }
6254 }
6255
6256 return SDValue();
6257}
6258
6259SDValue DAGCombiner::visitABS(SDNode *N) {
6260 SDValue N0 = N->getOperand(0);
6261 EVT VT = N->getValueType(0);
6262
6263 // fold (abs c1) -> c2
6264 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6265 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6266 // fold (abs (abs x)) -> (abs x)
6267 if (N0.getOpcode() == ISD::ABS)
6268 return N0;
6269 // fold (abs x) -> x iff not-negative
6270 if (DAG.SignBitIsZero(N0))
6271 return N0;
6272 return SDValue();
6273}
6274
6275SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6276 SDValue N0 = N->getOperand(0);
6277 EVT VT = N->getValueType(0);
6278
6279 // fold (bswap c1) -> c2
6280 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6281 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6282 // fold (bswap (bswap x)) -> x
6283 if (N0.getOpcode() == ISD::BSWAP)
6284 return N0->getOperand(0);
6285 return SDValue();
6286}
6287
6288SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6289 SDValue N0 = N->getOperand(0);
6290 EVT VT = N->getValueType(0);
6291
6292 // fold (bitreverse c1) -> c2
6293 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6294 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6295 // fold (bitreverse (bitreverse x)) -> x
6296 if (N0.getOpcode() == ISD::BITREVERSE)
6297 return N0.getOperand(0);
6298 return SDValue();
6299}
6300
6301SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6302 SDValue N0 = N->getOperand(0);
6303 EVT VT = N->getValueType(0);
6304
6305 // fold (ctlz c1) -> c2
6306 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6307 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6308
6309 // If the value is known never to be zero, switch to the undef version.
6310 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
6311 if (DAG.isKnownNeverZero(N0))
6312 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6313 }
6314
6315 return SDValue();
6316}
6317
6318SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6319 SDValue N0 = N->getOperand(0);
6320 EVT VT = N->getValueType(0);
6321
6322 // fold (ctlz_zero_undef c1) -> c2
6323 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6324 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6325 return SDValue();
6326}
6327
6328SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6329 SDValue N0 = N->getOperand(0);
6330 EVT VT = N->getValueType(0);
6331
6332 // fold (cttz c1) -> c2
6333 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6334 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6335
6336 // If the value is known never to be zero, switch to the undef version.
6337 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
6338 if (DAG.isKnownNeverZero(N0))
6339 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6340 }
6341
6342 return SDValue();
6343}
6344
6345SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6346 SDValue N0 = N->getOperand(0);
6347 EVT VT = N->getValueType(0);
6348
6349 // fold (cttz_zero_undef c1) -> c2
6350 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6351 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6352 return SDValue();
6353}
6354
6355SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6356 SDValue N0 = N->getOperand(0);
6357 EVT VT = N->getValueType(0);
6358
6359 // fold (ctpop c1) -> c2
6360 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6361 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6362 return SDValue();
6363}
6364
6365/// \brief Generate Min/Max node
6366static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6367 SDValue RHS, SDValue True, SDValue False,
6368 ISD::CondCode CC, const TargetLowering &TLI,
6369 SelectionDAG &DAG) {
6370 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6371 return SDValue();
6372
6373 switch (CC) {
6374 case ISD::SETOLT:
6375 case ISD::SETOLE:
6376 case ISD::SETLT:
6377 case ISD::SETLE:
6378 case ISD::SETULT:
6379 case ISD::SETULE: {
6380 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6381 if (TLI.isOperationLegal(Opcode, VT))
6382 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6383 return SDValue();
6384 }
6385 case ISD::SETOGT:
6386 case ISD::SETOGE:
6387 case ISD::SETGT:
6388 case ISD::SETGE:
6389 case ISD::SETUGT:
6390 case ISD::SETUGE: {
6391 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6392 if (TLI.isOperationLegal(Opcode, VT))
6393 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6394 return SDValue();
6395 }
6396 default:
6397 return SDValue();
6398 }
6399}
6400
6401SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6402 SDValue Cond = N->getOperand(0);
6403 SDValue N1 = N->getOperand(1);
6404 SDValue N2 = N->getOperand(2);
6405 EVT VT = N->getValueType(0);
6406 EVT CondVT = Cond.getValueType();
6407 SDLoc DL(N);
6408
6409 if (!VT.isInteger())
6410 return SDValue();
6411
6412 auto *C1 = dyn_cast<ConstantSDNode>(N1);
6413 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6414 if (!C1 || !C2)
6415 return SDValue();
6416
6417 // Only do this before legalization to avoid conflicting with target-specific
6418 // transforms in the other direction (create a select from a zext/sext). There
6419 // is also a target-independent combine here in DAGCombiner in the other
6420 // direction for (select Cond, -1, 0) when the condition is not i1.
6421 if (CondVT == MVT::i1 && !LegalOperations) {
6422 if (C1->isNullValue() && C2->isOne()) {
6423 // select Cond, 0, 1 --> zext (!Cond)
6424 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6425 if (VT != MVT::i1)
6426 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6427 return NotCond;
6428 }
6429 if (C1->isNullValue() && C2->isAllOnesValue()) {
6430 // select Cond, 0, -1 --> sext (!Cond)
6431 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6432 if (VT != MVT::i1)
6433 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6434 return NotCond;
6435 }
6436 if (C1->isOne() && C2->isNullValue()) {
6437 // select Cond, 1, 0 --> zext (Cond)
6438 if (VT != MVT::i1)
6439 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6440 return Cond;
6441 }
6442 if (C1->isAllOnesValue() && C2->isNullValue()) {
6443 // select Cond, -1, 0 --> sext (Cond)
6444 if (VT != MVT::i1)
6445 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6446 return Cond;
6447 }
6448
6449 // For any constants that differ by 1, we can transform the select into an
6450 // extend and add. Use a target hook because some targets may prefer to
6451 // transform in the other direction.
6452 if (TLI.convertSelectOfConstantsToMath(VT)) {
6453 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6454 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6455 if (VT != MVT::i1)
6456 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6457 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6458 }
6459 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6460 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6461 if (VT != MVT::i1)
6462 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6463 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6464 }
6465 }
6466
6467 return SDValue();
6468 }
6469
6470 // fold (select Cond, 0, 1) -> (xor Cond, 1)
6471 // We can't do this reliably if integer based booleans have different contents
6472 // to floating point based booleans. This is because we can't tell whether we
6473 // have an integer-based boolean or a floating-point-based boolean unless we
6474 // can find the SETCC that produced it and inspect its operands. This is
6475 // fairly easy if C is the SETCC node, but it can potentially be
6476 // undiscoverable (or not reasonably discoverable). For example, it could be
6477 // in another basic block or it could require searching a complicated
6478 // expression.
6479 if (CondVT.isInteger() &&
6480 TLI.getBooleanContents(false, true) ==
6481 TargetLowering::ZeroOrOneBooleanContent &&
6482 TLI.getBooleanContents(false, false) ==
6483 TargetLowering::ZeroOrOneBooleanContent &&
6484 C1->isNullValue() && C2->isOne()) {
6485 SDValue NotCond =
6486 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6487 if (VT.bitsEq(CondVT))
6488 return NotCond;
6489 return DAG.getZExtOrTrunc(NotCond, DL, VT);
6490 }
6491
6492 return SDValue();
6493}
6494
6495SDValue DAGCombiner::visitSELECT(SDNode *N) {
6496 SDValue N0 = N->getOperand(0);
6497 SDValue N1 = N->getOperand(1);
6498 SDValue N2 = N->getOperand(2);
6499 EVT VT = N->getValueType(0);
6500 EVT VT0 = N0.getValueType();
6501 SDLoc DL(N);
6502
6503 // fold (select C, X, X) -> X
6504 if (N1 == N2)
6505 return N1;
6506
6507 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6508 // fold (select true, X, Y) -> X
6509 // fold (select false, X, Y) -> Y
6510 return !N0C->isNullValue() ? N1 : N2;
6511 }
6512
6513 // fold (select X, X, Y) -> (or X, Y)
6514 // fold (select X, 1, Y) -> (or C, Y)
6515 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6516 return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6517
6518 if (SDValue V = foldSelectOfConstants(N))
6519 return V;
6520
6521 // fold (select C, 0, X) -> (and (not C), X)
6522 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6523 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6524 AddToWorklist(NOTNode.getNode());
6525 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6526 }
6527 // fold (select C, X, 1) -> (or (not C), X)
6528 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6529 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6530 AddToWorklist(NOTNode.getNode());
6531 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6532 }
6533 // fold (select X, Y, X) -> (and X, Y)
6534 // fold (select X, Y, 0) -> (and X, Y)
6535 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6536 return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6537
6538 // If we can fold this based on the true/false value, do so.
6539 if (SimplifySelectOps(N, N1, N2))
6540 return SDValue(N, 0); // Don't revisit N.
6541
6542 if (VT0 == MVT::i1) {
6543 // The code in this block deals with the following 2 equivalences:
6544 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6545 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6546 // The target can specify its preferred form with the
6547 // shouldNormalizeToSelectSequence() callback. However we always transform
6548 // to the right anyway if we find the inner select exists in the DAG anyway
6549 // and we always transform to the left side if we know that we can further
6550 // optimize the combination of the conditions.
6551 bool normalizeToSequence =
6552 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6553 // select (and Cond0, Cond1), X, Y
6554 // -> select Cond0, (select Cond1, X, Y), Y
6555 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6556 SDValue Cond0 = N0->getOperand(0);
6557 SDValue Cond1 = N0->getOperand(1);
6558 SDValue InnerSelect =
6559 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6560 if (normalizeToSequence || !InnerSelect.use_empty())
6561 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6562 InnerSelect, N2);
6563 }
6564 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6565 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6566 SDValue Cond0 = N0->getOperand(0);
6567 SDValue Cond1 = N0->getOperand(1);
6568 SDValue InnerSelect =
6569 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6570 if (normalizeToSequence || !InnerSelect.use_empty())
6571 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6572 InnerSelect);
6573 }
6574
6575 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6576 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6577 SDValue N1_0 = N1->getOperand(0);
6578 SDValue N1_1 = N1->getOperand(1);
6579 SDValue N1_2 = N1->getOperand(2);
6580 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6581 // Create the actual and node if we can generate good code for it.
6582 if (!normalizeToSequence) {
6583 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6584 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6585 }
6586 // Otherwise see if we can optimize the "and" to a better pattern.
6587 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6588 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6589 N2);
6590 }
6591 }
6592 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6593 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6594 SDValue N2_0 = N2->getOperand(0);
6595 SDValue N2_1 = N2->getOperand(1);
6596 SDValue N2_2 = N2->getOperand(2);
6597 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6598 // Create the actual or node if we can generate good code for it.
6599 if (!normalizeToSequence) {
6600 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6601 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6602 }
6603 // Otherwise see if we can optimize to a better pattern.
6604 if (SDValue Combined = visitORLike(N0, N2_0, N))
6605 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6606 N2_2);
6607 }
6608 }
6609 }
6610
6611 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6612 if (VT0 == MVT::i1) {
6613 if (N0->getOpcode() == ISD::XOR) {
6614 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6615 SDValue Cond0 = N0->getOperand(0);
6616 if (C->isOne())
6617 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6618 }
6619 }
6620 }
6621
6622 // fold selects based on a setcc into other things, such as min/max/abs
6623 if (N0.getOpcode() == ISD::SETCC) {
6624 // select x, y (fcmp lt x, y) -> fminnum x, y
6625 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6626 //
6627 // This is OK if we don't care about what happens if either operand is a
6628 // NaN.
6629 //
6630
6631 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6632 // no signed zeros as well as no nans.
6633 const TargetOptions &Options = DAG.getTarget().Options;
6634 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6635 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6636 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6637
6638 if (SDValue FMinMax = combineMinNumMaxNum(
6639 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6640 return FMinMax;
6641 }
6642
6643 if ((!LegalOperations &&
6644 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6645 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6646 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6647 N0.getOperand(1), N1, N2, N0.getOperand(2));
6648 return SimplifySelect(DL, N0, N1, N2);
6649 }
6650
6651 return SDValue();
6652}
6653
6654static
6655std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6656 SDLoc DL(N);
6657 EVT LoVT, HiVT;
6658 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6659
6660 // Split the inputs.
6661 SDValue Lo, Hi, LL, LH, RL, RH;
6662 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6663 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6664
6665 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6666 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6667
6668 return std::make_pair(Lo, Hi);
6669}
6670
6671// This function assumes all the vselect's arguments are CONCAT_VECTOR
6672// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6673static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6674 SDLoc DL(N);
6675 SDValue Cond = N->getOperand(0);
6676 SDValue LHS = N->getOperand(1);
6677 SDValue RHS = N->getOperand(2);
6678 EVT VT = N->getValueType(0);
6679 int NumElems = VT.getVectorNumElements();
6680 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&(static_cast <bool> (LHS.getOpcode() == ISD::CONCAT_VECTORS
&& RHS.getOpcode() == ISD::CONCAT_VECTORS &&
Cond.getOpcode() == ISD::BUILD_VECTOR) ? void (0) : __assert_fail
("LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6682, __extension__ __PRETTY_FUNCTION__))
6681 RHS.getOpcode() == ISD::CONCAT_VECTORS &&(static_cast <bool> (LHS.getOpcode() == ISD::CONCAT_VECTORS
&& RHS.getOpcode() == ISD::CONCAT_VECTORS &&
Cond.getOpcode() == ISD::BUILD_VECTOR) ? void (0) : __assert_fail
("LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6682, __extension__ __PRETTY_FUNCTION__))
6682 Cond.getOpcode() == ISD::BUILD_VECTOR)(static_cast <bool> (LHS.getOpcode() == ISD::CONCAT_VECTORS
&& RHS.getOpcode() == ISD::CONCAT_VECTORS &&
Cond.getOpcode() == ISD::BUILD_VECTOR) ? void (0) : __assert_fail
("LHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getOpcode() == ISD::CONCAT_VECTORS && Cond.getOpcode() == ISD::BUILD_VECTOR"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6682, __extension__ __PRETTY_FUNCTION__))
;
6683
6684 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6685 // binary ones here.
6686 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6687 return SDValue();
6688
6689 // We're sure we have an even number of elements due to the
6690 // concat_vectors we have as arguments to vselect.
6691 // Skip BV elements until we find one that's not an UNDEF
6692 // After we find an UNDEF element, keep looping until we get to half the
6693 // length of the BV and see if all the non-undef nodes are the same.
6694 ConstantSDNode *BottomHalf = nullptr;
6695 for (int i = 0; i < NumElems / 2; ++i) {
6696 if (Cond->getOperand(i)->isUndef())
6697 continue;
6698
6699 if (BottomHalf == nullptr)
6700 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6701 else if (Cond->getOperand(i).getNode() != BottomHalf)
6702 return SDValue();
6703 }
6704
6705 // Do the same for the second half of the BuildVector
6706 ConstantSDNode *TopHalf = nullptr;
6707 for (int i = NumElems / 2; i < NumElems; ++i) {
6708 if (Cond->getOperand(i)->isUndef())
6709 continue;
6710
6711 if (TopHalf == nullptr)
6712 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6713 else if (Cond->getOperand(i).getNode() != TopHalf)
6714 return SDValue();
6715 }
6716
6717 assert(TopHalf && BottomHalf &&(static_cast <bool> (TopHalf && BottomHalf &&
"One half of the selector was all UNDEFs and the other was all the "
"same value. This should have been addressed before this function."
) ? void (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6719, __extension__ __PRETTY_FUNCTION__))
6718 "One half of the selector was all UNDEFs and the other was all the "(static_cast <bool> (TopHalf && BottomHalf &&
"One half of the selector was all UNDEFs and the other was all the "
"same value. This should have been addressed before this function."
) ? void (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6719, __extension__ __PRETTY_FUNCTION__))
6719 "same value. This should have been addressed before this function.")(static_cast <bool> (TopHalf && BottomHalf &&
"One half of the selector was all UNDEFs and the other was all the "
"same value. This should have been addressed before this function."
) ? void (0) : __assert_fail ("TopHalf && BottomHalf && \"One half of the selector was all UNDEFs and the other was all the \" \"same value. This should have been addressed before this function.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 6719, __extension__ __PRETTY_FUNCTION__))
;
6720 return DAG.getNode(
6721 ISD::CONCAT_VECTORS, DL, VT,
6722 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6723 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6724}
6725
6726SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6727 if (Level >= AfterLegalizeTypes)
6728 return SDValue();
6729
6730 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6731 SDValue Mask = MSC->getMask();
6732 SDValue Data = MSC->getValue();
6733 SDLoc DL(N);
6734
6735 // If the MSCATTER data type requires splitting and the mask is provided by a
6736 // SETCC, then split both nodes and its operands before legalization. This
6737 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6738 // and enables future optimizations (e.g. min/max pattern matching on X86).
6739 if (Mask.getOpcode() != ISD::SETCC)
6740 return SDValue();
6741
6742 // Check if any splitting is required.
6743 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6744 TargetLowering::TypeSplitVector)
6745 return SDValue();
6746 SDValue MaskLo, MaskHi, Lo, Hi;
6747 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6748
6749 EVT LoVT, HiVT;
6750 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6751
6752 SDValue Chain = MSC->getChain();
6753
6754 EVT MemoryVT = MSC->getMemoryVT();
6755 unsigned Alignment = MSC->getOriginalAlignment();
6756
6757 EVT LoMemVT, HiMemVT;
6758 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6759
6760 SDValue DataLo, DataHi;
6761 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6762
6763 SDValue Scale = MSC->getScale();
6764 SDValue BasePtr = MSC->getBasePtr();
6765 SDValue IndexLo, IndexHi;
6766 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6767
6768 MachineMemOperand *MMO = DAG.getMachineFunction().
6769 getMachineMemOperand(MSC->getPointerInfo(),
6770 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6771 Alignment, MSC->getAAInfo(), MSC->getRanges());
6772
6773 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale };
6774 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6775 DL, OpsLo, MMO);
6776
6777 SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale };
6778 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6779 DL, OpsHi, MMO);
6780
6781 AddToWorklist(Lo.getNode());
6782 AddToWorklist(Hi.getNode());
6783
6784 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6785}
6786
6787SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6788 if (Level >= AfterLegalizeTypes)
6789 return SDValue();
6790
6791 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6792 SDValue Mask = MST->getMask();
6793 SDValue Data = MST->getValue();
6794 EVT VT = Data.getValueType();
6795 SDLoc DL(N);
6796
6797 // If the MSTORE data type requires splitting and the mask is provided by a
6798 // SETCC, then split both nodes and its operands before legalization. This
6799 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6800 // and enables future optimizations (e.g. min/max pattern matching on X86).
6801 if (Mask.getOpcode() == ISD::SETCC) {
6802 // Check if any splitting is required.
6803 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6804 TargetLowering::TypeSplitVector)
6805 return SDValue();
6806
6807 SDValue MaskLo, MaskHi, Lo, Hi;
6808 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6809
6810 SDValue Chain = MST->getChain();
6811 SDValue Ptr = MST->getBasePtr();
6812
6813 EVT MemoryVT = MST->getMemoryVT();
6814 unsigned Alignment = MST->getOriginalAlignment();
6815
6816 // if Alignment is equal to the vector size,
6817 // take the half of it for the second part
6818 unsigned SecondHalfAlignment =
6819 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6820
6821 EVT LoMemVT, HiMemVT;
6822 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6823
6824 SDValue DataLo, DataHi;
6825 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6826
6827 MachineMemOperand *MMO = DAG.getMachineFunction().
6828 getMachineMemOperand(MST->getPointerInfo(),
6829 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6830 Alignment, MST->getAAInfo(), MST->getRanges());
6831
6832 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6833 MST->isTruncatingStore(),
6834 MST->isCompressingStore());
6835
6836 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6837 MST->isCompressingStore());
6838
6839 MMO = DAG.getMachineFunction().
6840 getMachineMemOperand(MST->getPointerInfo(),
6841 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6842 SecondHalfAlignment, MST->getAAInfo(),
6843 MST->getRanges());
6844
6845 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6846 MST->isTruncatingStore(),
6847 MST->isCompressingStore());
6848
6849 AddToWorklist(Lo.getNode());
6850 AddToWorklist(Hi.getNode());
6851
6852 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6853 }
6854 return SDValue();
6855}
6856
6857SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6858 if (Level >= AfterLegalizeTypes)
6859 return SDValue();
6860
6861 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
6862 SDValue Mask = MGT->getMask();
6863 SDLoc DL(N);
6864
6865 // If the MGATHER result requires splitting and the mask is provided by a
6866 // SETCC, then split both nodes and its operands before legalization. This
6867 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6868 // and enables future optimizations (e.g. min/max pattern matching on X86).
6869
6870 if (Mask.getOpcode() != ISD::SETCC)
6871 return SDValue();
6872
6873 EVT VT = N->getValueType(0);
6874
6875 // Check if any splitting is required.
6876 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6877 TargetLowering::TypeSplitVector)
6878 return SDValue();
6879
6880 SDValue MaskLo, MaskHi, Lo, Hi;
6881 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6882
6883 SDValue Src0 = MGT->getValue();
6884 SDValue Src0Lo, Src0Hi;
6885 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6886
6887 EVT LoVT, HiVT;
6888 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6889
6890 SDValue Chain = MGT->getChain();
6891 EVT MemoryVT = MGT->getMemoryVT();
6892 unsigned Alignment = MGT->getOriginalAlignment();
6893
6894 EVT LoMemVT, HiMemVT;
6895 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6896
6897 SDValue Scale = MGT->getScale();
6898 SDValue BasePtr = MGT->getBasePtr();
6899 SDValue Index = MGT->getIndex();
6900 SDValue IndexLo, IndexHi;
6901 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6902
6903 MachineMemOperand *MMO = DAG.getMachineFunction().
6904 getMachineMemOperand(MGT->getPointerInfo(),
6905 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6906 Alignment, MGT->getAAInfo(), MGT->getRanges());
6907
6908 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale };
6909 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6910 MMO);
6911
6912 SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale };
6913 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6914 MMO);
6915
6916 AddToWorklist(Lo.getNode());
6917 AddToWorklist(Hi.getNode());
6918
6919 // Build a factor node to remember that this load is independent of the
6920 // other one.
6921 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6922 Hi.getValue(1));
6923
6924 // Legalized the chain result - switch anything that used the old chain to
6925 // use the new one.
6926 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6927
6928 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6929
6930 SDValue RetOps[] = { GatherRes, Chain };
6931 return DAG.getMergeValues(RetOps, DL);
6932}
6933
6934SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6935 if (Level >= AfterLegalizeTypes)
6936 return SDValue();
6937
6938 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6939 SDValue Mask = MLD->getMask();
6940 SDLoc DL(N);
6941
6942 // If the MLOAD result requires splitting and the mask is provided by a
6943 // SETCC, then split both nodes and its operands before legalization. This
6944 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6945 // and enables future optimizations (e.g. min/max pattern matching on X86).
6946 if (Mask.getOpcode() == ISD::SETCC) {
6947 EVT VT = N->getValueType(0);
6948
6949 // Check if any splitting is required.
6950 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6951 TargetLowering::TypeSplitVector)
6952 return SDValue();
6953
6954 SDValue MaskLo, MaskHi, Lo, Hi;
6955 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6956
6957 SDValue Src0 = MLD->getSrc0();
6958 SDValue Src0Lo, Src0Hi;
6959 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6960
6961 EVT LoVT, HiVT;
6962 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6963
6964 SDValue Chain = MLD->getChain();
6965 SDValue Ptr = MLD->getBasePtr();
6966 EVT MemoryVT = MLD->getMemoryVT();
6967 unsigned Alignment = MLD->getOriginalAlignment();
6968
6969 // if Alignment is equal to the vector size,
6970 // take the half of it for the second part
6971 unsigned SecondHalfAlignment =
6972 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6973 Alignment/2 : Alignment;
6974
6975 EVT LoMemVT, HiMemVT;
6976 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6977
6978 MachineMemOperand *MMO = DAG.getMachineFunction().
6979 getMachineMemOperand(MLD->getPointerInfo(),
6980 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6981 Alignment, MLD->getAAInfo(), MLD->getRanges());
6982
6983 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6984 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6985
6986 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6987 MLD->isExpandingLoad());
6988
6989 MMO = DAG.getMachineFunction().
6990 getMachineMemOperand(MLD->getPointerInfo(),
6991 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6992 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6993
6994 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6995 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6996
6997 AddToWorklist(Lo.getNode());
6998 AddToWorklist(Hi.getNode());
6999
7000 // Build a factor node to remember that this load is independent of the
7001 // other one.
7002 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7003 Hi.getValue(1));
7004
7005 // Legalized the chain result - switch anything that used the old chain to
7006 // use the new one.
7007 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
7008
7009 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7010
7011 SDValue RetOps[] = { LoadRes, Chain };
7012 return DAG.getMergeValues(RetOps, DL);
7013 }
7014 return SDValue();
7015}
7016
7017/// A vector select of 2 constant vectors can be simplified to math/logic to
7018/// avoid a variable select instruction and possibly avoid constant loads.
7019SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
7020 SDValue Cond = N->getOperand(0);
7021 SDValue N1 = N->getOperand(1);
7022 SDValue N2 = N->getOperand(2);
7023 EVT VT = N->getValueType(0);
7024 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
7025 !TLI.convertSelectOfConstantsToMath(VT) ||
7026 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
7027 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
7028 return SDValue();
7029
7030 // Check if we can use the condition value to increment/decrement a single
7031 // constant value. This simplifies a select to an add and removes a constant
7032 // load/materialization from the general case.
7033 bool AllAddOne = true;
7034 bool AllSubOne = true;
7035 unsigned Elts = VT.getVectorNumElements();
7036 for (unsigned i = 0; i != Elts; ++i) {
7037 SDValue N1Elt = N1.getOperand(i);
7038 SDValue N2Elt = N2.getOperand(i);
7039 if (N1Elt.isUndef() || N2Elt.isUndef())
7040 continue;
7041
7042 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
7043 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7044 if (C1 != C2 + 1)
7045 AllAddOne = false;
7046 if (C1 != C2 - 1)
7047 AllSubOne = false;
7048 }
7049
7050 // Further simplifications for the extra-special cases where the constants are
7051 // all 0 or all -1 should be implemented as folds of these patterns.
7052 SDLoc DL(N);
7053 if (AllAddOne || AllSubOne) {
7054 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7055 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7056 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7057 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7058 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7059 }
7060
7061 // The general case for select-of-constants:
7062 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7063 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7064 // leave that to a machine-specific pass.
7065 return SDValue();
7066}
7067
7068SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7069 SDValue N0 = N->getOperand(0);
7070 SDValue N1 = N->getOperand(1);
7071 SDValue N2 = N->getOperand(2);
7072 SDLoc DL(N);
7073
7074 // fold (vselect C, X, X) -> X
7075 if (N1 == N2)
7076 return N1;
7077
7078 // Canonicalize integer abs.
7079 // vselect (setg[te] X, 0), X, -X ->
7080 // vselect (setgt X, -1), X, -X ->
7081 // vselect (setl[te] X, 0), -X, X ->
7082 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7083 if (N0.getOpcode() == ISD::SETCC) {
7084 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7085 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7086 bool isAbs = false;
7087 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7088
7089 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7090 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7091 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7092 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7093 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7094 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7095 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7096
7097 if (isAbs) {
7098 EVT VT = LHS.getValueType();
7099 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7100 return DAG.getNode(ISD::ABS, DL, VT, LHS);
7101
7102 SDValue Shift = DAG.getNode(
7103 ISD::SRA, DL, VT, LHS,
7104 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7105 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7106 AddToWorklist(Shift.getNode());
7107 AddToWorklist(Add.getNode());
7108 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7109 }
7110 }
7111
7112 if (SimplifySelectOps(N, N1, N2))
7113 return SDValue(N, 0); // Don't revisit N.
7114
7115 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7116 if (ISD::isBuildVectorAllOnes(N0.getNode()))
7117 return N1;
7118 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7119 if (ISD::isBuildVectorAllZeros(N0.getNode()))
7120 return N2;
7121
7122 // The ConvertSelectToConcatVector function is assuming both the above
7123 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7124 // and addressed.
7125 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7126 N2.getOpcode() == ISD::CONCAT_VECTORS &&
7127 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7128 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7129 return CV;
7130 }
7131
7132 if (SDValue V = foldVSelectOfConstants(N))
7133 return V;
7134
7135 return SDValue();
7136}
7137
7138SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7139 SDValue N0 = N->getOperand(0);
7140 SDValue N1 = N->getOperand(1);
7141 SDValue N2 = N->getOperand(2);
7142 SDValue N3 = N->getOperand(3);
7143 SDValue N4 = N->getOperand(4);
7144 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7145
7146 // fold select_cc lhs, rhs, x, x, cc -> x
7147 if (N2 == N3)
7148 return N2;
7149
7150 // Determine if the condition we're dealing with is constant
7151 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7152 CC, SDLoc(N), false)) {
7153 AddToWorklist(SCC.getNode());
7154
7155 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7156 if (!SCCC->isNullValue())
7157 return N2; // cond always true -> true val
7158 else
7159 return N3; // cond always false -> false val
7160 } else if (SCC->isUndef()) {
7161 // When the condition is UNDEF, just return the first operand. This is
7162 // coherent the DAG creation, no setcc node is created in this case
7163 return N2;
7164 } else if (SCC.getOpcode() == ISD::SETCC) {
7165 // Fold to a simpler select_cc
7166 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7167 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7168 SCC.getOperand(2));
7169 }
7170 }
7171
7172 // If we can fold this based on the true/false value, do so.
7173 if (SimplifySelectOps(N, N2, N3))
7174 return SDValue(N, 0); // Don't revisit N.
7175
7176 // fold select_cc into other things, such as min/max/abs
7177 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7178}
7179
7180SDValue DAGCombiner::visitSETCC(SDNode *N) {
7181 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
7182 cast<CondCodeSDNode>(N->getOperand(2))->get(),
7183 SDLoc(N));
7184}
7185
7186SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7187 SDValue LHS = N->getOperand(0);
7188 SDValue RHS = N->getOperand(1);
7189 SDValue Carry = N->getOperand(2);
7190 SDValue Cond = N->getOperand(3);
7191
7192 // If Carry is false, fold to a regular SETCC.
7193 if (Carry.getOpcode() == ISD::CARRY_FALSE)
7194 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7195
7196 return SDValue();
7197}
7198
7199SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7200 SDValue LHS = N->getOperand(0);
7201 SDValue RHS = N->getOperand(1);
7202 SDValue Carry = N->getOperand(2);
7203 SDValue Cond = N->getOperand(3);
7204
7205 // If Carry is false, fold to a regular SETCC.
7206 if (isNullConstant(Carry))
7207 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7208
7209 return SDValue();
7210}
7211
7212/// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7213/// a build_vector of constants.
7214/// This function is called by the DAGCombiner when visiting sext/zext/aext
7215/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7216/// Vector extends are not folded if operations are legal; this is to
7217/// avoid introducing illegal build_vector dag nodes.
7218static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7219 SelectionDAG &DAG, bool LegalTypes,
7220 bool LegalOperations) {
7221 unsigned Opcode = N->getOpcode();
7222 SDValue N0 = N->getOperand(0);
7223 EVT VT = N->getValueType(0);
7224
7225 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||(static_cast <bool> ((Opcode == ISD::SIGN_EXTEND || Opcode
== ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode ==
ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG
) && "Expected EXTEND dag node in input!") ? void (0)
: __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7228, __extension__ __PRETTY_FUNCTION__))
7226 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||(static_cast <bool> ((Opcode == ISD::SIGN_EXTEND || Opcode
== ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode ==
ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG
) && "Expected EXTEND dag node in input!") ? void (0)
: __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7228, __extension__ __PRETTY_FUNCTION__))
7227 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)(static_cast <bool> ((Opcode == ISD::SIGN_EXTEND || Opcode
== ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode ==
ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG
) && "Expected EXTEND dag node in input!") ? void (0)
: __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7228, __extension__ __PRETTY_FUNCTION__))
7228 && "Expected EXTEND dag node in input!")(static_cast <bool> ((Opcode == ISD::SIGN_EXTEND || Opcode
== ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode ==
ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG
) && "Expected EXTEND dag node in input!") ? void (0)
: __assert_fail ("(Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) && \"Expected EXTEND dag node in input!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7228, __extension__ __PRETTY_FUNCTION__))
;
7229
7230 // fold (sext c1) -> c1
7231 // fold (zext c1) -> c1
7232 // fold (aext c1) -> c1
7233 if (isa<ConstantSDNode>(N0))
7234 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7235
7236 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7237 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7238 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7239 EVT SVT = VT.getScalarType();
7240 if (!(VT.isVector() &&
7241 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7242 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7243 return nullptr;
7244
7245 // We can fold this node into a build_vector.
7246 unsigned VTBits = SVT.getSizeInBits();
7247 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7248 SmallVector<SDValue, 8> Elts;
7249 unsigned NumElts = VT.getVectorNumElements();
7250 SDLoc DL(N);
7251
7252 for (unsigned i=0; i != NumElts; ++i) {
7253 SDValue Op = N0->getOperand(i);
7254 if (Op->isUndef()) {
7255 Elts.push_back(DAG.getUNDEF(SVT));
7256 continue;
7257 }
7258
7259 SDLoc DL(Op);
7260 // Get the constant value and if needed trunc it to the size of the type.
7261 // Nodes like build_vector might have constants wider than the scalar type.
7262 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7263 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7264 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7265 else
7266 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7267 }
7268
7269 return DAG.getBuildVector(VT, DL, Elts).getNode();
7270}
7271
7272// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7273// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7274// transformation. Returns true if extension are possible and the above
7275// mentioned transformation is profitable.
7276static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7277 unsigned ExtOpc,
7278 SmallVectorImpl<SDNode *> &ExtendNodes,
7279 const TargetLowering &TLI) {
7280 bool HasCopyToRegUses = false;
7281 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7282 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7283 UE = N0.getNode()->use_end();
7284 UI != UE; ++UI) {
7285 SDNode *User = *UI;
7286 if (User == N)
7287 continue;
7288 if (UI.getUse().getResNo() != N0.getResNo())
7289 continue;
7290 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7291 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7292 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7293 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7294 // Sign bits will be lost after a zext.
7295 return false;
7296 bool Add = false;
7297 for (unsigned i = 0; i != 2; ++i) {
7298 SDValue UseOp = User->getOperand(i);
7299 if (UseOp == N0)
7300 continue;
7301 if (!isa<ConstantSDNode>(UseOp))
7302 return false;
7303 Add = true;
7304 }
7305 if (Add)
7306 ExtendNodes.push_back(User);
7307 continue;
7308 }
7309 // If truncates aren't free and there are users we can't
7310 // extend, it isn't worthwhile.
7311 if (!isTruncFree)
7312 return false;
7313 // Remember if this value is live-out.
7314 if (User->getOpcode() == ISD::CopyToReg)
7315 HasCopyToRegUses = true;
7316 }
7317
7318 if (HasCopyToRegUses) {
7319 bool BothLiveOut = false;
7320 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7321 UI != UE; ++UI) {
7322 SDUse &Use = UI.getUse();
7323 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7324 BothLiveOut = true;
7325 break;
7326 }
7327 }
7328 if (BothLiveOut)
7329 // Both unextended and extended values are live out. There had better be
7330 // a good reason for the transformation.
7331 return ExtendNodes.size();
7332 }
7333 return true;
7334}
7335
7336void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7337 SDValue OrigLoad, SDValue ExtLoad,
7338 const SDLoc &DL, ISD::NodeType ExtType) {
7339 // Extend SetCC uses if necessary.
7340 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7341 SDNode *SetCC = SetCCs[i];
7342 SmallVector<SDValue, 4> Ops;
7343
7344 for (unsigned j = 0; j != 2; ++j) {
7345 SDValue SOp = SetCC->getOperand(j);
7346 if (SOp == OrigLoad)
7347 Ops.push_back(ExtLoad);
7348 else
7349 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7350 }
7351
7352 Ops.push_back(SetCC->getOperand(2));
7353 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7354 }
7355}
7356
7357// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7358SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7359 SDValue N0 = N->getOperand(0);
7360 EVT DstVT = N->getValueType(0);
7361 EVT SrcVT = N0.getValueType();
7362
7363 assert((N->getOpcode() == ISD::SIGN_EXTEND ||(static_cast <bool> ((N->getOpcode() == ISD::SIGN_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7365, __extension__ __PRETTY_FUNCTION__))
7364 N->getOpcode() == ISD::ZERO_EXTEND) &&(static_cast <bool> ((N->getOpcode() == ISD::SIGN_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7365, __extension__ __PRETTY_FUNCTION__))
7365 "Unexpected node type (not an extend)!")(static_cast <bool> ((N->getOpcode() == ISD::SIGN_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND) && "Unexpected node type (not an extend)!"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) && \"Unexpected node type (not an extend)!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7365, __extension__ __PRETTY_FUNCTION__))
;
7366
7367 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7368 // For example, on a target with legal v4i32, but illegal v8i32, turn:
7369 // (v8i32 (sext (v8i16 (load x))))
7370 // into:
7371 // (v8i32 (concat_vectors (v4i32 (sextload x)),
7372 // (v4i32 (sextload (x + 16)))))
7373 // Where uses of the original load, i.e.:
7374 // (v8i16 (load x))
7375 // are replaced with:
7376 // (v8i16 (truncate
7377 // (v8i32 (concat_vectors (v4i32 (sextload x)),
7378 // (v4i32 (sextload (x + 16)))))))
7379 //
7380 // This combine is only applicable to illegal, but splittable, vectors.
7381 // All legal types, and illegal non-vector types, are handled elsewhere.
7382 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7383 //
7384 if (N0->getOpcode() != ISD::LOAD)
7385 return SDValue();
7386
7387 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7388
7389 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7390 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7391 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7392 return SDValue();
7393
7394 SmallVector<SDNode *, 4> SetCCs;
7395 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7396 return SDValue();
7397
7398 ISD::LoadExtType ExtType =
7399 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7400
7401 // Try to split the vector types to get down to legal types.
7402 EVT SplitSrcVT = SrcVT;
7403 EVT SplitDstVT = DstVT;
7404 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7405 SplitSrcVT.getVectorNumElements() > 1) {
7406 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7407 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7408 }
7409
7410 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7411 return SDValue();
7412
7413 SDLoc DL(N);
7414 const unsigned NumSplits =
7415 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7416 const unsigned Stride = SplitSrcVT.getStoreSize();
7417 SmallVector<SDValue, 4> Loads;
7418 SmallVector<SDValue, 4> Chains;
7419
7420 SDValue BasePtr = LN0->getBasePtr();
7421 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7422 const unsigned Offset = Idx * Stride;
7423 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7424
7425 SDValue SplitLoad = DAG.getExtLoad(
7426 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7427 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7428 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7429
7430 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7431 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7432
7433 Loads.push_back(SplitLoad.getValue(0));
7434 Chains.push_back(SplitLoad.getValue(1));
7435 }
7436
7437 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7438 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7439
7440 // Simplify TF.
7441 AddToWorklist(NewChain.getNode());
7442
7443 CombineTo(N, NewValue);
7444
7445 // Replace uses of the original load (before extension)
7446 // with a truncate of the concatenated sextloaded vectors.
7447 SDValue Trunc =
7448 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7449 ExtendSetCCUses(SetCCs, N0, NewValue, DL,
7450 (ISD::NodeType)N->getOpcode());
7451 CombineTo(N0.getNode(), Trunc, NewChain);
7452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7453}
7454
7455/// If we're narrowing or widening the result of a vector select and the final
7456/// size is the same size as a setcc (compare) feeding the select, then try to
7457/// apply the cast operation to the select's operands because matching vector
7458/// sizes for a select condition and other operands should be more efficient.
7459SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7460 unsigned CastOpcode = Cast->getOpcode();
7461 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||(static_cast <bool> ((CastOpcode == ISD::SIGN_EXTEND ||
CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE
|| CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND
) && "Unexpected opcode for vector select narrowing/widening"
) ? void (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
7462 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||(static_cast <bool> ((CastOpcode == ISD::SIGN_EXTEND ||
CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE
|| CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND
) && "Unexpected opcode for vector select narrowing/widening"
) ? void (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
7463 CastOpcode == ISD::FP_ROUND) &&(static_cast <bool> ((CastOpcode == ISD::SIGN_EXTEND ||
CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE
|| CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND
) && "Unexpected opcode for vector select narrowing/widening"
) ? void (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
7464 "Unexpected opcode for vector select narrowing/widening")(static_cast <bool> ((CastOpcode == ISD::SIGN_EXTEND ||
CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE
|| CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND
) && "Unexpected opcode for vector select narrowing/widening"
) ? void (0) : __assert_fail ("(CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || CastOpcode == ISD::FP_ROUND) && \"Unexpected opcode for vector select narrowing/widening\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
;
7465
7466 // We only do this transform before legal ops because the pattern may be
7467 // obfuscated by target-specific operations after legalization. Do not create
7468 // an illegal select op, however, because that may be difficult to lower.
7469 EVT VT = Cast->getValueType(0);
7470 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7471 return SDValue();
7472
7473 SDValue VSel = Cast->getOperand(0);
7474 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7475 VSel.getOperand(0).getOpcode() != ISD::SETCC)
7476 return SDValue();
7477
7478 // Does the setcc have the same vector size as the casted select?
7479 SDValue SetCC = VSel.getOperand(0);
7480 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7481 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7482 return SDValue();
7483
7484 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7485 SDValue A = VSel.getOperand(1);
7486 SDValue B = VSel.getOperand(2);
7487 SDValue CastA, CastB;
7488 SDLoc DL(Cast);
7489 if (CastOpcode == ISD::FP_ROUND) {
7490 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7491 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7492 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7493 } else {
7494 CastA = DAG.getNode(CastOpcode, DL, VT, A);
7495 CastB = DAG.getNode(CastOpcode, DL, VT, B);
7496 }
7497 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7498}
7499
7500SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7501 SDValue N0 = N->getOperand(0);
7502 EVT VT = N->getValueType(0);
7503 SDLoc DL(N);
7504
7505 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7506 LegalOperations))
7507 return SDValue(Res, 0);
7508
7509 // fold (sext (sext x)) -> (sext x)
7510 // fold (sext (aext x)) -> (sext x)
7511 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7512 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7513
7514 if (N0.getOpcode() == ISD::TRUNCATE) {
7515 // fold (sext (truncate (load x))) -> (sext (smaller load x))
7516 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7517 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7518 SDNode *oye = N0.getOperand(0).getNode();
7519 if (NarrowLoad.getNode() != N0.getNode()) {
7520 CombineTo(N0.getNode(), NarrowLoad);
7521 // CombineTo deleted the truncate, if needed, but not what's under it.
7522 AddToWorklist(oye);
7523 }
7524 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7525 }
7526
7527 // See if the value being truncated is already sign extended. If so, just
7528 // eliminate the trunc/sext pair.
7529 SDValue Op = N0.getOperand(0);
7530 unsigned OpBits = Op.getScalarValueSizeInBits();
7531 unsigned MidBits = N0.getScalarValueSizeInBits();
7532 unsigned DestBits = VT.getScalarSizeInBits();
7533 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7534
7535 if (OpBits == DestBits) {
7536 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7537 // bits, it is already ready.
7538 if (NumSignBits > DestBits-MidBits)
7539 return Op;
7540 } else if (OpBits < DestBits) {
7541 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7542 // bits, just sext from i32.
7543 if (NumSignBits > OpBits-MidBits)
7544 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7545 } else {
7546 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7547 // bits, just truncate to i32.
7548 if (NumSignBits > OpBits-MidBits)
7549 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7550 }
7551
7552 // fold (sext (truncate x)) -> (sextinreg x).
7553 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7554 N0.getValueType())) {
7555 if (OpBits < DestBits)
7556 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7557 else if (OpBits > DestBits)
7558 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7559 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7560 DAG.getValueType(N0.getValueType()));
7561 }
7562 }
7563
7564 // fold (sext (load x)) -> (sext (truncate (sextload x)))
7565 // Only generate vector extloads when 1) they're legal, and 2) they are
7566 // deemed desirable by the target.
7567 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7568 ((!LegalOperations && !VT.isVector() &&
7569 !cast<LoadSDNode>(N0)->isVolatile()) ||
7570 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7571 bool DoXform = true;
7572 SmallVector<SDNode*, 4> SetCCs;
7573 if (!N0.hasOneUse())
7574 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7575 if (VT.isVector())
7576 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7577 if (DoXform) {
7578 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7579 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7580 LN0->getBasePtr(), N0.getValueType(),
7581 LN0->getMemOperand());
7582 ExtendSetCCUses(SetCCs, N0, ExtLoad, DL, ISD::SIGN_EXTEND);
7583 // If the load value is used only by N, replace it via CombineTo N.
7584 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7585 CombineTo(N, ExtLoad);
7586 if (NoReplaceTrunc) {
7587 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7588 } else {
7589 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7590 N0.getValueType(), ExtLoad);
7591 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7592 }
7593 return SDValue(N, 0);
7594 }
7595 }
7596
7597 // fold (sext (load x)) to multiple smaller sextloads.
7598 // Only on illegal but splittable vectors.
7599 if (SDValue ExtLoad = CombineExtLoad(N))
7600 return ExtLoad;
7601
7602 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7603 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7604 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7605 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7606 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7607 EVT MemVT = LN0->getMemoryVT();
7608 if ((!LegalOperations && !LN0->isVolatile()) ||
7609 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7610 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7611 LN0->getBasePtr(), MemVT,
7612 LN0->getMemOperand());
7613 CombineTo(N, ExtLoad);
7614 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7615 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7616 }
7617 }
7618
7619 // fold (sext (and/or/xor (load x), cst)) ->
7620 // (and/or/xor (sextload x), (sext cst))
7621 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7622 N0.getOpcode() == ISD::XOR) &&
7623 isa<LoadSDNode>(N0.getOperand(0)) &&
7624 N0.getOperand(1).getOpcode() == ISD::Constant &&
7625 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7626 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
7627 EVT MemVT = LN00->getMemoryVT();
7628 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
7629 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
7630 bool DoXform = true;
7631 SmallVector<SDNode*, 4> SetCCs;
7632 if (!N0.hasOneUse())
7633 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7634 SetCCs, TLI);
7635 if (DoXform) {
7636 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
7637 LN00->getChain(), LN00->getBasePtr(),
7638 LN00->getMemoryVT(),
7639 LN00->getMemOperand());
7640 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7641 Mask = Mask.sext(VT.getSizeInBits());
7642 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7643 ExtLoad, DAG.getConstant(Mask, DL, VT));
7644 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL,
7645 ISD::SIGN_EXTEND);
7646 bool NoReplaceTruncAnd = !N0.hasOneUse();
7647 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
7648 CombineTo(N, And);
7649 // If N0 has multiple uses, change other uses as well.
7650 if (NoReplaceTruncAnd) {
7651 SDValue TruncAnd =
7652 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7653 CombineTo(N0.getNode(), TruncAnd);
7654 }
7655 if (NoReplaceTrunc) {
7656 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
7657 } else {
7658 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
7659 LN00->getValueType(0), ExtLoad);
7660 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
7661 }
7662 return SDValue(N,0); // Return N so it doesn't get rechecked!
7663 }
7664 }
7665 }
7666
7667 if (N0.getOpcode() == ISD::SETCC) {
7668 SDValue N00 = N0.getOperand(0);
7669 SDValue N01 = N0.getOperand(1);
7670 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7671 EVT N00VT = N0.getOperand(0).getValueType();
7672
7673 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7674 // Only do this before legalize for now.
7675 if (VT.isVector() && !LegalOperations &&
7676 TLI.getBooleanContents(N00VT) ==
7677 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7678 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7679 // of the same size as the compared operands. Only optimize sext(setcc())
7680 // if this is the case.
7681 EVT SVT = getSetCCResultType(N00VT);
7682
7683 // We know that the # elements of the results is the same as the
7684 // # elements of the compare (and the # elements of the compare result
7685 // for that matter). Check to see that they are the same size. If so,
7686 // we know that the element size of the sext'd result matches the
7687 // element size of the compare operands.
7688 if (VT.getSizeInBits() == SVT.getSizeInBits())
7689 return DAG.getSetCC(DL, VT, N00, N01, CC);
7690
7691 // If the desired elements are smaller or larger than the source
7692 // elements, we can use a matching integer vector type and then
7693 // truncate/sign extend.
7694 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7695 if (SVT == MatchingVecType) {
7696 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7697 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7698 }
7699 }
7700
7701 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7702 // Here, T can be 1 or -1, depending on the type of the setcc and
7703 // getBooleanContents().
7704 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7705
7706 // To determine the "true" side of the select, we need to know the high bit
7707 // of the value returned by the setcc if it evaluates to true.
7708 // If the type of the setcc is i1, then the true case of the select is just
7709 // sext(i1 1), that is, -1.
7710 // If the type of the setcc is larger (say, i8) then the value of the high
7711 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7712 // of the appropriate width.
7713 SDValue ExtTrueVal = (SetCCWidth == 1)
7714 ? DAG.getAllOnesConstant(DL, VT)
7715 : DAG.getBoolConstant(true, DL, VT, N00VT);
7716 SDValue Zero = DAG.getConstant(0, DL, VT);
7717 if (SDValue SCC =
7718 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7719 return SCC;
7720
7721 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7722 EVT SetCCVT = getSetCCResultType(N00VT);
7723 // Don't do this transform for i1 because there's a select transform
7724 // that would reverse it.
7725 // TODO: We should not do this transform at all without a target hook
7726 // because a sext is likely cheaper than a select?
7727 if (SetCCVT.getScalarSizeInBits() != 1 &&
7728 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7729 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7730 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7731 }
7732 }
7733 }
7734
7735 // fold (sext x) -> (zext x) if the sign bit is known zero.
7736 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7737 DAG.SignBitIsZero(N0))
7738 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7739
7740 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7741 return NewVSel;
7742
7743 return SDValue();
7744}
7745
7746// isTruncateOf - If N is a truncate of some other value, return true, record
7747// the value being truncated in Op and which of Op's bits are zero/one in Known.
7748// This function computes KnownBits to avoid a duplicated call to
7749// computeKnownBits in the caller.
7750static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7751 KnownBits &Known) {
7752 if (N->getOpcode() == ISD::TRUNCATE) {
7753 Op = N->getOperand(0);
7754 DAG.computeKnownBits(Op, Known);
7755 return true;
7756 }
7757
7758 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7759 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7760 return false;
7761
7762 SDValue Op0 = N->getOperand(0);
7763 SDValue Op1 = N->getOperand(1);
7764 assert(Op0.getValueType() == Op1.getValueType())(static_cast <bool> (Op0.getValueType() == Op1.getValueType
()) ? void (0) : __assert_fail ("Op0.getValueType() == Op1.getValueType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 7764, __extension__ __PRETTY_FUNCTION__))
;
7765
7766 if (isNullConstant(Op0))
7767 Op = Op1;
7768 else if (isNullConstant(Op1))
7769 Op = Op0;
7770 else
7771 return false;
7772
7773 DAG.computeKnownBits(Op, Known);
7774
7775 if (!(Known.Zero | 1).isAllOnesValue())
7776 return false;
7777
7778 return true;
7779}
7780
7781SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7782 SDValue N0 = N->getOperand(0);
7783 EVT VT = N->getValueType(0);
7784
7785 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7786 LegalOperations))
7787 return SDValue(Res, 0);
7788
7789 // fold (zext (zext x)) -> (zext x)
7790 // fold (zext (aext x)) -> (zext x)
7791 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7792 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7793 N0.getOperand(0));
7794
7795 // fold (zext (truncate x)) -> (zext x) or
7796 // (zext (truncate x)) -> (truncate x)
7797 // This is valid when the truncated bits of x are already zero.
7798 // FIXME: We should extend this to work for vectors too.
7799 SDValue Op;
7800 KnownBits Known;
7801 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7802 APInt TruncatedBits =
7803 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7804 APInt(Op.getValueSizeInBits(), 0) :
7805 APInt::getBitsSet(Op.getValueSizeInBits(),
7806 N0.getValueSizeInBits(),
7807 std::min(Op.getValueSizeInBits(),
7808 VT.getSizeInBits()));
7809 if (TruncatedBits.isSubsetOf(Known.Zero))
7810 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7811 }
7812
7813 // fold (zext (truncate x)) -> (and x, mask)
7814 if (N0.getOpcode() == ISD::TRUNCATE) {
7815 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7816 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7817 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7818 SDNode *oye = N0.getOperand(0).getNode();
7819 if (NarrowLoad.getNode() != N0.getNode()) {
7820 CombineTo(N0.getNode(), NarrowLoad);
7821 // CombineTo deleted the truncate, if needed, but not what's under it.
7822 AddToWorklist(oye);
7823 }
7824 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7825 }
7826
7827 EVT SrcVT = N0.getOperand(0).getValueType();
7828 EVT MinVT = N0.getValueType();
7829
7830 // Try to mask before the extension to avoid having to generate a larger mask,
7831 // possibly over several sub-vectors.
7832 if (SrcVT.bitsLT(VT)) {
7833 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7834 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7835 SDValue Op = N0.getOperand(0);
7836 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7837 AddToWorklist(Op.getNode());
7838 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7839 // Transfer the debug info; the new node is equivalent to N0.
7840 DAG.transferDbgValues(N0, ZExtOrTrunc);
7841 return ZExtOrTrunc;
7842 }
7843 }
7844
7845 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7846 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7847 AddToWorklist(Op.getNode());
7848 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7849 // We may safely transfer the debug info describing the truncate node over
7850 // to the equivalent and operation.
7851 DAG.transferDbgValues(N0, And);
7852 return And;
7853 }
7854 }
7855
7856 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7857 // if either of the casts is not free.
7858 if (N0.getOpcode() == ISD::AND &&
7859 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7860 N0.getOperand(1).getOpcode() == ISD::Constant &&
7861 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7862 N0.getValueType()) ||
7863 !TLI.isZExtFree(N0.getValueType(), VT))) {
7864 SDValue X = N0.getOperand(0).getOperand(0);
7865 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7866 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7867 Mask = Mask.zext(VT.getSizeInBits());
7868 SDLoc DL(N);
7869 return DAG.getNode(ISD::AND, DL, VT,
7870 X, DAG.getConstant(Mask, DL, VT));
7871 }
7872
7873 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7874 // Only generate vector extloads when 1) they're legal, and 2) they are
7875 // deemed desirable by the target.
7876 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7877 ((!LegalOperations && !VT.isVector() &&
7878 !cast<LoadSDNode>(N0)->isVolatile()) ||
7879 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7880 bool DoXform = true;
7881 SmallVector<SDNode*, 4> SetCCs;
7882 if (!N0.hasOneUse())
7883 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7884 if (VT.isVector())
7885 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7886 if (DoXform) {
7887 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7888 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7889 LN0->getChain(),
7890 LN0->getBasePtr(), N0.getValueType(),
7891 LN0->getMemOperand());
7892
7893 ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7894 // If the load value is used only by N, replace it via CombineTo N.
7895 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7896 CombineTo(N, ExtLoad);
7897 if (NoReplaceTrunc) {
7898 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7899 } else {
7900 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7901 N0.getValueType(), ExtLoad);
7902 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7903 }
7904 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7905 }
7906 }
7907
7908 // fold (zext (load x)) to multiple smaller zextloads.
7909 // Only on illegal but splittable vectors.
7910 if (SDValue ExtLoad = CombineExtLoad(N))
7911 return ExtLoad;
7912
7913 // fold (zext (and/or/xor (load x), cst)) ->
7914 // (and/or/xor (zextload x), (zext cst))
7915 // Unless (and (load x) cst) will match as a zextload already and has
7916 // additional users.
7917 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7918 N0.getOpcode() == ISD::XOR) &&
7919 isa<LoadSDNode>(N0.getOperand(0)) &&
7920 N0.getOperand(1).getOpcode() == ISD::Constant &&
7921 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7922 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
7923 EVT MemVT = LN00->getMemoryVT();
7924 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
7925 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
7926 bool DoXform = true;
7927 SmallVector<SDNode*, 4> SetCCs;
7928 if (!N0.hasOneUse()) {
7929 if (N0.getOpcode() == ISD::AND) {
7930 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7931 EVT LoadResultTy = AndC->getValueType(0);
7932 EVT ExtVT;
7933 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
7934 DoXform = false;
7935 }
7936 if (DoXform)
7937 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7938 ISD::ZERO_EXTEND, SetCCs, TLI);
7939 }
7940 if (DoXform) {
7941 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
7942 LN00->getChain(), LN00->getBasePtr(),
7943 LN00->getMemoryVT(),
7944 LN00->getMemOperand());
7945 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7946 Mask = Mask.zext(VT.getSizeInBits());
7947 SDLoc DL(N);
7948 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7949 ExtLoad, DAG.getConstant(Mask, DL, VT));
7950 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL,
7951 ISD::ZERO_EXTEND);
7952 bool NoReplaceTruncAnd = !N0.hasOneUse();
7953 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
7954 CombineTo(N, And);
7955 // If N0 has multiple uses, change other uses as well.
7956 if (NoReplaceTruncAnd) {
7957 SDValue TruncAnd =
7958 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7959 CombineTo(N0.getNode(), TruncAnd);
7960 }
7961 if (NoReplaceTrunc) {
7962 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
7963 } else {
7964 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
7965 LN00->getValueType(0), ExtLoad);
7966 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
7967 }
7968 return SDValue(N,0); // Return N so it doesn't get rechecked!
7969 }
7970 }
7971 }
7972
7973 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7974 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7975 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7976 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7977 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7978 EVT MemVT = LN0->getMemoryVT();
7979 if ((!LegalOperations && !LN0->isVolatile()) ||
7980 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7981 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7982 LN0->getChain(),
7983 LN0->getBasePtr(), MemVT,
7984 LN0->getMemOperand());
7985 CombineTo(N, ExtLoad);
7986 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7987 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7988 }
7989 }
7990
7991 if (N0.getOpcode() == ISD::SETCC) {
7992 // Only do this before legalize for now.
7993 if (!LegalOperations && VT.isVector() &&
7994 N0.getValueType().getVectorElementType() == MVT::i1) {
7995 EVT N00VT = N0.getOperand(0).getValueType();
7996 if (getSetCCResultType(N00VT) == N0.getValueType())
7997 return SDValue();
7998
7999 // We know that the # elements of the results is the same as the #
8000 // elements of the compare (and the # elements of the compare result for
8001 // that matter). Check to see that they are the same size. If so, we know
8002 // that the element size of the sext'd result matches the element size of
8003 // the compare operands.
8004 SDLoc DL(N);
8005 SDValue VecOnes = DAG.getConstant(1, DL, VT);
8006 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
8007 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
8008 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
8009 N0.getOperand(1), N0.getOperand(2));
8010 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
8011 }
8012
8013 // If the desired elements are smaller or larger than the source
8014 // elements we can use a matching integer vector type and then
8015 // truncate/sign extend.
8016 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8017 SDValue VsetCC =
8018 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
8019 N0.getOperand(1), N0.getOperand(2));
8020 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
8021 VecOnes);
8022 }
8023
8024 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8025 SDLoc DL(N);
8026 if (SDValue SCC = SimplifySelectCC(
8027 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8028 DAG.getConstant(0, DL, VT),
8029 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8030 return SCC;
8031 }
8032
8033 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
8034 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
8035 isa<ConstantSDNode>(N0.getOperand(1)) &&
8036 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
8037 N0.hasOneUse()) {
8038 SDValue ShAmt = N0.getOperand(1);
8039 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8040 if (N0.getOpcode() == ISD::SHL) {
8041 SDValue InnerZExt = N0.getOperand(0);
8042 // If the original shl may be shifting out bits, do not perform this
8043 // transformation.
8044 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
8045 InnerZExt.getOperand(0).getValueSizeInBits();
8046 if (ShAmtVal > KnownZeroBits)
8047 return SDValue();
8048 }
8049
8050 SDLoc DL(N);
8051
8052 // Ensure that the shift amount is wide enough for the shifted value.
8053 if (VT.getSizeInBits() >= 256)
8054 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8055
8056 return DAG.getNode(N0.getOpcode(), DL, VT,
8057 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8058 ShAmt);
8059 }
8060
8061 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8062 return NewVSel;
8063
8064 return SDValue();
8065}
8066
8067SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8068 SDValue N0 = N->getOperand(0);
8069 EVT VT = N->getValueType(0);
8070
8071 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8072 LegalOperations))
8073 return SDValue(Res, 0);
8074
8075 // fold (aext (aext x)) -> (aext x)
8076 // fold (aext (zext x)) -> (zext x)
8077 // fold (aext (sext x)) -> (sext x)
8078 if (N0.getOpcode() == ISD::ANY_EXTEND ||
8079 N0.getOpcode() == ISD::ZERO_EXTEND ||
8080 N0.getOpcode() == ISD::SIGN_EXTEND)
8081 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8082
8083 // fold (aext (truncate (load x))) -> (aext (smaller load x))
8084 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8085 if (N0.getOpcode() == ISD::TRUNCATE) {
8086 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8087 SDNode *oye = N0.getOperand(0).getNode();
8088 if (NarrowLoad.getNode() != N0.getNode()) {
8089 CombineTo(N0.getNode(), NarrowLoad);
8090 // CombineTo deleted the truncate, if needed, but not what's under it.
8091 AddToWorklist(oye);
8092 }
8093 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8094 }
8095 }
8096
8097 // fold (aext (truncate x))
8098 if (N0.getOpcode() == ISD::TRUNCATE)
8099 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8100
8101 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8102 // if the trunc is not free.
8103 if (N0.getOpcode() == ISD::AND &&
8104 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8105 N0.getOperand(1).getOpcode() == ISD::Constant &&
8106 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8107 N0.getValueType())) {
8108 SDLoc DL(N);
8109 SDValue X = N0.getOperand(0).getOperand(0);
8110 X = DAG.getAnyExtOrTrunc(X, DL, VT);
8111 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8112 Mask = Mask.zext(VT.getSizeInBits());
8113 return DAG.getNode(ISD::AND, DL, VT,
8114 X, DAG.getConstant(Mask, DL, VT));
8115 }
8116
8117 // fold (aext (load x)) -> (aext (truncate (extload x)))
8118 // None of the supported targets knows how to perform load and any_ext
8119 // on vectors in one instruction. We only perform this transformation on
8120 // scalars.
8121 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8122 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8123 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8124 bool DoXform = true;
8125 SmallVector<SDNode*, 4> SetCCs;
8126 if (!N0.hasOneUse())
8127 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
8128 if (DoXform) {
8129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8130 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8131 LN0->getChain(),
8132 LN0->getBasePtr(), N0.getValueType(),
8133 LN0->getMemOperand());
8134 ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N),
8135 ISD::ANY_EXTEND);
8136 // If the load value is used only by N, replace it via CombineTo N.
8137 bool NoReplaceTrunc = N0.hasOneUse();
8138 CombineTo(N, ExtLoad);
8139 if (NoReplaceTrunc) {
8140 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8141 } else {
8142 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8143 N0.getValueType(), ExtLoad);
8144 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8145 }
8146 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8147 }
8148 }
8149
8150 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8151 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8152 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
8153 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
8154 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
8155 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8156 ISD::LoadExtType ExtType = LN0->getExtensionType();
8157 EVT MemVT = LN0->getMemoryVT();
8158 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8159 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8160 VT, LN0->getChain(), LN0->getBasePtr(),
8161 MemVT, LN0->getMemOperand());
8162 CombineTo(N, ExtLoad);
8163 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8164 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8165 }
8166 }
8167
8168 if (N0.getOpcode() == ISD::SETCC) {
8169 // For vectors:
8170 // aext(setcc) -> vsetcc
8171 // aext(setcc) -> truncate(vsetcc)
8172 // aext(setcc) -> aext(vsetcc)
8173 // Only do this before legalize for now.
8174 if (VT.isVector() && !LegalOperations) {
8175 EVT N00VT = N0.getOperand(0).getValueType();
8176 if (getSetCCResultType(N00VT) == N0.getValueType())
8177 return SDValue();
8178
8179 // We know that the # elements of the results is the same as the
8180 // # elements of the compare (and the # elements of the compare result
8181 // for that matter). Check to see that they are the same size. If so,
8182 // we know that the element size of the sext'd result matches the
8183 // element size of the compare operands.
8184 if (VT.getSizeInBits() == N00VT.getSizeInBits())
8185 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8186 N0.getOperand(1),
8187 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8188 // If the desired elements are smaller or larger than the source
8189 // elements we can use a matching integer vector type and then
8190 // truncate/any extend
8191 else {
8192 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8193 SDValue VsetCC =
8194 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8195 N0.getOperand(1),
8196 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8197 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8198 }
8199 }
8200
8201 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8202 SDLoc DL(N);
8203 if (SDValue SCC = SimplifySelectCC(
8204 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8205 DAG.getConstant(0, DL, VT),
8206 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8207 return SCC;
8208 }
8209
8210 return SDValue();
8211}
8212
8213SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8214 unsigned Opcode = N->getOpcode();
8215 SDValue N0 = N->getOperand(0);
8216 SDValue N1 = N->getOperand(1);
8217 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8218
8219 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8220 if (N0.getOpcode() == Opcode &&
8221 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8222 return N0;
8223
8224 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8225 N0.getOperand(0).getOpcode() == Opcode) {
8226 // We have an assert, truncate, assert sandwich. Make one stronger assert
8227 // by asserting on the smallest asserted type to the larger source type.
8228 // This eliminates the later assert:
8229 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8230 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8231 SDValue BigA = N0.getOperand(0);
8232 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8233 assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&(static_cast <bool> (BigA_AssertVT.bitsLE(N0.getValueType
()) && "Asserting zero/sign-extended bits to a type larger than the "
"truncated destination does not provide information") ? void
(0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8235, __extension__ __PRETTY_FUNCTION__))
8234 "Asserting zero/sign-extended bits to a type larger than the "(static_cast <bool> (BigA_AssertVT.bitsLE(N0.getValueType
()) && "Asserting zero/sign-extended bits to a type larger than the "
"truncated destination does not provide information") ? void
(0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8235, __extension__ __PRETTY_FUNCTION__))
8235 "truncated destination does not provide information")(static_cast <bool> (BigA_AssertVT.bitsLE(N0.getValueType
()) && "Asserting zero/sign-extended bits to a type larger than the "
"truncated destination does not provide information") ? void
(0) : __assert_fail ("BigA_AssertVT.bitsLE(N0.getValueType()) && \"Asserting zero/sign-extended bits to a type larger than the \" \"truncated destination does not provide information\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8235, __extension__ __PRETTY_FUNCTION__))
;
8236
8237 SDLoc DL(N);
8238 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8239 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8240 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8241 BigA.getOperand(0), MinAssertVTVal);
8242 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8243 }
8244
8245 return SDValue();
8246}
8247
8248/// If the result of a wider load is shifted to right of N bits and then
8249/// truncated to a narrower type and where N is a multiple of number of bits of
8250/// the narrower type, transform it to a narrower load from address + N / num of
8251/// bits of new type. Also narrow the load if the result is masked with an AND
8252/// to effectively produce a smaller type. If the result is to be extended, also
8253/// fold the extension to form a extending load.
8254SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8255 unsigned Opc = N->getOpcode();
8256
8257 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8258 SDValue N0 = N->getOperand(0);
8259 EVT VT = N->getValueType(0);
8260 EVT ExtVT = VT;
8261
8262 // This transformation isn't valid for vector loads.
8263 if (VT.isVector())
8264 return SDValue();
8265
8266 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8267 // extended to VT.
8268 if (Opc == ISD::SIGN_EXTEND_INREG) {
8269 ExtType = ISD::SEXTLOAD;
8270 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8271 } else if (Opc == ISD::SRL) {
8272 // Another special-case: SRL is basically zero-extending a narrower value,
8273 // or it maybe shifting a higher subword, half or byte into the lowest
8274 // bits.
8275 ExtType = ISD::ZEXTLOAD;
8276 N0 = SDValue(N, 0);
8277
8278 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8279 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8280 if (!N01 || !LN0)
8281 return SDValue();
8282
8283 uint64_t ShiftAmt = N01->getZExtValue();
8284 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8285 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8286 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8287 else
8288 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8289 VT.getSizeInBits() - ShiftAmt);
8290 } else if (Opc == ISD::AND) {
8291 // An AND with a constant mask is the same as a truncate + zero-extend.
8292 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8293 if (!AndC || !AndC->getAPIntValue().isMask())
8294 return SDValue();
8295
8296 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8297 ExtType = ISD::ZEXTLOAD;
8298 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8299 }
8300
8301 unsigned ShAmt = 0;
8302 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8303 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8304 ShAmt = N01->getZExtValue();
8305 unsigned EVTBits = ExtVT.getSizeInBits();
8306 // Is the shift amount a multiple of size of VT?
8307 if ((ShAmt & (EVTBits-1)) == 0) {
8308 N0 = N0.getOperand(0);
8309 // Is the load width a multiple of size of VT?
8310 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8311 return SDValue();
8312 }
8313
8314 // At this point, we must have a load or else we can't do the transform.
8315 if (!isa<LoadSDNode>(N0)) return SDValue();
8316
8317 // Because a SRL must be assumed to *need* to zero-extend the high bits
8318 // (as opposed to anyext the high bits), we can't combine the zextload
8319 // lowering of SRL and an sextload.
8320 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8321 return SDValue();
8322
8323 // If the shift amount is larger than the input type then we're not
8324 // accessing any of the loaded bytes. If the load was a zextload/extload
8325 // then the result of the shift+trunc is zero/undef (handled elsewhere).
8326 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8327 return SDValue();
8328 }
8329 }
8330
8331 // If the load is shifted left (and the result isn't shifted back right),
8332 // we can fold the truncate through the shift.
8333 unsigned ShLeftAmt = 0;
8334 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8335 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8336 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8337 ShLeftAmt = N01->getZExtValue();
8338 N0 = N0.getOperand(0);
8339 }
8340 }
8341
8342 // If we haven't found a load, we can't narrow it.
8343 if (!isa<LoadSDNode>(N0))
8344 return SDValue();
8345
8346 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8347 if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8348 return SDValue();
8349
8350 // For big endian targets, we need to adjust the offset to the pointer to
8351 // load the correct bytes.
8352 if (DAG.getDataLayout().isBigEndian()) {
8353 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8354 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8355 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8356 }
8357
8358 EVT PtrType = N0.getOperand(1).getValueType();
8359 uint64_t PtrOff = ShAmt / 8;
8360 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8361 SDLoc DL(LN0);
8362 // The original load itself didn't wrap, so an offset within it doesn't.
8363 SDNodeFlags Flags;
8364 Flags.setNoUnsignedWrap(true);
8365 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8366 PtrType, LN0->getBasePtr(),
8367 DAG.getConstant(PtrOff, DL, PtrType),
8368 Flags);
8369 AddToWorklist(NewPtr.getNode());
8370
8371 SDValue Load;
8372 if (ExtType == ISD::NON_EXTLOAD)
8373 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8374 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8375 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8376 else
8377 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8378 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8379 NewAlign, LN0->getMemOperand()->getFlags(),
8380 LN0->getAAInfo());
8381
8382 // Replace the old load's chain with the new load's chain.
8383 WorklistRemover DeadNodes(*this);
8384 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8385
8386 // Shift the result left, if we've swallowed a left shift.
8387 SDValue Result = Load;
8388 if (ShLeftAmt != 0) {
8389 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8390 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8391 ShImmTy = VT;
8392 // If the shift amount is as large as the result size (but, presumably,
8393 // no larger than the source) then the useful bits of the result are
8394 // zero; we can't simply return the shortened shift, because the result
8395 // of that operation is undefined.
8396 SDLoc DL(N0);
8397 if (ShLeftAmt >= VT.getSizeInBits())
8398 Result = DAG.getConstant(0, DL, VT);
8399 else
8400 Result = DAG.getNode(ISD::SHL, DL, VT,
8401 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8402 }
8403
8404 // Return the new loaded value.
8405 return Result;
8406}
8407
8408SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8409 SDValue N0 = N->getOperand(0);
8410 SDValue N1 = N->getOperand(1);
8411 EVT VT = N->getValueType(0);
8412 EVT EVT = cast<VTSDNode>(N1)->getVT();
8413 unsigned VTBits = VT.getScalarSizeInBits();
8414 unsigned EVTBits = EVT.getScalarSizeInBits();
8415
8416 if (N0.isUndef())
8417 return DAG.getUNDEF(VT);
8418
8419 // fold (sext_in_reg c1) -> c1
8420 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8421 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8422
8423 // If the input is already sign extended, just drop the extension.
8424 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8425 return N0;
8426
8427 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8428 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8429 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8430 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8431 N0.getOperand(0), N1);
8432
8433 // fold (sext_in_reg (sext x)) -> (sext x)
8434 // fold (sext_in_reg (aext x)) -> (sext x)
8435 // if x is small enough.
8436 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8437 SDValue N00 = N0.getOperand(0);
8438 if (N00.getScalarValueSizeInBits() <= EVTBits &&
8439 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8440 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8441 }
8442
8443 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8444 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8445 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8446 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8447 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8448 if (!LegalOperations ||
8449 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8450 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8451 }
8452
8453 // fold (sext_in_reg (zext x)) -> (sext x)
8454 // iff we are extending the source sign bit.
8455 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8456 SDValue N00 = N0.getOperand(0);
8457 if (N00.getScalarValueSizeInBits() == EVTBits &&
8458 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8459 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8460 }
8461
8462 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8463 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8464 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8465
8466 // fold operands of sext_in_reg based on knowledge that the top bits are not
8467 // demanded.
8468 if (SimplifyDemandedBits(SDValue(N, 0)))
8469 return SDValue(N, 0);
8470
8471 // fold (sext_in_reg (load x)) -> (smaller sextload x)
8472 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8473 if (SDValue NarrowLoad = ReduceLoadWidth(N))
8474 return NarrowLoad;
8475
8476 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8477 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8478 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8479 if (N0.getOpcode() == ISD::SRL) {
8480 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8481 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8482 // We can turn this into an SRA iff the input to the SRL is already sign
8483 // extended enough.
8484 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8485 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8486 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8487 N0.getOperand(0), N0.getOperand(1));
8488 }
8489 }
8490
8491 // fold (sext_inreg (extload x)) -> (sextload x)
8492 // If sextload is not supported by target, we can only do the combine when
8493 // load has one use. Doing otherwise can block folding the extload with other
8494 // extends that the target does support.
8495 if (ISD::isEXTLoad(N0.getNode()) &&
8496 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8497 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8498 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8499 N0.hasOneUse()) ||
8500 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8501 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8502 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8503 LN0->getChain(),
8504 LN0->getBasePtr(), EVT,
8505 LN0->getMemOperand());
8506 CombineTo(N, ExtLoad);
8507 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8508 AddToWorklist(ExtLoad.getNode());
8509 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8510 }
8511 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8512 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8513 N0.hasOneUse() &&
8514 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8515 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8516 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8517 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8518 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8519 LN0->getChain(),
8520 LN0->getBasePtr(), EVT,
8521 LN0->getMemOperand());
8522 CombineTo(N, ExtLoad);
8523 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8524 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8525 }
8526
8527 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8528 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8529 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8530 N0.getOperand(1), false))
8531 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8532 BSwap, N1);
8533 }
8534
8535 return SDValue();
8536}
8537
8538SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8539 SDValue N0 = N->getOperand(0);
8540 EVT VT = N->getValueType(0);
8541
8542 if (N0.isUndef())
8543 return DAG.getUNDEF(VT);
8544
8545 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8546 LegalOperations))
8547 return SDValue(Res, 0);
8548
8549 return SDValue();
8550}
8551
8552SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8553 SDValue N0 = N->getOperand(0);
8554 EVT VT = N->getValueType(0);
8555
8556 if (N0.isUndef())
8557 return DAG.getUNDEF(VT);
8558
8559 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8560 LegalOperations))
8561 return SDValue(Res, 0);
8562
8563 return SDValue();
8564}
8565
8566SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8567 SDValue N0 = N->getOperand(0);
8568 EVT VT = N->getValueType(0);
8569 bool isLE = DAG.getDataLayout().isLittleEndian();
8570
8571 // noop truncate
8572 if (N0.getValueType() == N->getValueType(0))
8573 return N0;
8574
8575 // fold (truncate (truncate x)) -> (truncate x)
8576 if (N0.getOpcode() == ISD::TRUNCATE)
8577 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8578
8579 // fold (truncate c1) -> c1
8580 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8581 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8582 if (C.getNode() != N)
8583 return C;
8584 }
8585
8586 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8587 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8588 N0.getOpcode() == ISD::SIGN_EXTEND ||
8589 N0.getOpcode() == ISD::ANY_EXTEND) {
8590 // if the source is smaller than the dest, we still need an extend.
8591 if (N0.getOperand(0).getValueType().bitsLT(VT))
8592 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8593 // if the source is larger than the dest, than we just need the truncate.
8594 if (N0.getOperand(0).getValueType().bitsGT(VT))
8595 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8596 // if the source and dest are the same type, we can drop both the extend
8597 // and the truncate.
8598 return N0.getOperand(0);
8599 }
8600
8601 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8602 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8603 return SDValue();
8604
8605 // Fold extract-and-trunc into a narrow extract. For example:
8606 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8607 // i32 y = TRUNCATE(i64 x)
8608 // -- becomes --
8609 // v16i8 b = BITCAST (v2i64 val)
8610 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8611 //
8612 // Note: We only run this optimization after type legalization (which often
8613 // creates this pattern) and before operation legalization after which
8614 // we need to be more careful about the vector instructions that we generate.
8615 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8616 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8617 EVT VecTy = N0.getOperand(0).getValueType();
8618 EVT ExTy = N0.getValueType();
8619 EVT TrTy = N->getValueType(0);
8620
8621 unsigned NumElem = VecTy.getVectorNumElements();
8622 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8623
8624 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8625 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size")(static_cast <bool> (NVT.getSizeInBits() == VecTy.getSizeInBits
() && "Invalid Size") ? void (0) : __assert_fail ("NVT.getSizeInBits() == VecTy.getSizeInBits() && \"Invalid Size\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8625, __extension__ __PRETTY_FUNCTION__))
;
8626
8627 SDValue EltNo = N0->getOperand(1);
8628 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8629 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8630 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8631 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8632
8633 SDLoc DL(N);
8634 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8635 DAG.getBitcast(NVT, N0.getOperand(0)),
8636 DAG.getConstant(Index, DL, IndexTy));
8637 }
8638 }
8639
8640 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8641 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8642 EVT SrcVT = N0.getValueType();
8643 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8644 TLI.isTruncateFree(SrcVT, VT)) {
8645 SDLoc SL(N0);
8646 SDValue Cond = N0.getOperand(0);
8647 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8648 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8649 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8650 }
8651 }
8652
8653 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8654 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8655 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8656 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8657 SDValue Amt = N0.getOperand(1);
8658 KnownBits Known;
8659 DAG.computeKnownBits(Amt, Known);
8660 unsigned Size = VT.getScalarSizeInBits();
8661 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8662 SDLoc SL(N);
8663 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8664
8665 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8666 if (AmtVT != Amt.getValueType()) {
8667 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8668 AddToWorklist(Amt.getNode());
8669 }
8670 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8671 }
8672 }
8673
8674 // Fold a series of buildvector, bitcast, and truncate if possible.
8675 // For example fold
8676 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8677 // (2xi32 (buildvector x, y)).
8678 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8679 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8680 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8681 N0.getOperand(0).hasOneUse()) {
8682 SDValue BuildVect = N0.getOperand(0);
8683 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8684 EVT TruncVecEltTy = VT.getVectorElementType();
8685
8686 // Check that the element types match.
8687 if (BuildVectEltTy == TruncVecEltTy) {
8688 // Now we only need to compute the offset of the truncated elements.
8689 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8690 unsigned TruncVecNumElts = VT.getVectorNumElements();
8691 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8692
8693 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&(static_cast <bool> ((BuildVecNumElts % TruncVecNumElts
) == 0 && "Invalid number of elements") ? void (0) : __assert_fail
("(BuildVecNumElts % TruncVecNumElts) == 0 && \"Invalid number of elements\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8694, __extension__ __PRETTY_FUNCTION__))
8694 "Invalid number of elements")(static_cast <bool> ((BuildVecNumElts % TruncVecNumElts
) == 0 && "Invalid number of elements") ? void (0) : __assert_fail
("(BuildVecNumElts % TruncVecNumElts) == 0 && \"Invalid number of elements\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8694, __extension__ __PRETTY_FUNCTION__))
;
8695
8696 SmallVector<SDValue, 8> Opnds;
8697 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8698 Opnds.push_back(BuildVect.getOperand(i));
8699
8700 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8701 }
8702 }
8703
8704 // See if we can simplify the input to this truncate through knowledge that
8705 // only the low bits are being used.
8706 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8707 // Currently we only perform this optimization on scalars because vectors
8708 // may have different active low bits.
8709 if (!VT.isVector()) {
8710 APInt Mask =
8711 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8712 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8713 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8714 }
8715
8716 // fold (truncate (load x)) -> (smaller load x)
8717 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8718 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8719 if (SDValue Reduced = ReduceLoadWidth(N))
8720 return Reduced;
8721
8722 // Handle the case where the load remains an extending load even
8723 // after truncation.
8724 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8726 if (!LN0->isVolatile() &&
8727 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8728 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8729 VT, LN0->getChain(), LN0->getBasePtr(),
8730 LN0->getMemoryVT(),
8731 LN0->getMemOperand());
8732 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8733 return NewLoad;
8734 }
8735 }
8736 }
8737
8738 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8739 // where ... are all 'undef'.
8740 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8741 SmallVector<EVT, 8> VTs;
8742 SDValue V;
8743 unsigned Idx = 0;
8744 unsigned NumDefs = 0;
8745
8746 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8747 SDValue X = N0.getOperand(i);
8748 if (!X.isUndef()) {
8749 V = X;
8750 Idx = i;
8751 NumDefs++;
8752 }
8753 // Stop if more than one members are non-undef.
8754 if (NumDefs > 1)
8755 break;
8756 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8757 VT.getVectorElementType(),
8758 X.getValueType().getVectorNumElements()));
8759 }
8760
8761 if (NumDefs == 0)
8762 return DAG.getUNDEF(VT);
8763
8764 if (NumDefs == 1) {
8765 assert(V.getNode() && "The single defined operand is empty!")(static_cast <bool> (V.getNode() && "The single defined operand is empty!"
) ? void (0) : __assert_fail ("V.getNode() && \"The single defined operand is empty!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8765, __extension__ __PRETTY_FUNCTION__))
;
8766 SmallVector<SDValue, 8> Opnds;
8767 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8768 if (i != Idx) {
8769 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8770 continue;
8771 }
8772 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8773 AddToWorklist(NV.getNode());
8774 Opnds.push_back(NV);
8775 }
8776 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8777 }
8778 }
8779
8780 // Fold truncate of a bitcast of a vector to an extract of the low vector
8781 // element.
8782 //
8783 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8784 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8785 SDValue VecSrc = N0.getOperand(0);
8786 EVT SrcVT = VecSrc.getValueType();
8787 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8788 (!LegalOperations ||
8789 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8790 SDLoc SL(N);
8791
8792 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8793 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8794 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8795 VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8796 }
8797 }
8798
8799 // Simplify the operands using demanded-bits information.
8800 if (!VT.isVector() &&
8801 SimplifyDemandedBits(SDValue(N, 0)))
8802 return SDValue(N, 0);
8803
8804 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8805 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8806 // When the adde's carry is not used.
8807 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8808 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8809 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8810 SDLoc SL(N);
8811 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8812 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8813 auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8814 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8815 }
8816
8817 // fold (truncate (extract_subvector(ext x))) ->
8818 // (extract_subvector x)
8819 // TODO: This can be generalized to cover cases where the truncate and extract
8820 // do not fully cancel each other out.
8821 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8822 SDValue N00 = N0.getOperand(0);
8823 if (N00.getOpcode() == ISD::SIGN_EXTEND ||
8824 N00.getOpcode() == ISD::ZERO_EXTEND ||
8825 N00.getOpcode() == ISD::ANY_EXTEND) {
8826 if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
8827 VT.getVectorElementType())
8828 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
8829 N00.getOperand(0), N0.getOperand(1));
8830 }
8831 }
8832
8833 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8834 return NewVSel;
8835
8836 return SDValue();
8837}
8838
8839static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8840 SDValue Elt = N->getOperand(i);
8841 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8842 return Elt.getNode();
8843 return Elt.getOperand(Elt.getResNo()).getNode();
8844}
8845
8846/// build_pair (load, load) -> load
8847/// if load locations are consecutive.
8848SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8849 assert(N->getOpcode() == ISD::BUILD_PAIR)(static_cast <bool> (N->getOpcode() == ISD::BUILD_PAIR
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::BUILD_PAIR"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8849, __extension__ __PRETTY_FUNCTION__))
;
8850
8851 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8852 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8853
8854 // A BUILD_PAIR is always having the least significant part in elt 0 and the
8855 // most significant part in elt 1. So when combining into one large load, we
8856 // need to consider the endianness.
8857 if (DAG.getDataLayout().isBigEndian())
8858 std::swap(LD1, LD2);
8859
8860 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8861 LD1->getAddressSpace() != LD2->getAddressSpace())
8862 return SDValue();
8863 EVT LD1VT = LD1->getValueType(0);
8864 unsigned LD1Bytes = LD1VT.getStoreSize();
8865 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8866 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8867 unsigned Align = LD1->getAlignment();
8868 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8869 VT.getTypeForEVT(*DAG.getContext()));
8870
8871 if (NewAlign <= Align &&
8872 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8873 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8874 LD1->getPointerInfo(), Align);
8875 }
8876
8877 return SDValue();
8878}
8879
8880static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8881 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8882 // and Lo parts; on big-endian machines it doesn't.
8883 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8884}
8885
8886static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8887 const TargetLowering &TLI) {
8888 // If this is not a bitcast to an FP type or if the target doesn't have
8889 // IEEE754-compliant FP logic, we're done.
8890 EVT VT = N->getValueType(0);
8891 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8892 return SDValue();
8893
8894 // TODO: Use splat values for the constant-checking below and remove this
8895 // restriction.
8896 SDValue N0 = N->getOperand(0);
8897 EVT SourceVT = N0.getValueType();
8898 if (SourceVT.isVector())
8899 return SDValue();
8900
8901 unsigned FPOpcode;
8902 APInt SignMask;
8903 switch (N0.getOpcode()) {
8904 case ISD::AND:
8905 FPOpcode = ISD::FABS;
8906 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8907 break;
8908 case ISD::XOR:
8909 FPOpcode = ISD::FNEG;
8910 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8911 break;
8912 // TODO: ISD::OR --> ISD::FNABS?
8913 default:
8914 return SDValue();
8915 }
8916
8917 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8918 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8919 SDValue LogicOp0 = N0.getOperand(0);
8920 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8921 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8922 LogicOp0.getOpcode() == ISD::BITCAST &&
8923 LogicOp0->getOperand(0).getValueType() == VT)
8924 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8925
8926 return SDValue();
8927}
8928
8929SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8930 SDValue N0 = N->getOperand(0);
8931 EVT VT = N->getValueType(0);
8932
8933 if (N0.isUndef())
8934 return DAG.getUNDEF(VT);
8935
8936 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8937 // Only do this before legalize, since afterward the target may be depending
8938 // on the bitconvert.
8939 // First check to see if this is all constant.
8940 if (!LegalTypes &&
8941 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8942 VT.isVector()) {
8943 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8944
8945 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8946 assert(!DestEltVT.isVector() &&(static_cast <bool> (!DestEltVT.isVector() && "Element type of vector ValueType must not be vector!"
) ? void (0) : __assert_fail ("!DestEltVT.isVector() && \"Element type of vector ValueType must not be vector!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8947, __extension__ __PRETTY_FUNCTION__))
8947 "Element type of vector ValueType must not be vector!")(static_cast <bool> (!DestEltVT.isVector() && "Element type of vector ValueType must not be vector!"
) ? void (0) : __assert_fail ("!DestEltVT.isVector() && \"Element type of vector ValueType must not be vector!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 8947, __extension__ __PRETTY_FUNCTION__))
;
8948 if (isSimple)
8949 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8950 }
8951
8952 // If the input is a constant, let getNode fold it.
8953 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8954 // If we can't allow illegal operations, we need to check that this is just
8955 // a fp -> int or int -> conversion and that the resulting operation will
8956 // be legal.
8957 if (!LegalOperations ||
8958 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8959 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8960 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8961 TLI.isOperationLegal(ISD::Constant, VT)))
8962 return DAG.getBitcast(VT, N0);
8963 }
8964
8965 // (conv (conv x, t1), t2) -> (conv x, t2)
8966 if (N0.getOpcode() == ISD::BITCAST)
8967 return DAG.getBitcast(VT, N0.getOperand(0));
8968
8969 // fold (conv (load x)) -> (load (conv*)x)
8970 // If the resultant load doesn't need a higher alignment than the original!
8971 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8972 // Do not change the width of a volatile load.
8973 !cast<LoadSDNode>(N0)->isVolatile() &&
8974 // Do not remove the cast if the types differ in endian layout.
8975 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8976 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8977 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8978 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8979 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8980 unsigned OrigAlign = LN0->getAlignment();
8981
8982 bool Fast = false;
8983 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8984 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8985 Fast) {
8986 SDValue Load =
8987 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8988 LN0->getPointerInfo(), OrigAlign,
8989 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8990 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8991 return Load;
8992 }
8993 }
8994
8995 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8996 return V;
8997
8998 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8999 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
9000 //
9001 // For ppc_fp128:
9002 // fold (bitcast (fneg x)) ->
9003 // flipbit = signbit
9004 // (xor (bitcast x) (build_pair flipbit, flipbit))
9005 //
9006 // fold (bitcast (fabs x)) ->
9007 // flipbit = (and (extract_element (bitcast x), 0), signbit)
9008 // (xor (bitcast x) (build_pair flipbit, flipbit))
9009 // This often reduces constant pool loads.
9010 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
9011 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
9012 N0.getNode()->hasOneUse() && VT.isInteger() &&
9013 !VT.isVector() && !N0.getValueType().isVector()) {
9014 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
9015 AddToWorklist(NewConv.getNode());
9016
9017 SDLoc DL(N);
9018 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9019 assert(VT.getSizeInBits() == 128)(static_cast <bool> (VT.getSizeInBits() == 128) ? void (
0) : __assert_fail ("VT.getSizeInBits() == 128", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 9019, __extension__ __PRETTY_FUNCTION__))
;
9020 SDValue SignBit = DAG.getConstant(
9021 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
9022 SDValue FlipBit;
9023 if (N0.getOpcode() == ISD::FNEG) {
9024 FlipBit = SignBit;
9025 AddToWorklist(FlipBit.getNode());
9026 } else {
9027 assert(N0.getOpcode() == ISD::FABS)(static_cast <bool> (N0.getOpcode() == ISD::FABS) ? void
(0) : __assert_fail ("N0.getOpcode() == ISD::FABS", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 9027, __extension__ __PRETTY_FUNCTION__))
;
9028 SDValue Hi =
9029 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
9030 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9031 SDLoc(NewConv)));
9032 AddToWorklist(Hi.getNode());
9033 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
9034 AddToWorklist(FlipBit.getNode());
9035 }
9036 SDValue FlipBits =
9037 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9038 AddToWorklist(FlipBits.getNode());
9039 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
9040 }
9041 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9042 if (N0.getOpcode() == ISD::FNEG)
9043 return DAG.getNode(ISD::XOR, DL, VT,
9044 NewConv, DAG.getConstant(SignBit, DL, VT));
9045 assert(N0.getOpcode() == ISD::FABS)(static_cast <bool> (N0.getOpcode() == ISD::FABS) ? void
(0) : __assert_fail ("N0.getOpcode() == ISD::FABS", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 9045, __extension__ __PRETTY_FUNCTION__))
;
9046 return DAG.getNode(ISD::AND, DL, VT,
9047 NewConv, DAG.getConstant(~SignBit, DL, VT));
9048 }
9049
9050 // fold (bitconvert (fcopysign cst, x)) ->
9051 // (or (and (bitconvert x), sign), (and cst, (not sign)))
9052 // Note that we don't handle (copysign x, cst) because this can always be
9053 // folded to an fneg or fabs.
9054 //
9055 // For ppc_fp128:
9056 // fold (bitcast (fcopysign cst, x)) ->
9057 // flipbit = (and (extract_element
9058 // (xor (bitcast cst), (bitcast x)), 0),
9059 // signbit)
9060 // (xor (bitcast cst) (build_pair flipbit, flipbit))
9061 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
9062 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
9063 VT.isInteger() && !VT.isVector()) {
9064 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
9065 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
9066 if (isTypeLegal(IntXVT)) {
9067 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9068 AddToWorklist(X.getNode());
9069
9070 // If X has a different width than the result/lhs, sext it or truncate it.
9071 unsigned VTWidth = VT.getSizeInBits();
9072 if (OrigXWidth < VTWidth) {
9073 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9074 AddToWorklist(X.getNode());
9075 } else if (OrigXWidth > VTWidth) {
9076 // To get the sign bit in the right place, we have to shift it right
9077 // before truncating.
9078 SDLoc DL(X);
9079 X = DAG.getNode(ISD::SRL, DL,
9080 X.getValueType(), X,
9081 DAG.getConstant(OrigXWidth-VTWidth, DL,
9082 X.getValueType()));
9083 AddToWorklist(X.getNode());
9084 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9085 AddToWorklist(X.getNode());
9086 }
9087
9088 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9089 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9090 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9091 AddToWorklist(Cst.getNode());
9092 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9093 AddToWorklist(X.getNode());
9094 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9095 AddToWorklist(XorResult.getNode());
9096 SDValue XorResult64 = DAG.getNode(
9097 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9098 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9099 SDLoc(XorResult)));
9100 AddToWorklist(XorResult64.getNode());
9101 SDValue FlipBit =
9102 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9103 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9104 AddToWorklist(FlipBit.getNode());
9105 SDValue FlipBits =
9106 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9107 AddToWorklist(FlipBits.getNode());
9108 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9109 }
9110 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9111 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9112 X, DAG.getConstant(SignBit, SDLoc(X), VT));
9113 AddToWorklist(X.getNode());
9114
9115 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9116 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9117 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9118 AddToWorklist(Cst.getNode());
9119
9120 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9121 }
9122 }
9123
9124 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9125 if (N0.getOpcode() == ISD::BUILD_PAIR)
9126 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9127 return CombineLD;
9128
9129 // Remove double bitcasts from shuffles - this is often a legacy of
9130 // XformToShuffleWithZero being used to combine bitmaskings (of
9131 // float vectors bitcast to integer vectors) into shuffles.
9132 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9133 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9134 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9135 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9136 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9137 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9138
9139 // If operands are a bitcast, peek through if it casts the original VT.
9140 // If operands are a constant, just bitcast back to original VT.
9141 auto PeekThroughBitcast = [&](SDValue Op) {
9142 if (Op.getOpcode() == ISD::BITCAST &&
9143 Op.getOperand(0).getValueType() == VT)
9144 return SDValue(Op.getOperand(0));
9145 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9146 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9147 return DAG.getBitcast(VT, Op);
9148 return SDValue();
9149 };
9150
9151 // FIXME: If either input vector is bitcast, try to convert the shuffle to
9152 // the result type of this bitcast. This would eliminate at least one
9153 // bitcast. See the transform in InstCombine.
9154 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9155 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9156 if (!(SV0 && SV1))
9157 return SDValue();
9158
9159 int MaskScale =
9160 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9161 SmallVector<int, 8> NewMask;
9162 for (int M : SVN->getMask())
9163 for (int i = 0; i != MaskScale; ++i)
9164 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9165
9166 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9167 if (!LegalMask) {
9168 std::swap(SV0, SV1);
9169 ShuffleVectorSDNode::commuteMask(NewMask);
9170 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9171 }
9172
9173 if (LegalMask)
9174 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9175 }
9176
9177 return SDValue();
9178}
9179
9180SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9181 EVT VT = N->getValueType(0);
9182 return CombineConsecutiveLoads(N, VT);
9183}
9184
9185/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9186/// operands. DstEltVT indicates the destination element value type.
9187SDValue DAGCombiner::
9188ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9189 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9190
9191 // If this is already the right type, we're done.
9192 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9193
9194 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9195 unsigned DstBitSize = DstEltVT.getSizeInBits();
9196
9197 // If this is a conversion of N elements of one type to N elements of another
9198 // type, convert each element. This handles FP<->INT cases.
9199 if (SrcBitSize == DstBitSize) {
9200 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9201 BV->getValueType(0).getVectorNumElements());
9202
9203 // Due to the FP element handling below calling this routine recursively,
9204 // we can end up with a scalar-to-vector node here.
9205 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9206 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9207 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9208
9209 SmallVector<SDValue, 8> Ops;
9210 for (SDValue Op : BV->op_values()) {
9211 // If the vector element type is not legal, the BUILD_VECTOR operands
9212 // are promoted and implicitly truncated. Make that explicit here.
9213 if (Op.getValueType() != SrcEltVT)
9214 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9215 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9216 AddToWorklist(Ops.back().getNode());
9217 }
9218 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9219 }
9220
9221 // Otherwise, we're growing or shrinking the elements. To avoid having to
9222 // handle annoying details of growing/shrinking FP values, we convert them to
9223 // int first.
9224 if (SrcEltVT.isFloatingPoint()) {
9225 // Convert the input float vector to a int vector where the elements are the
9226 // same sizes.
9227 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9228 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9229 SrcEltVT = IntVT;
9230 }
9231
9232 // Now we know the input is an integer vector. If the output is a FP type,
9233 // convert to integer first, then to FP of the right size.
9234 if (DstEltVT.isFloatingPoint()) {
9235 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9236 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9237
9238 // Next, convert to FP elements of the same size.
9239 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9240 }
9241
9242 SDLoc DL(BV);
9243
9244 // Okay, we know the src/dst types are both integers of differing types.
9245 // Handling growing first.
9246 assert(SrcEltVT.isInteger() && DstEltVT.isInteger())(static_cast <bool> (SrcEltVT.isInteger() && DstEltVT
.isInteger()) ? void (0) : __assert_fail ("SrcEltVT.isInteger() && DstEltVT.isInteger()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 9246, __extension__ __PRETTY_FUNCTION__))
;
9247 if (SrcBitSize < DstBitSize) {
9248 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9249
9250 SmallVector<SDValue, 8> Ops;
9251 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9252 i += NumInputsPerOutput) {
9253 bool isLE = DAG.getDataLayout().isLittleEndian();
9254 APInt NewBits = APInt(DstBitSize, 0);
9255 bool EltIsUndef = true;
9256 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9257 // Shift the previously computed bits over.
9258 NewBits <<= SrcBitSize;
9259 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9260 if (Op.isUndef()) continue;
9261 EltIsUndef = false;
9262
9263 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9264 zextOrTrunc(SrcBitSize).zext(DstBitSize);
9265 }
9266
9267 if (EltIsUndef)
9268 Ops.push_back(DAG.getUNDEF(DstEltVT));
9269 else
9270 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9271 }
9272
9273 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9274 return DAG.getBuildVector(VT, DL, Ops);
9275 }
9276
9277 // Finally, this must be the case where we are shrinking elements: each input
9278 // turns into multiple outputs.
9279 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9280 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9281 NumOutputsPerInput*BV->getNumOperands());
9282 SmallVector<SDValue, 8> Ops;
9283
9284 for (const SDValue &Op : BV->op_values()) {
9285 if (Op.isUndef()) {
9286 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9287 continue;
9288 }
9289
9290 APInt OpVal = cast<ConstantSDNode>(Op)->
9291 getAPIntValue().zextOrTrunc(SrcBitSize);
9292
9293 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9294 APInt ThisVal = OpVal.trunc(DstBitSize);
9295 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9296 OpVal.lshrInPlace(DstBitSize);
9297 }
9298
9299 // For big endian targets, swap the order of the pieces of each element.
9300 if (DAG.getDataLayout().isBigEndian())
9301 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9302 }
9303
9304 return DAG.getBuildVector(VT, DL, Ops);
9305}
9306
9307static bool isContractable(SDNode *N) {
9308 SDNodeFlags F = N->getFlags();
9309 return F.hasAllowContract() || F.hasUnsafeAlgebra();
9310}
9311
9312/// Try to perform FMA combining on a given FADD node.
9313SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9314 SDValue N0 = N->getOperand(0);
9315 SDValue N1 = N->getOperand(1);
9316 EVT VT = N->getValueType(0);
9317 SDLoc SL(N);
9318
9319 const TargetOptions &Options = DAG.getTarget().Options;
9320
9321 // Floating-point multiply-add with intermediate rounding.
9322 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9323
9324 // Floating-point multiply-add without intermediate rounding.
9325 bool HasFMA =
9326 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9327 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9328
9329 // No valid opcode, do not combine.
9330 if (!HasFMAD && !HasFMA)
9331 return SDValue();
9332
9333 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9334 Options.UnsafeFPMath || HasFMAD);
9335 // If the addition is not contractable, do not combine.
9336 if (!AllowFusionGlobally && !isContractable(N))
9337 return SDValue();
9338
9339 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9340 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9341 return SDValue();
9342
9343 // Always prefer FMAD to FMA for precision.
9344 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9345 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9346
9347 // Is the node an FMUL and contractable either due to global flags or
9348 // SDNodeFlags.
9349 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9350 if (N.getOpcode() != ISD::FMUL)
9351 return false;
9352 return AllowFusionGlobally || isContractable(N.getNode());
9353 };
9354 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9355 // prefer to fold the multiply with fewer uses.
9356 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9357 if (N0.getNode()->use_size() > N1.getNode()->use_size())
9358 std::swap(N0, N1);
9359 }
9360
9361 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9362 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9363 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9364 N0.getOperand(0), N0.getOperand(1), N1);
9365 }
9366
9367 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9368 // Note: Commutes FADD operands.
9369 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9370 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9371 N1.getOperand(0), N1.getOperand(1), N0);
9372 }
9373
9374 // Look through FP_EXTEND nodes to do more combining.
9375
9376 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9377 if (N0.getOpcode() == ISD::FP_EXTEND) {
9378 SDValue N00 = N0.getOperand(0);
9379 if (isContractableFMUL(N00) &&
9380 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9381 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9382 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9383 N00.getOperand(0)),
9384 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9385 N00.getOperand(1)), N1);
9386 }
9387 }
9388
9389 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9390 // Note: Commutes FADD operands.
9391 if (N1.getOpcode() == ISD::FP_EXTEND) {
9392 SDValue N10 = N1.getOperand(0);
9393 if (isContractableFMUL(N10) &&
9394 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9395 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9396 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9397 N10.getOperand(0)),
9398 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9399 N10.getOperand(1)), N0);
9400 }
9401 }
9402
9403 // More folding opportunities when target permits.
9404 if (Aggressive) {
9405 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9406 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9407 // are currently only supported on binary nodes.
9408 if (Options.UnsafeFPMath &&
9409 N0.getOpcode() == PreferredFusedOpcode &&
9410 N0.getOperand(2).getOpcode() == ISD::FMUL &&
9411 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9412 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9413 N0.getOperand(0), N0.getOperand(1),
9414 DAG.getNode(PreferredFusedOpcode, SL, VT,
9415 N0.getOperand(2).getOperand(0),
9416 N0.getOperand(2).getOperand(1),
9417 N1));
9418 }
9419
9420 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9421 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9422 // are currently only supported on binary nodes.
9423 if (Options.UnsafeFPMath &&
9424 N1->getOpcode() == PreferredFusedOpcode &&
9425 N1.getOperand(2).getOpcode() == ISD::FMUL &&
9426 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9427 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9428 N1.getOperand(0), N1.getOperand(1),
9429 DAG.getNode(PreferredFusedOpcode, SL, VT,
9430 N1.getOperand(2).getOperand(0),
9431 N1.getOperand(2).getOperand(1),
9432 N0));
9433 }
9434
9435
9436 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9437 // -> (fma x, y, (fma (fpext u), (fpext v), z))
9438 auto FoldFAddFMAFPExtFMul = [&] (
9439 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9440 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9441 DAG.getNode(PreferredFusedOpcode, SL, VT,
9442 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9443 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9444 Z));
9445 };
9446 if (N0.getOpcode() == PreferredFusedOpcode) {
9447 SDValue N02 = N0.getOperand(2);
9448 if (N02.getOpcode() == ISD::FP_EXTEND) {
9449 SDValue N020 = N02.getOperand(0);
9450 if (isContractableFMUL(N020) &&
9451 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9452 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9453 N020.getOperand(0), N020.getOperand(1),
9454 N1);
9455 }
9456 }
9457 }
9458
9459 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9460 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9461 // FIXME: This turns two single-precision and one double-precision
9462 // operation into two double-precision operations, which might not be
9463 // interesting for all targets, especially GPUs.
9464 auto FoldFAddFPExtFMAFMul = [&] (
9465 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9466 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9467 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9468 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9469 DAG.getNode(PreferredFusedOpcode, SL, VT,
9470 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9471 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9472 Z));
9473 };
9474 if (N0.getOpcode() == ISD::FP_EXTEND) {
9475 SDValue N00 = N0.getOperand(0);
9476 if (N00.getOpcode() == PreferredFusedOpcode) {
9477 SDValue N002 = N00.getOperand(2);
9478 if (isContractableFMUL(N002) &&
9479 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9480 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9481 N002.getOperand(0), N002.getOperand(1),
9482 N1);
9483 }
9484 }
9485 }
9486
9487 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9488 // -> (fma y, z, (fma (fpext u), (fpext v), x))
9489 if (N1.getOpcode() == PreferredFusedOpcode) {
9490 SDValue N12 = N1.getOperand(2);
9491 if (N12.getOpcode() == ISD::FP_EXTEND) {
9492 SDValue N120 = N12.getOperand(0);
9493 if (isContractableFMUL(N120) &&
9494 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9495 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9496 N120.getOperand(0), N120.getOperand(1),
9497 N0);
9498 }
9499 }
9500 }
9501
9502 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9503 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9504 // FIXME: This turns two single-precision and one double-precision
9505 // operation into two double-precision operations, which might not be
9506 // interesting for all targets, especially GPUs.
9507 if (N1.getOpcode() == ISD::FP_EXTEND) {
9508 SDValue N10 = N1.getOperand(0);
9509 if (N10.getOpcode() == PreferredFusedOpcode) {
9510 SDValue N102 = N10.getOperand(2);
9511 if (isContractableFMUL(N102) &&
9512 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9513 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9514 N102.getOperand(0), N102.getOperand(1),
9515 N0);
9516 }
9517 }
9518 }
9519 }
9520
9521 return SDValue();
9522}
9523
9524/// Try to perform FMA combining on a given FSUB node.
9525SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9526 SDValue N0 = N->getOperand(0);
9527 SDValue N1 = N->getOperand(1);
9528 EVT VT = N->getValueType(0);
9529 SDLoc SL(N);
9530
9531 const TargetOptions &Options = DAG.getTarget().Options;
9532 // Floating-point multiply-add with intermediate rounding.
9533 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9534
9535 // Floating-point multiply-add without intermediate rounding.
9536 bool HasFMA =
9537 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9538 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9539
9540 // No valid opcode, do not combine.
9541 if (!HasFMAD && !HasFMA)
9542 return SDValue();
9543
9544 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9545 Options.UnsafeFPMath || HasFMAD);
9546 // If the subtraction is not contractable, do not combine.
9547 if (!AllowFusionGlobally && !isContractable(N))
9548 return SDValue();
9549
9550 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9551 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9552 return SDValue();
9553
9554 // Always prefer FMAD to FMA for precision.
9555 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9556 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9557
9558 // Is the node an FMUL and contractable either due to global flags or
9559 // SDNodeFlags.
9560 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9561 if (N.getOpcode() != ISD::FMUL)
9562 return false;
9563 return AllowFusionGlobally || isContractable(N.getNode());
9564 };
9565
9566 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9567 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9568 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9569 N0.getOperand(0), N0.getOperand(1),
9570 DAG.getNode(ISD::FNEG, SL, VT, N1));
9571 }
9572
9573 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9574 // Note: Commutes FSUB operands.
9575 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9576 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9577 DAG.getNode(ISD::FNEG, SL, VT,
9578 N1.getOperand(0)),
9579 N1.getOperand(1), N0);
9580
9581 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9582 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9583 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9584 SDValue N00 = N0.getOperand(0).getOperand(0);
9585 SDValue N01 = N0.getOperand(0).getOperand(1);
9586 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9587 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9588 DAG.getNode(ISD::FNEG, SL, VT, N1));
9589 }
9590
9591 // Look through FP_EXTEND nodes to do more combining.
9592
9593 // fold (fsub (fpext (fmul x, y)), z)
9594 // -> (fma (fpext x), (fpext y), (fneg z))
9595 if (N0.getOpcode() == ISD::FP_EXTEND) {
9596 SDValue N00 = N0.getOperand(0);
9597 if (isContractableFMUL(N00) &&
9598 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9599 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9600 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9601 N00.getOperand(0)),
9602 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9603 N00.getOperand(1)),
9604 DAG.getNode(ISD::FNEG, SL, VT, N1));
9605 }
9606 }
9607
9608 // fold (fsub x, (fpext (fmul y, z)))
9609 // -> (fma (fneg (fpext y)), (fpext z), x)
9610 // Note: Commutes FSUB operands.
9611 if (N1.getOpcode() == ISD::FP_EXTEND) {
9612 SDValue N10 = N1.getOperand(0);
9613 if (isContractableFMUL(N10) &&
9614 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9615 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9616 DAG.getNode(ISD::FNEG, SL, VT,
9617 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9618 N10.getOperand(0))),
9619 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9620 N10.getOperand(1)),
9621 N0);
9622 }
9623 }
9624
9625 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9626 // -> (fneg (fma (fpext x), (fpext y), z))
9627 // Note: This could be removed with appropriate canonicalization of the
9628 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9629 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9630 // from implementing the canonicalization in visitFSUB.
9631 if (N0.getOpcode() == ISD::FP_EXTEND) {
9632 SDValue N00 = N0.getOperand(0);
9633 if (N00.getOpcode() == ISD::FNEG) {
9634 SDValue N000 = N00.getOperand(0);
9635 if (isContractableFMUL(N000) &&
9636 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9637 return DAG.getNode(ISD::FNEG, SL, VT,
9638 DAG.getNode(PreferredFusedOpcode, SL, VT,
9639 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9640 N000.getOperand(0)),
9641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9642 N000.getOperand(1)),
9643 N1));
9644 }
9645 }
9646 }
9647
9648 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9649 // -> (fneg (fma (fpext x)), (fpext y), z)
9650 // Note: This could be removed with appropriate canonicalization of the
9651 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9652 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9653 // from implementing the canonicalization in visitFSUB.
9654 if (N0.getOpcode() == ISD::FNEG) {
9655 SDValue N00 = N0.getOperand(0);
9656 if (N00.getOpcode() == ISD::FP_EXTEND) {
9657 SDValue N000 = N00.getOperand(0);
9658 if (isContractableFMUL(N000) &&
9659 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9660 return DAG.getNode(ISD::FNEG, SL, VT,
9661 DAG.getNode(PreferredFusedOpcode, SL, VT,
9662 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9663 N000.getOperand(0)),
9664 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9665 N000.getOperand(1)),
9666 N1));
9667 }
9668 }
9669 }
9670
9671 // More folding opportunities when target permits.
9672 if (Aggressive) {
9673 // fold (fsub (fma x, y, (fmul u, v)), z)
9674 // -> (fma x, y (fma u, v, (fneg z)))
9675 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9676 // are currently only supported on binary nodes.
9677 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9678 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9679 N0.getOperand(2)->hasOneUse()) {
9680 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9681 N0.getOperand(0), N0.getOperand(1),
9682 DAG.getNode(PreferredFusedOpcode, SL, VT,
9683 N0.getOperand(2).getOperand(0),
9684 N0.getOperand(2).getOperand(1),
9685 DAG.getNode(ISD::FNEG, SL, VT,
9686 N1)));
9687 }
9688
9689 // fold (fsub x, (fma y, z, (fmul u, v)))
9690 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9691 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9692 // are currently only supported on binary nodes.
9693 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9694 isContractableFMUL(N1.getOperand(2))) {
9695 SDValue N20 = N1.getOperand(2).getOperand(0);
9696 SDValue N21 = N1.getOperand(2).getOperand(1);
9697 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9698 DAG.getNode(ISD::FNEG, SL, VT,
9699 N1.getOperand(0)),
9700 N1.getOperand(1),
9701 DAG.getNode(PreferredFusedOpcode, SL, VT,
9702 DAG.getNode(ISD::FNEG, SL, VT, N20),
9703
9704 N21, N0));
9705 }
9706
9707
9708 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9709 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9710 if (N0.getOpcode() == PreferredFusedOpcode) {
9711 SDValue N02 = N0.getOperand(2);
9712 if (N02.getOpcode() == ISD::FP_EXTEND) {
9713 SDValue N020 = N02.getOperand(0);
9714 if (isContractableFMUL(N020) &&
9715 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9716 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9717 N0.getOperand(0), N0.getOperand(1),
9718 DAG.getNode(PreferredFusedOpcode, SL, VT,
9719 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9720 N020.getOperand(0)),
9721 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9722 N020.getOperand(1)),
9723 DAG.getNode(ISD::FNEG, SL, VT,
9724 N1)));
9725 }
9726 }
9727 }
9728
9729 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9730 // -> (fma (fpext x), (fpext y),
9731 // (fma (fpext u), (fpext v), (fneg z)))
9732 // FIXME: This turns two single-precision and one double-precision
9733 // operation into two double-precision operations, which might not be
9734 // interesting for all targets, especially GPUs.
9735 if (N0.getOpcode() == ISD::FP_EXTEND) {
9736 SDValue N00 = N0.getOperand(0);
9737 if (N00.getOpcode() == PreferredFusedOpcode) {
9738 SDValue N002 = N00.getOperand(2);
9739 if (isContractableFMUL(N002) &&
9740 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9741 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9742 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9743 N00.getOperand(0)),
9744 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9745 N00.getOperand(1)),
9746 DAG.getNode(PreferredFusedOpcode, SL, VT,
9747 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9748 N002.getOperand(0)),
9749 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9750 N002.getOperand(1)),
9751 DAG.getNode(ISD::FNEG, SL, VT,
9752 N1)));
9753 }
9754 }
9755 }
9756
9757 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9758 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9759 if (N1.getOpcode() == PreferredFusedOpcode &&
9760 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9761 SDValue N120 = N1.getOperand(2).getOperand(0);
9762 if (isContractableFMUL(N120) &&
9763 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9764 SDValue N1200 = N120.getOperand(0);
9765 SDValue N1201 = N120.getOperand(1);
9766 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9767 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9768 N1.getOperand(1),
9769 DAG.getNode(PreferredFusedOpcode, SL, VT,
9770 DAG.getNode(ISD::FNEG, SL, VT,
9771 DAG.getNode(ISD::FP_EXTEND, SL,
9772 VT, N1200)),
9773 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9774 N1201),
9775 N0));
9776 }
9777 }
9778
9779 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9780 // -> (fma (fneg (fpext y)), (fpext z),
9781 // (fma (fneg (fpext u)), (fpext v), x))
9782 // FIXME: This turns two single-precision and one double-precision
9783 // operation into two double-precision operations, which might not be
9784 // interesting for all targets, especially GPUs.
9785 if (N1.getOpcode() == ISD::FP_EXTEND &&
9786 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9787 SDValue CvtSrc = N1.getOperand(0);
9788 SDValue N100 = CvtSrc.getOperand(0);
9789 SDValue N101 = CvtSrc.getOperand(1);
9790 SDValue N102 = CvtSrc.getOperand(2);
9791 if (isContractableFMUL(N102) &&
9792 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
9793 SDValue N1020 = N102.getOperand(0);
9794 SDValue N1021 = N102.getOperand(1);
9795 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9796 DAG.getNode(ISD::FNEG, SL, VT,
9797 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9798 N100)),
9799 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9800 DAG.getNode(PreferredFusedOpcode, SL, VT,
9801 DAG.getNode(ISD::FNEG, SL, VT,
9802 DAG.getNode(ISD::FP_EXTEND, SL,
9803 VT, N1020)),
9804 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9805 N1021),
9806 N0));
9807 }
9808 }
9809 }
9810
9811 return SDValue();
9812}
9813
9814/// Try to perform FMA combining on a given FMUL node based on the distributive
9815/// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9816/// subtraction instead of addition).
9817SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9818 SDValue N0 = N->getOperand(0);
9819 SDValue N1 = N->getOperand(1);
9820 EVT VT = N->getValueType(0);
9821 SDLoc SL(N);
9822
9823 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation")(static_cast <bool> (N->getOpcode() == ISD::FMUL &&
"Expected FMUL Operation") ? void (0) : __assert_fail ("N->getOpcode() == ISD::FMUL && \"Expected FMUL Operation\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 9823, __extension__ __PRETTY_FUNCTION__))
;
9824
9825 const TargetOptions &Options = DAG.getTarget().Options;
9826
9827 // The transforms below are incorrect when x == 0 and y == inf, because the
9828 // intermediate multiplication produces a nan.
9829 if (!Options.NoInfsFPMath)
9830 return SDValue();
9831
9832 // Floating-point multiply-add without intermediate rounding.
9833 bool HasFMA =
9834 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9835 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9836 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9837
9838 // Floating-point multiply-add with intermediate rounding. This can result
9839 // in a less precise result due to the changed rounding order.
9840 bool HasFMAD = Options.UnsafeFPMath &&
9841 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9842
9843 // No valid opcode, do not combine.
9844 if (!HasFMAD && !HasFMA)
9845 return SDValue();
9846
9847 // Always prefer FMAD to FMA for precision.
9848 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9849 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9850
9851 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9852 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9853 auto FuseFADD = [&](SDValue X, SDValue Y) {
9854 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9855 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9856 if (XC1 && XC1->isExactlyValue(+1.0))
9857 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9858 if (XC1 && XC1->isExactlyValue(-1.0))
9859 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9860 DAG.getNode(ISD::FNEG, SL, VT, Y));
9861 }
9862 return SDValue();
9863 };
9864
9865 if (SDValue FMA = FuseFADD(N0, N1))
9866 return FMA;
9867 if (SDValue FMA = FuseFADD(N1, N0))
9868 return FMA;
9869
9870 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9871 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9872 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9873 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9874 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9875 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9876 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9877 if (XC0 && XC0->isExactlyValue(+1.0))
9878 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9879 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9880 Y);
9881 if (XC0 && XC0->isExactlyValue(-1.0))
9882 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9883 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9884 DAG.getNode(ISD::FNEG, SL, VT, Y));
9885
9886 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9887 if (XC1 && XC1->isExactlyValue(+1.0))
9888 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9889 DAG.getNode(ISD::FNEG, SL, VT, Y));
9890 if (XC1 && XC1->isExactlyValue(-1.0))
9891 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9892 }
9893 return SDValue();
9894 };
9895
9896 if (SDValue FMA = FuseFSUB(N0, N1))
9897 return FMA;
9898 if (SDValue FMA = FuseFSUB(N1, N0))
9899 return FMA;
9900
9901 return SDValue();
9902}
9903
9904static bool isFMulNegTwo(SDValue &N) {
9905 if (N.getOpcode() != ISD::FMUL)
9906 return false;
9907 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9908 return CFP->isExactlyValue(-2.0);
9909 return false;
9910}
9911
9912SDValue DAGCombiner::visitFADD(SDNode *N) {
9913 SDValue N0 = N->getOperand(0);
9914 SDValue N1 = N->getOperand(1);
9915 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9916 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9917 EVT VT = N->getValueType(0);
9918 SDLoc DL(N);
9919 const TargetOptions &Options = DAG.getTarget().Options;
9920 const SDNodeFlags Flags = N->getFlags();
9921
9922 // fold vector ops
9923 if (VT.isVector())
9924 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9925 return FoldedVOp;
9926
9927 // fold (fadd c1, c2) -> c1 + c2
9928 if (N0CFP && N1CFP)
9929 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9930
9931 // canonicalize constant to RHS
9932 if (N0CFP && !N1CFP)
9933 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9934
9935 if (SDValue NewSel = foldBinOpIntoSelect(N))
9936 return NewSel;
9937
9938 // fold (fadd A, (fneg B)) -> (fsub A, B)
9939 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9940 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9941 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9942 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9943
9944 // fold (fadd (fneg A), B) -> (fsub B, A)
9945 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9946 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9947 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9948 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9949
9950 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9951 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9952 if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9953 (isFMulNegTwo(N1) && N1.hasOneUse())) {
9954 bool N1IsFMul = isFMulNegTwo(N1);
9955 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9956 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9957 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9958 }
9959
9960 // FIXME: Auto-upgrade the target/function-level option.
9961 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9962 // fold (fadd A, 0) -> A
9963 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9964 if (N1C->isZero())
9965 return N0;
9966 }
9967
9968 // If 'unsafe math' is enabled, fold lots of things.
9969 if (Options.UnsafeFPMath) {
9970 // No FP constant should be created after legalization as Instruction
9971 // Selection pass has a hard time dealing with FP constants.
9972 bool AllowNewConst = (Level < AfterLegalizeDAG);
9973
9974 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9975 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9976 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9977 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9978 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9979 Flags),
9980 Flags);
9981
9982 // If allowed, fold (fadd (fneg x), x) -> 0.0
9983 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9984 return DAG.getConstantFP(0.0, DL, VT);
9985
9986 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9987 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9988 return DAG.getConstantFP(0.0, DL, VT);
9989
9990 // We can fold chains of FADD's of the same value into multiplications.
9991 // This transform is not safe in general because we are reducing the number
9992 // of rounding steps.
9993 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9994 if (N0.getOpcode() == ISD::FMUL) {
9995 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9996 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9997
9998 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9999 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
10000 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10001 DAG.getConstantFP(1.0, DL, VT), Flags);
10002 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
10003 }
10004
10005 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
10006 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
10007 N1.getOperand(0) == N1.getOperand(1) &&
10008 N0.getOperand(0) == N1.getOperand(0)) {
10009 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10010 DAG.getConstantFP(2.0, DL, VT), Flags);
10011 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
10012 }
10013 }
10014
10015 if (N1.getOpcode() == ISD::FMUL) {
10016 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10017 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
10018
10019 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
10020 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
10021 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10022 DAG.getConstantFP(1.0, DL, VT), Flags);
10023 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
10024 }
10025
10026 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
10027 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
10028 N0.getOperand(0) == N0.getOperand(1) &&
10029 N1.getOperand(0) == N0.getOperand(0)) {
10030 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10031 DAG.getConstantFP(2.0, DL, VT), Flags);
10032 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
10033 }
10034 }
10035
10036 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
10037 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10038 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
10039 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
10040 (N0.getOperand(0) == N1)) {
10041 return DAG.getNode(ISD::FMUL, DL, VT,
10042 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
10043 }
10044 }
10045
10046 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
10047 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10048 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
10049 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
10050 N1.getOperand(0) == N0) {
10051 return DAG.getNode(ISD::FMUL, DL, VT,
10052 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
10053 }
10054 }
10055
10056 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
10057 if (AllowNewConst &&
10058 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
10059 N0.getOperand(0) == N0.getOperand(1) &&
10060 N1.getOperand(0) == N1.getOperand(1) &&
10061 N0.getOperand(0) == N1.getOperand(0)) {
10062 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
10063 DAG.getConstantFP(4.0, DL, VT), Flags);
10064 }
10065 }
10066 } // enable-unsafe-fp-math
10067
10068 // FADD -> FMA combines:
10069 if (SDValue Fused = visitFADDForFMACombine(N)) {
10070 AddToWorklist(Fused.getNode());
10071 return Fused;
10072 }
10073 return SDValue();
10074}
10075
10076SDValue DAGCombiner::visitFSUB(SDNode *N) {
10077 SDValue N0 = N->getOperand(0);
10078 SDValue N1 = N->getOperand(1);
10079 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10080 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10081 EVT VT = N->getValueType(0);
10082 SDLoc DL(N);
10083 const TargetOptions &Options = DAG.getTarget().Options;
10084 const SDNodeFlags Flags = N->getFlags();
10085
10086 // fold vector ops
10087 if (VT.isVector())
10088 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10089 return FoldedVOp;
10090
10091 // fold (fsub c1, c2) -> c1-c2
10092 if (N0CFP && N1CFP)
10093 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10094
10095 if (SDValue NewSel = foldBinOpIntoSelect(N))
10096 return NewSel;
10097
10098 // fold (fsub A, (fneg B)) -> (fadd A, B)
10099 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10100 return DAG.getNode(ISD::FADD, DL, VT, N0,
10101 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10102
10103 // FIXME: Auto-upgrade the target/function-level option.
10104 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
10105 // (fsub 0, B) -> -B
10106 if (N0CFP && N0CFP->isZero()) {
10107 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10108 return GetNegatedExpression(N1, DAG, LegalOperations);
10109 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10110 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10111 }
10112 }
10113
10114 // If 'unsafe math' is enabled, fold lots of things.
10115 if (Options.UnsafeFPMath) {
10116 // (fsub A, 0) -> A
10117 if (N1CFP && N1CFP->isZero())
10118 return N0;
10119
10120 // (fsub x, x) -> 0.0
10121 if (N0 == N1)
10122 return DAG.getConstantFP(0.0f, DL, VT);
10123
10124 // (fsub x, (fadd x, y)) -> (fneg y)
10125 // (fsub x, (fadd y, x)) -> (fneg y)
10126 if (N1.getOpcode() == ISD::FADD) {
10127 SDValue N10 = N1->getOperand(0);
10128 SDValue N11 = N1->getOperand(1);
10129
10130 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10131 return GetNegatedExpression(N11, DAG, LegalOperations);
10132
10133 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10134 return GetNegatedExpression(N10, DAG, LegalOperations);
10135 }
10136 }
10137
10138 // FSUB -> FMA combines:
10139 if (SDValue Fused = visitFSUBForFMACombine(N)) {
10140 AddToWorklist(Fused.getNode());
10141 return Fused;
10142 }
10143
10144 return SDValue();
10145}
10146
10147SDValue DAGCombiner::visitFMUL(SDNode *N) {
10148 SDValue N0 = N->getOperand(0);
10149 SDValue N1 = N->getOperand(1);
10150 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10151 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10152 EVT VT = N->getValueType(0);
10153 SDLoc DL(N);
10154 const TargetOptions &Options = DAG.getTarget().Options;
10155 const SDNodeFlags Flags = N->getFlags();
10156
10157 // fold vector ops
10158 if (VT.isVector()) {
10159 // This just handles C1 * C2 for vectors. Other vector folds are below.
10160 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10161 return FoldedVOp;
10162 }
10163
10164 // fold (fmul c1, c2) -> c1*c2
10165 if (N0CFP && N1CFP)
10166 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10167
10168 // canonicalize constant to RHS
10169 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10170 !isConstantFPBuildVectorOrConstantFP(N1))
10171 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10172
10173 // fold (fmul A, 1.0) -> A
10174 if (N1CFP && N1CFP->isExactlyValue(1.0))
10175 return N0;
10176
10177 if (SDValue NewSel = foldBinOpIntoSelect(N))
10178 return NewSel;
10179
10180 if (Options.UnsafeFPMath) {
10181 // fold (fmul A, 0) -> 0
10182 if (N1CFP && N1CFP->isZero())
10183 return N1;
10184
10185 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10186 if (N0.getOpcode() == ISD::FMUL) {
10187 // Fold scalars or any vector constants (not just splats).
10188 // This fold is done in general by InstCombine, but extra fmul insts
10189 // may have been generated during lowering.
10190 SDValue N00 = N0.getOperand(0);
10191 SDValue N01 = N0.getOperand(1);
10192 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10193 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10194 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10195
10196 // Check 1: Make sure that the first operand of the inner multiply is NOT
10197 // a constant. Otherwise, we may induce infinite looping.
10198 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10199 // Check 2: Make sure that the second operand of the inner multiply and
10200 // the second operand of the outer multiply are constants.
10201 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10202 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10203 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10204 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10205 }
10206 }
10207 }
10208
10209 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10210 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10211 // during an early run of DAGCombiner can prevent folding with fmuls
10212 // inserted during lowering.
10213 if (N0.getOpcode() == ISD::FADD &&
10214 (N0.getOperand(0) == N0.getOperand(1)) &&
10215 N0.hasOneUse()) {
10216 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10217 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10218 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10219 }
10220 }
10221
10222 // fold (fmul X, 2.0) -> (fadd X, X)
10223 if (N1CFP && N1CFP->isExactlyValue(+2.0))
10224 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10225
10226 // fold (fmul X, -1.0) -> (fneg X)
10227 if (N1CFP && N1CFP->isExactlyValue(-1.0))
10228 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10229 return DAG.getNode(ISD::FNEG, DL, VT, N0);
10230
10231 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10232 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10233 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10234 // Both can be negated for free, check to see if at least one is cheaper
10235 // negated.
10236 if (LHSNeg == 2 || RHSNeg == 2)
10237 return DAG.getNode(ISD::FMUL, DL, VT,
10238 GetNegatedExpression(N0, DAG, LegalOperations),
10239 GetNegatedExpression(N1, DAG, LegalOperations),
10240 Flags);
10241 }
10242 }
10243
10244 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10245 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10246 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10247 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10248 TLI.isOperationLegal(ISD::FABS, VT)) {
10249 SDValue Select = N0, X = N1;
10250 if (Select.getOpcode() != ISD::SELECT)
10251 std::swap(Select, X);
10252
10253 SDValue Cond = Select.getOperand(0);
10254 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10255 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10256
10257 if (TrueOpnd && FalseOpnd &&
10258 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10259 isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10260 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10261 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10262 switch (CC) {
10263 default: break;
10264 case ISD::SETOLT:
10265 case ISD::SETULT:
10266 case ISD::SETOLE:
10267 case ISD::SETULE:
10268 case ISD::SETLT:
10269 case ISD::SETLE:
10270 std::swap(TrueOpnd, FalseOpnd);
10271 LLVM_FALLTHROUGH[[clang::fallthrough]];
10272 case ISD::SETOGT:
10273 case ISD::SETUGT:
10274 case ISD::SETOGE:
10275 case ISD::SETUGE:
10276 case ISD::SETGT:
10277 case ISD::SETGE:
10278 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10279 TLI.isOperationLegal(ISD::FNEG, VT))
10280 return DAG.getNode(ISD::FNEG, DL, VT,
10281 DAG.getNode(ISD::FABS, DL, VT, X));
10282 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10283 return DAG.getNode(ISD::FABS, DL, VT, X);
10284
10285 break;
10286 }
10287 }
10288 }
10289
10290 // FMUL -> FMA combines:
10291 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10292 AddToWorklist(Fused.getNode());
10293 return Fused;
10294 }
10295
10296 return SDValue();
10297}
10298
10299SDValue DAGCombiner::visitFMA(SDNode *N) {
10300 SDValue N0 = N->getOperand(0);
10301 SDValue N1 = N->getOperand(1);
10302 SDValue N2 = N->getOperand(2);
10303 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10304 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10305 EVT VT = N->getValueType(0);
10306 SDLoc DL(N);
10307 const TargetOptions &Options = DAG.getTarget().Options;
10308
10309 // Constant fold FMA.
10310 if (isa<ConstantFPSDNode>(N0) &&
10311 isa<ConstantFPSDNode>(N1) &&
10312 isa<ConstantFPSDNode>(N2)) {
10313 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10314 }
10315
10316 if (Options.UnsafeFPMath) {
10317 if (N0CFP && N0CFP->isZero())
10318 return N2;
10319 if (N1CFP && N1CFP->isZero())
10320 return N2;
10321 }
10322 // TODO: The FMA node should have flags that propagate to these nodes.
10323 if (N0CFP && N0CFP->isExactlyValue(1.0))
10324 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10325 if (N1CFP && N1CFP->isExactlyValue(1.0))
10326 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10327
10328 // Canonicalize (fma c, x, y) -> (fma x, c, y)
10329 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10330 !isConstantFPBuildVectorOrConstantFP(N1))
10331 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10332
10333 // TODO: FMA nodes should have flags that propagate to the created nodes.
10334 // For now, create a Flags object for use with all unsafe math transforms.
10335 SDNodeFlags Flags;
10336 Flags.setUnsafeAlgebra(true);
10337
10338 if (Options.UnsafeFPMath) {
10339 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10340 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10341 isConstantFPBuildVectorOrConstantFP(N1) &&
10342 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10343 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10344 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10345 Flags), Flags);
10346 }
10347
10348 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10349 if (N0.getOpcode() == ISD::FMUL &&
10350 isConstantFPBuildVectorOrConstantFP(N1) &&
10351 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10352 return DAG.getNode(ISD::FMA, DL, VT,
10353 N0.getOperand(0),
10354 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10355 Flags),
10356 N2);
10357 }
10358 }
10359
10360 // (fma x, 1, y) -> (fadd x, y)
10361 // (fma x, -1, y) -> (fadd (fneg x), y)
10362 if (N1CFP) {
10363 if (N1CFP->isExactlyValue(1.0))
10364 // TODO: The FMA node should have flags that propagate to this node.
10365 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10366
10367 if (N1CFP->isExactlyValue(-1.0) &&
10368 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10369 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10370 AddToWorklist(RHSNeg.getNode());
10371 // TODO: The FMA node should have flags that propagate to this node.
10372 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10373 }
10374
10375 // fma (fneg x), K, y -> fma x -K, y
10376 if (N0.getOpcode() == ISD::FNEG &&
10377 (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10378 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10379 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10380 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10381 }
10382 }
10383
10384 if (Options.UnsafeFPMath) {
10385 // (fma x, c, x) -> (fmul x, (c+1))
10386 if (N1CFP && N0 == N2) {
10387 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10388 DAG.getNode(ISD::FADD, DL, VT, N1,
10389 DAG.getConstantFP(1.0, DL, VT), Flags),
10390 Flags);
10391 }
10392
10393 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10394 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10395 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10396 DAG.getNode(ISD::FADD, DL, VT, N1,
10397 DAG.getConstantFP(-1.0, DL, VT), Flags),
10398 Flags);
10399 }
10400 }
10401
10402 return SDValue();
10403}
10404
10405// Combine multiple FDIVs with the same divisor into multiple FMULs by the
10406// reciprocal.
10407// E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10408// Notice that this is not always beneficial. One reason is different targets
10409// may have different costs for FDIV and FMUL, so sometimes the cost of two
10410// FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10411// is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10412SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10413 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10414 const SDNodeFlags Flags = N->getFlags();
10415 if (!UnsafeMath && !Flags.hasAllowReciprocal())
10416 return SDValue();
10417
10418 // Skip if current node is a reciprocal.
10419 SDValue N0 = N->getOperand(0);
10420 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10421 if (N0CFP && N0CFP->isExactlyValue(1.0))
10422 return SDValue();
10423
10424 // Exit early if the target does not want this transform or if there can't
10425 // possibly be enough uses of the divisor to make the transform worthwhile.
10426 SDValue N1 = N->getOperand(1);
10427 unsigned MinUses = TLI.combineRepeatedFPDivisors();
10428 if (!MinUses || N1->use_size() < MinUses)
10429 return SDValue();
10430
10431 // Find all FDIV users of the same divisor.
10432 // Use a set because duplicates may be present in the user list.
10433 SetVector<SDNode *> Users;
10434 for (auto *U : N1->uses()) {
10435 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10436 // This division is eligible for optimization only if global unsafe math
10437 // is enabled or if this division allows reciprocal formation.
10438 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10439 Users.insert(U);
10440 }
10441 }
10442
10443 // Now that we have the actual number of divisor uses, make sure it meets
10444 // the minimum threshold specified by the target.
10445 if (Users.size() < MinUses)
10446 return SDValue();
10447
10448 EVT VT = N->getValueType(0);
10449 SDLoc DL(N);
10450 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10451 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10452
10453 // Dividend / Divisor -> Dividend * Reciprocal
10454 for (auto *U : Users) {
10455 SDValue Dividend = U->getOperand(0);
10456 if (Dividend != FPOne) {
10457 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10458 Reciprocal, Flags);
10459 CombineTo(U, NewNode);
10460 } else if (U != Reciprocal.getNode()) {
10461 // In the absence of fast-math-flags, this user node is always the
10462 // same node as Reciprocal, but with FMF they may be different nodes.
10463 CombineTo(U, Reciprocal);
10464 }
10465 }
10466 return SDValue(N, 0); // N was replaced.
10467}
10468
10469SDValue DAGCombiner::visitFDIV(SDNode *N) {
10470 SDValue N0 = N->getOperand(0);
10471 SDValue N1 = N->getOperand(1);
10472 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10473 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10474 EVT VT = N->getValueType(0);
10475 SDLoc DL(N);
10476 const TargetOptions &Options = DAG.getTarget().Options;
10477 SDNodeFlags Flags = N->getFlags();
10478
10479 // fold vector ops
10480 if (VT.isVector())
10481 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10482 return FoldedVOp;
10483
10484 // fold (fdiv c1, c2) -> c1/c2
10485 if (N0CFP && N1CFP)
10486 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10487
10488 if (SDValue NewSel = foldBinOpIntoSelect(N))
10489 return NewSel;
10490
10491 if (Options.UnsafeFPMath) {
10492 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10493 if (N1CFP) {
10494 // Compute the reciprocal 1.0 / c2.
10495 const APFloat &N1APF = N1CFP->getValueAPF();
10496 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10497 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10498 // Only do the transform if the reciprocal is a legal fp immediate that
10499 // isn't too nasty (eg NaN, denormal, ...).
10500 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10501 (!LegalOperations ||
10502 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10503 // backend)... we should handle this gracefully after Legalize.
10504 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10505 TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10506 TLI.isFPImmLegal(Recip, VT)))
10507 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10508 DAG.getConstantFP(Recip, DL, VT), Flags);
10509 }
10510
10511 // If this FDIV is part of a reciprocal square root, it may be folded
10512 // into a target-specific square root estimate instruction.
10513 if (N1.getOpcode() == ISD::FSQRT) {
10514 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10515 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10516 }
10517 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10518 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10519 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10520 Flags)) {
10521 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10522 AddToWorklist(RV.getNode());
10523 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10524 }
10525 } else if (N1.getOpcode() == ISD::FP_ROUND &&
10526 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10527 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10528 Flags)) {
10529 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10530 AddToWorklist(RV.getNode());
10531 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10532 }
10533 } else if (N1.getOpcode() == ISD::FMUL) {
10534 // Look through an FMUL. Even though this won't remove the FDIV directly,
10535 // it's still worthwhile to get rid of the FSQRT if possible.
10536 SDValue SqrtOp;
10537 SDValue OtherOp;
10538 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10539 SqrtOp = N1.getOperand(0);
10540 OtherOp = N1.getOperand(1);
10541 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10542 SqrtOp = N1.getOperand(1);
10543 OtherOp = N1.getOperand(0);
10544 }
10545 if (SqrtOp.getNode()) {
10546 // We found a FSQRT, so try to make this fold:
10547 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10548 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10549 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10550 AddToWorklist(RV.getNode());
10551 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10552 }
10553 }
10554 }
10555
10556 // Fold into a reciprocal estimate and multiply instead of a real divide.
10557 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10558 AddToWorklist(RV.getNode());
10559 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10560 }
10561 }
10562
10563 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10564 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10565 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10566 // Both can be negated for free, check to see if at least one is cheaper
10567 // negated.
10568 if (LHSNeg == 2 || RHSNeg == 2)
10569 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10570 GetNegatedExpression(N0, DAG, LegalOperations),
10571 GetNegatedExpression(N1, DAG, LegalOperations),
10572 Flags);
10573 }
10574 }
10575
10576 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10577 return CombineRepeatedDivisors;
10578
10579 return SDValue();
10580}
10581
10582SDValue DAGCombiner::visitFREM(SDNode *N) {
10583 SDValue N0 = N->getOperand(0);
10584 SDValue N1 = N->getOperand(1);
10585 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10586 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10587 EVT VT = N->getValueType(0);
10588
10589 // fold (frem c1, c2) -> fmod(c1,c2)
10590 if (N0CFP && N1CFP)
10591 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10592
10593 if (SDValue NewSel = foldBinOpIntoSelect(N))
10594 return NewSel;
10595
10596 return SDValue();
10597}
10598
10599SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10600 if (!DAG.getTarget().Options.UnsafeFPMath)
10601 return SDValue();
10602
10603 SDValue N0 = N->getOperand(0);
10604 if (TLI.isFsqrtCheap(N0, DAG))
10605 return SDValue();
10606
10607 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10608 // For now, create a Flags object for use with all unsafe math transforms.
10609 SDNodeFlags Flags;
10610 Flags.setUnsafeAlgebra(true);
10611 return buildSqrtEstimate(N0, Flags);
10612}
10613
10614/// copysign(x, fp_extend(y)) -> copysign(x, y)
10615/// copysign(x, fp_round(y)) -> copysign(x, y)
10616static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10617 SDValue N1 = N->getOperand(1);
10618 if ((N1.getOpcode() == ISD::FP_EXTEND ||
10619 N1.getOpcode() == ISD::FP_ROUND)) {
10620 // Do not optimize out type conversion of f128 type yet.
10621 // For some targets like x86_64, configuration is changed to keep one f128
10622 // value in one SSE register, but instruction selection cannot handle
10623 // FCOPYSIGN on SSE registers yet.
10624 EVT N1VT = N1->getValueType(0);
10625 EVT N1Op0VT = N1->getOperand(0).getValueType();
10626 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10627 }
10628 return false;
10629}
10630
10631SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10632 SDValue N0 = N->getOperand(0);
10633 SDValue N1 = N->getOperand(1);
10634 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10635 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10636 EVT VT = N->getValueType(0);
10637
10638 if (N0CFP && N1CFP) // Constant fold
10639 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10640
10641 if (N1CFP) {
10642 const APFloat &V = N1CFP->getValueAPF();
10643 // copysign(x, c1) -> fabs(x) iff ispos(c1)
10644 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10645 if (!V.isNegative()) {
10646 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10647 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10648 } else {
10649 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10650 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10651 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10652 }
10653 }
10654
10655 // copysign(fabs(x), y) -> copysign(x, y)
10656 // copysign(fneg(x), y) -> copysign(x, y)
10657 // copysign(copysign(x,z), y) -> copysign(x, y)
10658 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10659 N0.getOpcode() == ISD::FCOPYSIGN)
10660 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10661
10662 // copysign(x, abs(y)) -> abs(x)
10663 if (N1.getOpcode() == ISD::FABS)
10664 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10665
10666 // copysign(x, copysign(y,z)) -> copysign(x, z)
10667 if (N1.getOpcode() == ISD::FCOPYSIGN)
10668 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10669
10670 // copysign(x, fp_extend(y)) -> copysign(x, y)
10671 // copysign(x, fp_round(y)) -> copysign(x, y)
10672 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10673 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10674
10675 return SDValue();
10676}
10677
10678SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10679 SDValue N0 = N->getOperand(0);
10680 EVT VT = N->getValueType(0);
10681 EVT OpVT = N0.getValueType();
10682
10683 // fold (sint_to_fp c1) -> c1fp
10684 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10685 // ...but only if the target supports immediate floating-point values
10686 (!LegalOperations ||
10687 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10688 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10689
10690 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10691 // but UINT_TO_FP is legal on this target, try to convert.
10692 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10693 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10694 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10695 if (DAG.SignBitIsZero(N0))
10696 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10697 }
10698
10699 // The next optimizations are desirable only if SELECT_CC can be lowered.
10700 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10701 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10702 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10703 !VT.isVector() &&
10704 (!LegalOperations ||
10705 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10706 SDLoc DL(N);
10707 SDValue Ops[] =
10708 { N0.getOperand(0), N0.getOperand(1),
10709 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10710 N0.getOperand(2) };
10711 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10712 }
10713
10714 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10715 // (select_cc x, y, 1.0, 0.0,, cc)
10716 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10717 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10718 (!LegalOperations ||
10719 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10720 SDLoc DL(N);
10721 SDValue Ops[] =
10722 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10723 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10724 N0.getOperand(0).getOperand(2) };
10725 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10726 }
10727 }
10728
10729 return SDValue();
10730}
10731
10732SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10733 SDValue N0 = N->getOperand(0);
10734 EVT VT = N->getValueType(0);
10735 EVT OpVT = N0.getValueType();
10736
10737 // fold (uint_to_fp c1) -> c1fp
10738 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10739 // ...but only if the target supports immediate floating-point values
10740 (!LegalOperations ||
10741 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10742 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10743
10744 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10745 // but SINT_TO_FP is legal on this target, try to convert.
10746 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10747 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10748 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10749 if (DAG.SignBitIsZero(N0))
10750 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10751 }
10752
10753 // The next optimizations are desirable only if SELECT_CC can be lowered.
10754 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10755 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10756 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10757 (!LegalOperations ||
10758 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10759 SDLoc DL(N);
10760 SDValue Ops[] =
10761 { N0.getOperand(0), N0.getOperand(1),
10762 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10763 N0.getOperand(2) };
10764 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10765 }
10766 }
10767
10768 return SDValue();
10769}
10770
10771// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10772static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10773 SDValue N0 = N->getOperand(0);
10774 EVT VT = N->getValueType(0);
10775
10776 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10777 return SDValue();
10778
10779 SDValue Src = N0.getOperand(0);
10780 EVT SrcVT = Src.getValueType();
10781 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10782 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10783
10784 // We can safely assume the conversion won't overflow the output range,
10785 // because (for example) (uint8_t)18293.f is undefined behavior.
10786
10787 // Since we can assume the conversion won't overflow, our decision as to
10788 // whether the input will fit in the float should depend on the minimum
10789 // of the input range and output range.
10790
10791 // This means this is also safe for a signed input and unsigned output, since
10792 // a negative input would lead to undefined behavior.
10793 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10794 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10795 unsigned ActualSize = std::min(InputSize, OutputSize);
10796 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10797
10798 // We can only fold away the float conversion if the input range can be
10799 // represented exactly in the float range.
10800 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10801 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10802 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10803 : ISD::ZERO_EXTEND;
10804 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10805 }
10806 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10807 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10808 return DAG.getBitcast(VT, Src);
10809 }
10810 return SDValue();
10811}
10812
10813SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10814 SDValue N0 = N->getOperand(0);
10815 EVT VT = N->getValueType(0);
10816
10817 // fold (fp_to_sint c1fp) -> c1
10818 if (isConstantFPBuildVectorOrConstantFP(N0))
10819 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10820
10821 return FoldIntToFPToInt(N, DAG);
10822}
10823
10824SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10825 SDValue N0 = N->getOperand(0);
10826 EVT VT = N->getValueType(0);
10827
10828 // fold (fp_to_uint c1fp) -> c1
10829 if (isConstantFPBuildVectorOrConstantFP(N0))
10830 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10831
10832 return FoldIntToFPToInt(N, DAG);
10833}
10834
10835SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10836 SDValue N0 = N->getOperand(0);
10837 SDValue N1 = N->getOperand(1);
10838 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10839 EVT VT = N->getValueType(0);
10840
10841 // fold (fp_round c1fp) -> c1fp
10842 if (N0CFP)
10843 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10844
10845 // fold (fp_round (fp_extend x)) -> x
10846 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10847 return N0.getOperand(0);
10848
10849 // fold (fp_round (fp_round x)) -> (fp_round x)
10850 if (N0.getOpcode() == ISD::FP_ROUND) {
10851 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10852 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10853
10854 // Skip this folding if it results in an fp_round from f80 to f16.
10855 //
10856 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10857 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10858 // instructions from f32 or f64. Moreover, the first (value-preserving)
10859 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10860 // x86.
10861 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10862 return SDValue();
10863
10864 // If the first fp_round isn't a value preserving truncation, it might
10865 // introduce a tie in the second fp_round, that wouldn't occur in the
10866 // single-step fp_round we want to fold to.
10867 // In other words, double rounding isn't the same as rounding.
10868 // Also, this is a value preserving truncation iff both fp_round's are.
10869 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10870 SDLoc DL(N);
10871 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10872 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10873 }
10874 }
10875
10876 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10877 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10878 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10879 N0.getOperand(0), N1);
10880 AddToWorklist(Tmp.getNode());
10881 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10882 Tmp, N0.getOperand(1));
10883 }
10884
10885 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10886 return NewVSel;
10887
10888 return SDValue();
10889}
10890
10891SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10892 SDValue N0 = N->getOperand(0);
10893 EVT VT = N->getValueType(0);
10894 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10895 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10896
10897 // fold (fp_round_inreg c1fp) -> c1fp
10898 if (N0CFP && isTypeLegal(EVT)) {
10899 SDLoc DL(N);
10900 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10901 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10902 }
10903
10904 return SDValue();
10905}
10906
10907SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10908 SDValue N0 = N->getOperand(0);
10909 EVT VT = N->getValueType(0);
10910
10911 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10912 if (N->hasOneUse() &&
10913 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10914 return SDValue();
10915
10916 // fold (fp_extend c1fp) -> c1fp
10917 if (isConstantFPBuildVectorOrConstantFP(N0))
10918 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10919
10920 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10921 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10922 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10923 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10924
10925 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10926 // value of X.
10927 if (N0.getOpcode() == ISD::FP_ROUND
10928 && N0.getConstantOperandVal(1) == 1) {
10929 SDValue In = N0.getOperand(0);
10930 if (In.getValueType() == VT) return In;
10931 if (VT.bitsLT(In.getValueType()))
10932 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10933 In, N0.getOperand(1));
10934 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10935 }
10936
10937 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10938 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10939 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10941 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10942 LN0->getChain(),
10943 LN0->getBasePtr(), N0.getValueType(),
10944 LN0->getMemOperand());
10945 CombineTo(N, ExtLoad);
10946 CombineTo(N0.getNode(),
10947 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10948 N0.getValueType(), ExtLoad,
10949 DAG.getIntPtrConstant(1, SDLoc(N0))),
10950 ExtLoad.getValue(1));
10951 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10952 }
10953
10954 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10955 return NewVSel;
10956
10957 return SDValue();
10958}
10959
10960SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10961 SDValue N0 = N->getOperand(0);
10962 EVT VT = N->getValueType(0);
10963
10964 // fold (fceil c1) -> fceil(c1)
10965 if (isConstantFPBuildVectorOrConstantFP(N0))
10966 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10967
10968 return SDValue();
10969}
10970
10971SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10972 SDValue N0 = N->getOperand(0);
10973 EVT VT = N->getValueType(0);
10974
10975 // fold (ftrunc c1) -> ftrunc(c1)
10976 if (isConstantFPBuildVectorOrConstantFP(N0))
10977 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10978
10979 // fold ftrunc (known rounded int x) -> x
10980 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
10981 // likely to be generated to extract integer from a rounded floating value.
10982 switch (N0.getOpcode()) {
10983 default: break;
10984 case ISD::FRINT:
10985 case ISD::FTRUNC:
10986 case ISD::FNEARBYINT:
10987 case ISD::FFLOOR:
10988 case ISD::FCEIL:
10989 return N0;
10990 }
10991
10992 return SDValue();
10993}
10994
10995SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10996 SDValue N0 = N->getOperand(0);
10997 EVT VT = N->getValueType(0);
10998
10999 // fold (ffloor c1) -> ffloor(c1)
11000 if (isConstantFPBuildVectorOrConstantFP(N0))
11001 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
11002
11003 return SDValue();
11004}
11005
11006// FIXME: FNEG and FABS have a lot in common; refactor.
11007SDValue DAGCombiner::visitFNEG(SDNode *N) {
11008 SDValue N0 = N->getOperand(0);
11009 EVT VT = N->getValueType(0);
11010
11011 // Constant fold FNEG.
11012 if (isConstantFPBuildVectorOrConstantFP(N0))
11013 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
11014
11015 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
11016 &DAG.getTarget().Options))
11017 return GetNegatedExpression(N0, DAG, LegalOperations);
11018
11019 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
11020 // constant pool values.
11021 if (!TLI.isFNegFree(VT) &&
11022 N0.getOpcode() == ISD::BITCAST &&
11023 N0.getNode()->hasOneUse()) {
11024 SDValue Int = N0.getOperand(0);
11025 EVT IntVT = Int.getValueType();
11026 if (IntVT.isInteger() && !IntVT.isVector()) {
11027 APInt SignMask;
11028 if (N0.getValueType().isVector()) {
11029 // For a vector, get a mask such as 0x80... per scalar element
11030 // and splat it.
11031 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
11032 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11033 } else {
11034 // For a scalar, just generate 0x80...
11035 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
11036 }
11037 SDLoc DL0(N0);
11038 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
11039 DAG.getConstant(SignMask, DL0, IntVT));
11040 AddToWorklist(Int.getNode());
11041 return DAG.getBitcast(VT, Int);
11042 }
11043 }
11044
11045 // (fneg (fmul c, x)) -> (fmul -c, x)
11046 if (N0.getOpcode() == ISD::FMUL &&
11047 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
11048 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
11049 if (CFP1) {
11050 APFloat CVal = CFP1->getValueAPF();
11051 CVal.changeSign();
11052 if (Level >= AfterLegalizeDAG &&
11053 (TLI.isFPImmLegal(CVal, VT) ||
11054 TLI.isOperationLegal(ISD::ConstantFP, VT)))
11055 return DAG.getNode(
11056 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
11057 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
11058 N0->getFlags());
11059 }
11060 }
11061
11062 return SDValue();
11063}
11064
11065SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
11066 SDValue N0 = N->getOperand(0);
11067 SDValue N1 = N->getOperand(1);
11068 EVT VT = N->getValueType(0);
11069 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11070 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11071
11072 if (N0CFP && N1CFP) {
11073 const APFloat &C0 = N0CFP->getValueAPF();
11074 const APFloat &C1 = N1CFP->getValueAPF();
11075 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11076 }
11077
11078 // Canonicalize to constant on RHS.
11079 if (isConstantFPBuildVectorOrConstantFP(N0) &&
11080 !isConstantFPBuildVectorOrConstantFP(N1))
11081 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11082
11083 return SDValue();
11084}
11085
11086SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11087 SDValue N0 = N->getOperand(0);
11088 SDValue N1 = N->getOperand(1);
11089 EVT VT = N->getValueType(0);
11090 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11091 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11092
11093 if (N0CFP && N1CFP) {
11094 const APFloat &C0 = N0CFP->getValueAPF();
11095 const APFloat &C1 = N1CFP->getValueAPF();
11096 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11097 }
11098
11099 // Canonicalize to constant on RHS.
11100 if (isConstantFPBuildVectorOrConstantFP(N0) &&
11101 !isConstantFPBuildVectorOrConstantFP(N1))
11102 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11103
11104 return SDValue();
11105}
11106
11107SDValue DAGCombiner::visitFABS(SDNode *N) {
11108 SDValue N0 = N->getOperand(0);
11109 EVT VT = N->getValueType(0);
11110
11111 // fold (fabs c1) -> fabs(c1)
11112 if (isConstantFPBuildVectorOrConstantFP(N0))
11113 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11114
11115 // fold (fabs (fabs x)) -> (fabs x)
11116 if (N0.getOpcode() == ISD::FABS)
11117 return N->getOperand(0);
11118
11119 // fold (fabs (fneg x)) -> (fabs x)
11120 // fold (fabs (fcopysign x, y)) -> (fabs x)
11121 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11122 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11123
11124 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11125 // constant pool values.
11126 if (!TLI.isFAbsFree(VT) &&
11127 N0.getOpcode() == ISD::BITCAST &&
11128 N0.getNode()->hasOneUse()) {
11129 SDValue Int = N0.getOperand(0);
11130 EVT IntVT = Int.getValueType();
11131 if (IntVT.isInteger() && !IntVT.isVector()) {
11132 APInt SignMask;
11133 if (N0.getValueType().isVector()) {
11134 // For a vector, get a mask such as 0x7f... per scalar element
11135 // and splat it.
11136 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11137 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11138 } else {
11139 // For a scalar, just generate 0x7f...
11140 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11141 }
11142 SDLoc DL(N0);
11143 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11144 DAG.getConstant(SignMask, DL, IntVT));
11145 AddToWorklist(Int.getNode());
11146 return DAG.getBitcast(N->getValueType(0), Int);
11147 }
11148 }
11149
11150 return SDValue();
11151}
11152
11153SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11154 SDValue Chain = N->getOperand(0);
11155 SDValue N1 = N->getOperand(1);
11156 SDValue N2 = N->getOperand(2);
11157
11158 // If N is a constant we could fold this into a fallthrough or unconditional
11159 // branch. However that doesn't happen very often in normal code, because
11160 // Instcombine/SimplifyCFG should have handled the available opportunities.
11161 // If we did this folding here, it would be necessary to update the
11162 // MachineBasicBlock CFG, which is awkward.
11163
11164 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11165 // on the target.
11166 if (N1.getOpcode() == ISD::SETCC &&
11167 TLI.isOperationLegalOrCustom(ISD::BR_CC,
11168 N1.getOperand(0).getValueType())) {
11169 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11170 Chain, N1.getOperand(2),
11171 N1.getOperand(0), N1.getOperand(1), N2);
11172 }
11173
11174 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
11175 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
11176 (N1.getOperand(0).hasOneUse() &&
11177 N1.getOperand(0).getOpcode() == ISD::SRL))) {
11178 SDNode *Trunc = nullptr;
11179 if (N1.getOpcode() == ISD::TRUNCATE) {
11180 // Look pass the truncate.
11181 Trunc = N1.getNode();
11182 N1 = N1.getOperand(0);
11183 }
11184
11185 // Match this pattern so that we can generate simpler code:
11186 //
11187 // %a = ...
11188 // %b = and i32 %a, 2
11189 // %c = srl i32 %b, 1
11190 // brcond i32 %c ...
11191 //
11192 // into
11193 //
11194 // %a = ...
11195 // %b = and i32 %a, 2
11196 // %c = setcc eq %b, 0
11197 // brcond %c ...
11198 //
11199 // This applies only when the AND constant value has one bit set and the
11200 // SRL constant is equal to the log2 of the AND constant. The back-end is
11201 // smart enough to convert the result into a TEST/JMP sequence.
11202 SDValue Op0 = N1.getOperand(0);
11203 SDValue Op1 = N1.getOperand(1);
11204
11205 if (Op0.getOpcode() == ISD::AND &&
11206 Op1.getOpcode() == ISD::Constant) {
11207 SDValue AndOp1 = Op0.getOperand(1);
11208
11209 if (AndOp1.getOpcode() == ISD::Constant) {
11210 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11211
11212 if (AndConst.isPowerOf2() &&
11213 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
11214 SDLoc DL(N);
11215 SDValue SetCC =
11216 DAG.getSetCC(DL,
11217 getSetCCResultType(Op0.getValueType()),
11218 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11219 ISD::SETNE);
11220
11221 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
11222 MVT::Other, Chain, SetCC, N2);
11223 // Don't add the new BRCond into the worklist or else SimplifySelectCC
11224 // will convert it back to (X & C1) >> C2.
11225 CombineTo(N, NewBRCond, false);
11226 // Truncate is dead.
11227 if (Trunc)
11228 deleteAndRecombine(Trunc);
11229 // Replace the uses of SRL with SETCC
11230 WorklistRemover DeadNodes(*this);
11231 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11232 deleteAndRecombine(N1.getNode());
11233 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11234 }
11235 }
11236 }
11237
11238 if (Trunc)
11239 // Restore N1 if the above transformation doesn't match.
11240 N1 = N->getOperand(1);
11241 }
11242
11243 // Transform br(xor(x, y)) -> br(x != y)
11244 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11245 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
11246 SDNode *TheXor = N1.getNode();
11247 SDValue Op0 = TheXor->getOperand(0);
11248 SDValue Op1 = TheXor->getOperand(1);
11249 if (Op0.getOpcode() == Op1.getOpcode()) {
11250 // Avoid missing important xor optimizations.
11251 if (SDValue Tmp = visitXOR(TheXor)) {
11252 if (Tmp.getNode() != TheXor) {
11253 DEBUG(dbgs() << "\nReplacing.8 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.8 "; TheXor->
dump(&DAG); dbgs() << "\nWith: "; Tmp.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11254 TheXor->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.8 "; TheXor->
dump(&DAG); dbgs() << "\nWith: "; Tmp.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11255 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.8 "; TheXor->
dump(&DAG); dbgs() << "\nWith: "; Tmp.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11256 Tmp.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.8 "; TheXor->
dump(&DAG); dbgs() << "\nWith: "; Tmp.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11257 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.8 "; TheXor->
dump(&DAG); dbgs() << "\nWith: "; Tmp.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
;
11258 WorklistRemover DeadNodes(*this);
11259 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
11260 deleteAndRecombine(TheXor);
11261 return DAG.getNode(ISD::BRCOND, SDLoc(N),
11262 MVT::Other, Chain, Tmp, N2);
11263 }
11264
11265 // visitXOR has changed XOR's operands or replaced the XOR completely,
11266 // bail out.
11267 return SDValue(N, 0);
11268 }
11269 }
11270
11271 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11272 bool Equal = false;
11273 if (isOneConstant(Op0) && Op0.hasOneUse() &&
11274 Op0.getOpcode() == ISD::XOR) {
11275 TheXor = Op0.getNode();
11276 Equal = true;
11277 }
11278
11279 EVT SetCCVT = N1.getValueType();
11280 if (LegalTypes)
11281 SetCCVT = getSetCCResultType(SetCCVT);
11282 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
11283 SetCCVT,
11284 Op0, Op1,
11285 Equal ? ISD::SETEQ : ISD::SETNE);
11286 // Replace the uses of XOR with SETCC
11287 WorklistRemover DeadNodes(*this);
11288 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11289 deleteAndRecombine(N1.getNode());
11290 return DAG.getNode(ISD::BRCOND, SDLoc(N),
11291 MVT::Other, Chain, SetCC, N2);
11292 }
11293 }
11294
11295 return SDValue();
11296}
11297
11298// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11299//
11300SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11301 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11302 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11303
11304 // If N is a constant we could fold this into a fallthrough or unconditional
11305 // branch. However that doesn't happen very often in normal code, because
11306 // Instcombine/SimplifyCFG should have handled the available opportunities.
11307 // If we did this folding here, it would be necessary to update the
11308 // MachineBasicBlock CFG, which is awkward.
11309
11310 // Use SimplifySetCC to simplify SETCC's.
11311 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11312 CondLHS, CondRHS, CC->get(), SDLoc(N),
11313 false);
11314 if (Simp.getNode()) AddToWorklist(Simp.getNode());
11315
11316 // fold to a simpler setcc
11317 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11318 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11319 N->getOperand(0), Simp.getOperand(2),
11320 Simp.getOperand(0), Simp.getOperand(1),
11321 N->getOperand(4));
11322
11323 return SDValue();
11324}
11325
11326/// Return true if 'Use' is a load or a store that uses N as its base pointer
11327/// and that N may be folded in the load / store addressing mode.
11328static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11329 SelectionDAG &DAG,
11330 const TargetLowering &TLI) {
11331 EVT VT;
11332 unsigned AS;
11333
11334 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
11335 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11336 return false;
11337 VT = LD->getMemoryVT();
11338 AS = LD->getAddressSpace();
11339 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
11340 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11341 return false;
11342 VT = ST->getMemoryVT();
11343 AS = ST->getAddressSpace();
11344 } else
11345 return false;
11346
11347 TargetLowering::AddrMode AM;
11348 if (N->getOpcode() == ISD::ADD) {
11349 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11350 if (Offset)
11351 // [reg +/- imm]
11352 AM.BaseOffs = Offset->getSExtValue();
11353 else
11354 // [reg +/- reg]
11355 AM.Scale = 1;
11356 } else if (N->getOpcode() == ISD::SUB) {
11357 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11358 if (Offset)
11359 // [reg +/- imm]
11360 AM.BaseOffs = -Offset->getSExtValue();
11361 else
11362 // [reg +/- reg]
11363 AM.Scale = 1;
11364 } else
11365 return false;
11366
11367 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11368 VT.getTypeForEVT(*DAG.getContext()), AS);
11369}
11370
11371/// Try turning a load/store into a pre-indexed load/store when the base
11372/// pointer is an add or subtract and it has other uses besides the load/store.
11373/// After the transformation, the new indexed load/store has effectively folded
11374/// the add/subtract in and all of its other uses are redirected to the
11375/// new load/store.
11376bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11377 if (Level < AfterLegalizeDAG)
11378 return false;
11379
11380 bool isLoad = true;
11381 SDValue Ptr;
11382 EVT VT;
11383 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11384 if (LD->isIndexed())
11385 return false;
11386 VT = LD->getMemoryVT();
11387 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11388 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11389 return false;
11390 Ptr = LD->getBasePtr();
11391 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11392 if (ST->isIndexed())
11393 return false;
11394 VT = ST->getMemoryVT();
11395 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11396 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11397 return false;
11398 Ptr = ST->getBasePtr();
11399 isLoad = false;
11400 } else {
11401 return false;
11402 }
11403
11404 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11405 // out. There is no reason to make this a preinc/predec.
11406 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11407 Ptr.getNode()->hasOneUse())
11408 return false;
11409
11410 // Ask the target to do addressing mode selection.
11411 SDValue BasePtr;
11412 SDValue Offset;
11413 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11414 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11415 return false;
11416
11417 // Backends without true r+i pre-indexed forms may need to pass a
11418 // constant base with a variable offset so that constant coercion
11419 // will work with the patterns in canonical form.
11420 bool Swapped = false;
11421 if (isa<ConstantSDNode>(BasePtr)) {
11422 std::swap(BasePtr, Offset);
11423 Swapped = true;
11424 }
11425
11426 // Don't create a indexed load / store with zero offset.
11427 if (isNullConstant(Offset))
11428 return false;
11429
11430 // Try turning it into a pre-indexed load / store except when:
11431 // 1) The new base ptr is a frame index.
11432 // 2) If N is a store and the new base ptr is either the same as or is a
11433 // predecessor of the value being stored.
11434 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11435 // that would create a cycle.
11436 // 4) All uses are load / store ops that use it as old base ptr.
11437
11438 // Check #1. Preinc'ing a frame index would require copying the stack pointer
11439 // (plus the implicit offset) to a register to preinc anyway.
11440 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11441 return false;
11442
11443 // Check #2.
11444 if (!isLoad) {
11445 SDValue Val = cast<StoreSDNode>(N)->getValue();
11446 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11447 return false;
11448 }
11449
11450 // Caches for hasPredecessorHelper.
11451 SmallPtrSet<const SDNode *, 32> Visited;
11452 SmallVector<const SDNode *, 16> Worklist;
11453 Worklist.push_back(N);
11454
11455 // If the offset is a constant, there may be other adds of constants that
11456 // can be folded with this one. We should do this to avoid having to keep
11457 // a copy of the original base pointer.
11458 SmallVector<SDNode *, 16> OtherUses;
11459 if (isa<ConstantSDNode>(Offset))
11460 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11461 UE = BasePtr.getNode()->use_end();
11462 UI != UE; ++UI) {
11463 SDUse &Use = UI.getUse();
11464 // Skip the use that is Ptr and uses of other results from BasePtr's
11465 // node (important for nodes that return multiple results).
11466 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11467 continue;
11468
11469 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11470 continue;
11471
11472 if (Use.getUser()->getOpcode() != ISD::ADD &&
11473 Use.getUser()->getOpcode() != ISD::SUB) {
11474 OtherUses.clear();
11475 break;
11476 }
11477
11478 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11479 if (!isa<ConstantSDNode>(Op1)) {
11480 OtherUses.clear();
11481 break;
11482 }
11483
11484 // FIXME: In some cases, we can be smarter about this.
11485 if (Op1.getValueType() != Offset.getValueType()) {
11486 OtherUses.clear();
11487 break;
11488 }
11489
11490 OtherUses.push_back(Use.getUser());
11491 }
11492
11493 if (Swapped)
11494 std::swap(BasePtr, Offset);
11495
11496 // Now check for #3 and #4.
11497 bool RealUse = false;
11498
11499 for (SDNode *Use : Ptr.getNode()->uses()) {
11500 if (Use == N)
11501 continue;
11502 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11503 return false;
11504
11505 // If Ptr may be folded in addressing mode of other use, then it's
11506 // not profitable to do this transformation.
11507 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11508 RealUse = true;
11509 }
11510
11511 if (!RealUse)
11512 return false;
11513
11514 SDValue Result;
11515 if (isLoad)
11516 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11517 BasePtr, Offset, AM);
11518 else
11519 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11520 BasePtr, Offset, AM);
11521 ++PreIndexedNodes;
11522 ++NodesCombined;
11523 DEBUG(dbgs() << "\nReplacing.4 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11524 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11525 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11526 Result.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11527 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.4 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
;
11528 WorklistRemover DeadNodes(*this);
11529 if (isLoad) {
11530 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11532 } else {
11533 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11534 }
11535
11536 // Finally, since the node is now dead, remove it from the graph.
11537 deleteAndRecombine(N);
11538
11539 if (Swapped)
11540 std::swap(BasePtr, Offset);
11541
11542 // Replace other uses of BasePtr that can be updated to use Ptr
11543 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11544 unsigned OffsetIdx = 1;
11545 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11546 OffsetIdx = 0;
11547 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==(static_cast <bool> (OtherUses[i]->getOperand(!OffsetIdx
).getNode() == BasePtr.getNode() && "Expected BasePtr operand"
) ? void (0) : __assert_fail ("OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr.getNode() && \"Expected BasePtr operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11548, __extension__ __PRETTY_FUNCTION__))
11548 BasePtr.getNode() && "Expected BasePtr operand")(static_cast <bool> (OtherUses[i]->getOperand(!OffsetIdx
).getNode() == BasePtr.getNode() && "Expected BasePtr operand"
) ? void (0) : __assert_fail ("OtherUses[i]->getOperand(!OffsetIdx).getNode() == BasePtr.getNode() && \"Expected BasePtr operand\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11548, __extension__ __PRETTY_FUNCTION__))
;
11549
11550 // We need to replace ptr0 in the following expression:
11551 // x0 * offset0 + y0 * ptr0 = t0
11552 // knowing that
11553 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11554 //
11555 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11556 // indexed load/store and the expression that needs to be re-written.
11557 //
11558 // Therefore, we have:
11559 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11560
11561 ConstantSDNode *CN =
11562 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11563 int X0, X1, Y0, Y1;
11564 const APInt &Offset0 = CN->getAPIntValue();
11565 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11566
11567 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11568 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11569 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11570 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11571
11572 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11573
11574 APInt CNV = Offset0;
11575 if (X0 < 0) CNV = -CNV;
11576 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11577 else CNV = CNV - Offset1;
11578
11579 SDLoc DL(OtherUses[i]);
11580
11581 // We can now generate the new expression.
11582 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11583 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11584
11585 SDValue NewUse = DAG.getNode(Opcode,
11586 DL,
11587 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11588 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11589 deleteAndRecombine(OtherUses[i]);
11590 }
11591
11592 // Replace the uses of Ptr with uses of the updated base value.
11593 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11594 deleteAndRecombine(Ptr.getNode());
11595 AddToWorklist(Result.getNode());
11596
11597 return true;
11598}
11599
11600/// Try to combine a load/store with a add/sub of the base pointer node into a
11601/// post-indexed load/store. The transformation folded the add/subtract into the
11602/// new indexed load/store effectively and all of its uses are redirected to the
11603/// new load/store.
11604bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11605 if (Level < AfterLegalizeDAG)
11606 return false;
11607
11608 bool isLoad = true;
11609 SDValue Ptr;
11610 EVT VT;
11611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11612 if (LD->isIndexed())
11613 return false;
11614 VT = LD->getMemoryVT();
11615 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11616 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11617 return false;
11618 Ptr = LD->getBasePtr();
11619 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11620 if (ST->isIndexed())
11621 return false;
11622 VT = ST->getMemoryVT();
11623 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11624 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11625 return false;
11626 Ptr = ST->getBasePtr();
11627 isLoad = false;
11628 } else {
11629 return false;
11630 }
11631
11632 if (Ptr.getNode()->hasOneUse())
11633 return false;
11634
11635 for (SDNode *Op : Ptr.getNode()->uses()) {
11636 if (Op == N ||
11637 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11638 continue;
11639
11640 SDValue BasePtr;
11641 SDValue Offset;
11642 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11643 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11644 // Don't create a indexed load / store with zero offset.
11645 if (isNullConstant(Offset))
11646 continue;
11647
11648 // Try turning it into a post-indexed load / store except when
11649 // 1) All uses are load / store ops that use it as base ptr (and
11650 // it may be folded as addressing mmode).
11651 // 2) Op must be independent of N, i.e. Op is neither a predecessor
11652 // nor a successor of N. Otherwise, if Op is folded that would
11653 // create a cycle.
11654
11655 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11656 continue;
11657
11658 // Check for #1.
11659 bool TryNext = false;
11660 for (SDNode *Use : BasePtr.getNode()->uses()) {
11661 if (Use == Ptr.getNode())
11662 continue;
11663
11664 // If all the uses are load / store addresses, then don't do the
11665 // transformation.
11666 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11667 bool RealUse = false;
11668 for (SDNode *UseUse : Use->uses()) {
11669 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11670 RealUse = true;
11671 }
11672
11673 if (!RealUse) {
11674 TryNext = true;
11675 break;
11676 }
11677 }
11678 }
11679
11680 if (TryNext)
11681 continue;
11682
11683 // Check for #2
11684 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11685 SDValue Result = isLoad
11686 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11687 BasePtr, Offset, AM)
11688 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11689 BasePtr, Offset, AM);
11690 ++PostIndexedNodes;
11691 ++NodesCombined;
11692 DEBUG(dbgs() << "\nReplacing.5 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11693 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11694 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11695 Result.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
11696 dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.5 "; N->dump
(&DAG); dbgs() << "\nWith: "; Result.getNode()->
dump(&DAG); dbgs() << '\n'; } } while (false)
;
11697 WorklistRemover DeadNodes(*this);
11698 if (isLoad) {
11699 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11700 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11701 } else {
11702 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11703 }
11704
11705 // Finally, since the node is now dead, remove it from the graph.
11706 deleteAndRecombine(N);
11707
11708 // Replace the uses of Use with uses of the updated base value.
11709 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11710 Result.getValue(isLoad ? 1 : 0));
11711 deleteAndRecombine(Op);
11712 return true;
11713 }
11714 }
11715 }
11716
11717 return false;
11718}
11719
11720/// \brief Return the base-pointer arithmetic from an indexed \p LD.
11721SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11722 ISD::MemIndexedMode AM = LD->getAddressingMode();
11723 assert(AM != ISD::UNINDEXED)(static_cast <bool> (AM != ISD::UNINDEXED) ? void (0) :
__assert_fail ("AM != ISD::UNINDEXED", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11723, __extension__ __PRETTY_FUNCTION__))
;
11724 SDValue BP = LD->getOperand(1);
11725 SDValue Inc = LD->getOperand(2);
11726
11727 // Some backends use TargetConstants for load offsets, but don't expect
11728 // TargetConstants in general ADD nodes. We can convert these constants into
11729 // regular Constants (if the constant is not opaque).
11730 assert((Inc.getOpcode() != ISD::TargetConstant ||(static_cast <bool> ((Inc.getOpcode() != ISD::TargetConstant
|| !cast<ConstantSDNode>(Inc)->isOpaque()) &&
"Cannot split out indexing using opaque target constants") ?
void (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11732, __extension__ __PRETTY_FUNCTION__))
11731 !cast<ConstantSDNode>(Inc)->isOpaque()) &&(static_cast <bool> ((Inc.getOpcode() != ISD::TargetConstant
|| !cast<ConstantSDNode>(Inc)->isOpaque()) &&
"Cannot split out indexing using opaque target constants") ?
void (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11732, __extension__ __PRETTY_FUNCTION__))
11732 "Cannot split out indexing using opaque target constants")(static_cast <bool> ((Inc.getOpcode() != ISD::TargetConstant
|| !cast<ConstantSDNode>(Inc)->isOpaque()) &&
"Cannot split out indexing using opaque target constants") ?
void (0) : __assert_fail ("(Inc.getOpcode() != ISD::TargetConstant || !cast<ConstantSDNode>(Inc)->isOpaque()) && \"Cannot split out indexing using opaque target constants\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11732, __extension__ __PRETTY_FUNCTION__))
;
11733 if (Inc.getOpcode() == ISD::TargetConstant) {
11734 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11735 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11736 ConstInc->getValueType(0));
11737 }
11738
11739 unsigned Opc =
11740 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11741 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11742}
11743
11744SDValue DAGCombiner::visitLOAD(SDNode *N) {
11745 LoadSDNode *LD = cast<LoadSDNode>(N);
11746 SDValue Chain = LD->getChain();
11747 SDValue Ptr = LD->getBasePtr();
11748
11749 // If load is not volatile and there are no uses of the loaded value (and
11750 // the updated indexed value in case of indexed loads), change uses of the
11751 // chain value into uses of the chain input (i.e. delete the dead load).
11752 if (!LD->isVolatile()) {
11753 if (N->getValueType(1) == MVT::Other) {
11754 // Unindexed loads.
11755 if (!N->hasAnyUseOfValue(0)) {
11756 // It's not safe to use the two value CombineTo variant here. e.g.
11757 // v1, chain2 = load chain1, loc
11758 // v2, chain3 = load chain2, loc
11759 // v3 = add v2, c
11760 // Now we replace use of chain2 with chain1. This makes the second load
11761 // isomorphic to the one we are deleting, and thus makes this load live.
11762 DEBUG(dbgs() << "\nReplacing.6 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump
(&DAG); dbgs() << "\nWith chain: "; Chain.getNode()
->dump(&DAG); dbgs() << "\n"; } } while (false)
11763 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump
(&DAG); dbgs() << "\nWith chain: "; Chain.getNode()
->dump(&DAG); dbgs() << "\n"; } } while (false)
11764 dbgs() << "\nWith chain: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump
(&DAG); dbgs() << "\nWith chain: "; Chain.getNode()
->dump(&DAG); dbgs() << "\n"; } } while (false)
11765 Chain.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump
(&DAG); dbgs() << "\nWith chain: "; Chain.getNode()
->dump(&DAG); dbgs() << "\n"; } } while (false)
11766 dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.6 "; N->dump
(&DAG); dbgs() << "\nWith chain: "; Chain.getNode()
->dump(&DAG); dbgs() << "\n"; } } while (false)
;
11767 WorklistRemover DeadNodes(*this);
11768 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11769 AddUsersToWorklist(Chain.getNode());
11770 if (N->use_empty())
11771 deleteAndRecombine(N);
11772
11773 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11774 }
11775 } else {
11776 // Indexed loads.
11777 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?")(static_cast <bool> (N->getValueType(2) == MVT::Other
&& "Malformed indexed loads?") ? void (0) : __assert_fail
("N->getValueType(2) == MVT::Other && \"Malformed indexed loads?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 11777, __extension__ __PRETTY_FUNCTION__))
;
11778
11779 // If this load has an opaque TargetConstant offset, then we cannot split
11780 // the indexing into an add/sub directly (that TargetConstant may not be
11781 // valid for a different type of node, and we cannot convert an opaque
11782 // target constant into a regular constant).
11783 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11784 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11785
11786 if (!N->hasAnyUseOfValue(0) &&
11787 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11788 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11789 SDValue Index;
11790 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11791 Index = SplitIndexingFromLoad(LD);
11792 // Try to fold the base pointer arithmetic into subsequent loads and
11793 // stores.
11794 AddUsersToWorklist(N);
11795 } else
11796 Index = DAG.getUNDEF(N->getValueType(1));
11797 DEBUG(dbgs() << "\nReplacing.7 ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump
(&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump
(&DAG); dbgs() << " and 2 other values\n"; } } while
(false)
11798 N->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump
(&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump
(&DAG); dbgs() << " and 2 other values\n"; } } while
(false)
11799 dbgs() << "\nWith: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump
(&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump
(&DAG); dbgs() << " and 2 other values\n"; } } while
(false)
11800 Undef.getNode()->dump(&DAG);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump
(&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump
(&DAG); dbgs() << " and 2 other values\n"; } } while
(false)
11801 dbgs() << " and 2 other values\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dagcombine")) { dbgs() << "\nReplacing.7 "; N->dump
(&DAG); dbgs() << "\nWith: "; Undef.getNode()->dump
(&DAG); dbgs() << " and 2 other values\n"; } } while
(false)
;
11802 WorklistRemover DeadNodes(*this);
11803 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11804 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11805 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11806 deleteAndRecombine(N);
11807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11808 }
11809 }
11810 }
11811
11812 // If this load is directly stored, replace the load value with the stored
11813 // value.
11814 // TODO: Handle store large -> read small portion.
11815 // TODO: Handle TRUNCSTORE/LOADEXT
11816 if (OptLevel != CodeGenOpt::None &&
11817 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11818 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11819 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11820 if (PrevST->getBasePtr() == Ptr &&
11821 PrevST->getValue().getValueType() == N->getValueType(0))
11822 return CombineTo(N, PrevST->getOperand(1), Chain);
11823 }
11824 }
11825
11826 // Try to infer better alignment information than the load already has.
11827 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11828 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11829 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11830 SDValue NewLoad = DAG.getExtLoad(
11831 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11832 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11833 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11834 if (NewLoad.getNode() != N)
11835 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11836 }
11837 }
11838 }
11839
11840 if (LD->isUnindexed()) {
11841 // Walk up chain skipping non-aliasing memory nodes.
11842 SDValue BetterChain = FindBetterChain(N, Chain);
11843
11844 // If there is a better chain.
11845 if (Chain != BetterChain) {
11846 SDValue ReplLoad;
11847
11848 // Replace the chain to void dependency.
11849 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11850 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11851 BetterChain, Ptr, LD->getMemOperand());
11852 } else {
11853 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11854 LD->getValueType(0),
11855 BetterChain, Ptr, LD->getMemoryVT(),
11856 LD->getMemOperand());
11857 }
11858
11859 // Create token factor to keep old chain connected.
11860 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11861 MVT::Other, Chain, ReplLoad.getValue(1));
11862
11863 // Replace uses with load result and token factor
11864 return CombineTo(N, ReplLoad.getValue(0), Token);
11865 }
11866 }
11867
11868 // Try transforming N to an indexed load.
11869 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11870 return SDValue(N, 0);
11871
11872 // Try to slice up N to more direct loads if the slices are mapped to
11873 // different register banks or pairing can take place.
11874 if (SliceUpLoad(N))
11875 return SDValue(N, 0);
11876
11877 return SDValue();
11878}
11879
11880namespace {
11881
11882/// \brief Helper structure used to slice a load in smaller loads.
11883/// Basically a slice is obtained from the following sequence:
11884/// Origin = load Ty1, Base
11885/// Shift = srl Ty1 Origin, CstTy Amount
11886/// Inst = trunc Shift to Ty2
11887///
11888/// Then, it will be rewritten into:
11889/// Slice = load SliceTy, Base + SliceOffset
11890/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11891///
11892/// SliceTy is deduced from the number of bits that are actually used to
11893/// build Inst.
11894struct LoadedSlice {
11895 /// \brief Helper structure used to compute the cost of a slice.
11896 struct Cost {
11897 /// Are we optimizing for code size.
11898 bool ForCodeSize;
11899
11900 /// Various cost.
11901 unsigned Loads = 0;
11902 unsigned Truncates = 0;
11903 unsigned CrossRegisterBanksCopies = 0;
11904 unsigned ZExts = 0;
11905 unsigned Shift = 0;
11906
11907 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
11908
11909 /// \brief Get the cost of one isolated slice.
11910 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11911 : ForCodeSize(ForCodeSize), Loads(1) {
11912 EVT TruncType = LS.Inst->getValueType(0);
11913 EVT LoadedType = LS.getLoadedType();
11914 if (TruncType != LoadedType &&
11915 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11916 ZExts = 1;
11917 }
11918
11919 /// \brief Account for slicing gain in the current cost.
11920 /// Slicing provide a few gains like removing a shift or a
11921 /// truncate. This method allows to grow the cost of the original
11922 /// load with the gain from this slice.
11923 void addSliceGain(const LoadedSlice &LS) {
11924 // Each slice saves a truncate.
11925 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11926 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11927 LS.Inst->getValueType(0)))
11928 ++Truncates;
11929 // If there is a shift amount, this slice gets rid of it.
11930 if (LS.Shift)
11931 ++Shift;
11932 // If this slice can merge a cross register bank copy, account for it.
11933 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11934 ++CrossRegisterBanksCopies;
11935 }
11936
11937 Cost &operator+=(const Cost &RHS) {
11938 Loads += RHS.Loads;
11939 Truncates += RHS.Truncates;
11940 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11941 ZExts += RHS.ZExts;
11942 Shift += RHS.Shift;
11943 return *this;
11944 }
11945
11946 bool operator==(const Cost &RHS) const {
11947 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11948 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11949 ZExts == RHS.ZExts && Shift == RHS.Shift;
11950 }
11951
11952 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11953
11954 bool operator<(const Cost &RHS) const {
11955 // Assume cross register banks copies are as expensive as loads.
11956 // FIXME: Do we want some more target hooks?
11957 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11958 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11959 // Unless we are optimizing for code size, consider the
11960 // expensive operation first.
11961 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11962 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11963 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11964 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11965 }
11966
11967 bool operator>(const Cost &RHS) const { return RHS < *this; }
11968
11969 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11970
11971 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11972 };
11973
11974 // The last instruction that represent the slice. This should be a
11975 // truncate instruction.
11976 SDNode *Inst;
11977
11978 // The original load instruction.
11979 LoadSDNode *Origin;
11980
11981 // The right shift amount in bits from the original load.
11982 unsigned Shift;
11983
11984 // The DAG from which Origin came from.
11985 // This is used to get some contextual information about legal types, etc.
11986 SelectionDAG *DAG;
11987
11988 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11989 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11990 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11991
11992 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11993 /// \return Result is \p BitWidth and has used bits set to 1 and
11994 /// not used bits set to 0.
11995 APInt getUsedBits() const {
11996 // Reproduce the trunc(lshr) sequence:
11997 // - Start from the truncated value.
11998 // - Zero extend to the desired bit width.
11999 // - Shift left.
12000 assert(Origin && "No original load to compare against.")(static_cast <bool> (Origin && "No original load to compare against."
) ? void (0) : __assert_fail ("Origin && \"No original load to compare against.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12000, __extension__ __PRETTY_FUNCTION__))
;
12001 unsigned BitWidth = Origin->getValueSizeInBits(0);
12002 assert(Inst && "This slice is not bound to an instruction")(static_cast <bool> (Inst && "This slice is not bound to an instruction"
) ? void (0) : __assert_fail ("Inst && \"This slice is not bound to an instruction\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12002, __extension__ __PRETTY_FUNCTION__))
;
12003 assert(Inst->getValueSizeInBits(0) <= BitWidth &&(static_cast <bool> (Inst->getValueSizeInBits(0) <=
BitWidth && "Extracted slice is bigger than the whole type!"
) ? void (0) : __assert_fail ("Inst->getValueSizeInBits(0) <= BitWidth && \"Extracted slice is bigger than the whole type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12004, __extension__ __PRETTY_FUNCTION__))
12004 "Extracted slice is bigger than the whole type!")(static_cast <bool> (Inst->getValueSizeInBits(0) <=
BitWidth && "Extracted slice is bigger than the whole type!"
) ? void (0) : __assert_fail ("Inst->getValueSizeInBits(0) <= BitWidth && \"Extracted slice is bigger than the whole type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12004, __extension__ __PRETTY_FUNCTION__))
;
12005 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
12006 UsedBits.setAllBits();
12007 UsedBits = UsedBits.zext(BitWidth);
12008 UsedBits <<= Shift;
12009 return UsedBits;
12010 }
12011
12012 /// \brief Get the size of the slice to be loaded in bytes.
12013 unsigned getLoadedSize() const {
12014 unsigned SliceSize = getUsedBits().countPopulation();
12015 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.")(static_cast <bool> (!(SliceSize & 0x7) && "Size is not a multiple of a byte."
) ? void (0) : __assert_fail ("!(SliceSize & 0x7) && \"Size is not a multiple of a byte.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12015, __extension__ __PRETTY_FUNCTION__))
;
12016 return SliceSize / 8;
12017 }
12018
12019 /// \brief Get the type that will be loaded for this slice.
12020 /// Note: This may not be the final type for the slice.
12021 EVT getLoadedType() const {
12022 assert(DAG && "Missing context")(static_cast <bool> (DAG && "Missing context") ?
void (0) : __assert_fail ("DAG && \"Missing context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12022, __extension__ __PRETTY_FUNCTION__))
;
12023 LLVMContext &Ctxt = *DAG->getContext();
12024 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
12025 }
12026
12027 /// \brief Get the alignment of the load used for this slice.
12028 unsigned getAlignment() const {
12029 unsigned Alignment = Origin->getAlignment();
12030 unsigned Offset = getOffsetFromBase();
12031 if (Offset != 0)
12032 Alignment = MinAlign(Alignment, Alignment + Offset);
12033 return Alignment;
12034 }
12035
12036 /// \brief Check if this slice can be rewritten with legal operations.
12037 bool isLegal() const {
12038 // An invalid slice is not legal.
12039 if (!Origin || !Inst || !DAG)
12040 return false;
12041
12042 // Offsets are for indexed load only, we do not handle that.
12043 if (!Origin->getOffset().isUndef())
12044 return false;
12045
12046 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12047
12048 // Check that the type is legal.
12049 EVT SliceType = getLoadedType();
12050 if (!TLI.isTypeLegal(SliceType))
12051 return false;
12052
12053 // Check that the load is legal for this type.
12054 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
12055 return false;
12056
12057 // Check that the offset can be computed.
12058 // 1. Check its type.
12059 EVT PtrType = Origin->getBasePtr().getValueType();
12060 if (PtrType == MVT::Untyped || PtrType.isExtended())
12061 return false;
12062
12063 // 2. Check that it fits in the immediate.
12064 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12065 return false;
12066
12067 // 3. Check that the computation is legal.
12068 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12069 return false;
12070
12071 // Check that the zext is legal if it needs one.
12072 EVT TruncateType = Inst->getValueType(0);
12073 if (TruncateType != SliceType &&
12074 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12075 return false;
12076
12077 return true;
12078 }
12079
12080 /// \brief Get the offset in bytes of this slice in the original chunk of
12081 /// bits.
12082 /// \pre DAG != nullptr.
12083 uint64_t getOffsetFromBase() const {
12084 assert(DAG && "Missing context.")(static_cast <bool> (DAG && "Missing context.")
? void (0) : __assert_fail ("DAG && \"Missing context.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12084, __extension__ __PRETTY_FUNCTION__))
;
12085 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12086 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.")(static_cast <bool> (!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."
) ? void (0) : __assert_fail ("!(Shift & 0x7) && \"Shifts not aligned on Bytes are not supported.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12086, __extension__ __PRETTY_FUNCTION__))
;
12087 uint64_t Offset = Shift / 8;
12088 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12089 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&(static_cast <bool> (!(Origin->getValueSizeInBits(0)
& 0x7) && "The size of the original loaded type is not a multiple of a"
" byte.") ? void (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12091, __extension__ __PRETTY_FUNCTION__))
12090 "The size of the original loaded type is not a multiple of a"(static_cast <bool> (!(Origin->getValueSizeInBits(0)
& 0x7) && "The size of the original loaded type is not a multiple of a"
" byte.") ? void (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12091, __extension__ __PRETTY_FUNCTION__))
12091 " byte.")(static_cast <bool> (!(Origin->getValueSizeInBits(0)
& 0x7) && "The size of the original loaded type is not a multiple of a"
" byte.") ? void (0) : __assert_fail ("!(Origin->getValueSizeInBits(0) & 0x7) && \"The size of the original loaded type is not a multiple of a\" \" byte.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12091, __extension__ __PRETTY_FUNCTION__))
;
12092 // If Offset is bigger than TySizeInBytes, it means we are loading all
12093 // zeros. This should have been optimized before in the process.
12094 assert(TySizeInBytes > Offset &&(static_cast <bool> (TySizeInBytes > Offset &&
"Invalid shift amount for given loaded size") ? void (0) : __assert_fail
("TySizeInBytes > Offset && \"Invalid shift amount for given loaded size\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12095, __extension__ __PRETTY_FUNCTION__))
12095 "Invalid shift amount for given loaded size")(static_cast <bool> (TySizeInBytes > Offset &&
"Invalid shift amount for given loaded size") ? void (0) : __assert_fail
("TySizeInBytes > Offset && \"Invalid shift amount for given loaded size\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12095, __extension__ __PRETTY_FUNCTION__))
;
12096 if (IsBigEndian)
12097 Offset = TySizeInBytes - Offset - getLoadedSize();
12098 return Offset;
12099 }
12100
12101 /// \brief Generate the sequence of instructions to load the slice
12102 /// represented by this object and redirect the uses of this slice to
12103 /// this new sequence of instructions.
12104 /// \pre this->Inst && this->Origin are valid Instructions and this
12105 /// object passed the legal check: LoadedSlice::isLegal returned true.
12106 /// \return The last instruction of the sequence used to load the slice.
12107 SDValue loadSlice() const {
12108 assert(Inst && Origin && "Unable to replace a non-existing slice.")(static_cast <bool> (Inst && Origin && "Unable to replace a non-existing slice."
) ? void (0) : __assert_fail ("Inst && Origin && \"Unable to replace a non-existing slice.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12108, __extension__ __PRETTY_FUNCTION__))
;
12109 const SDValue &OldBaseAddr = Origin->getBasePtr();
12110 SDValue BaseAddr = OldBaseAddr;
12111 // Get the offset in that chunk of bytes w.r.t. the endianness.
12112 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12113 assert(Offset >= 0 && "Offset too big to fit in int64_t!")(static_cast <bool> (Offset >= 0 && "Offset too big to fit in int64_t!"
) ? void (0) : __assert_fail ("Offset >= 0 && \"Offset too big to fit in int64_t!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12113, __extension__ __PRETTY_FUNCTION__))
;
12114 if (Offset) {
12115 // BaseAddr = BaseAddr + Offset.
12116 EVT ArithType = BaseAddr.getValueType();
12117 SDLoc DL(Origin);
12118 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12119 DAG->getConstant(Offset, DL, ArithType));
12120 }
12121
12122 // Create the type of the loaded slice according to its size.
12123 EVT SliceType = getLoadedType();
12124
12125 // Create the load for the slice.
12126 SDValue LastInst =
12127 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12128 Origin->getPointerInfo().getWithOffset(Offset),
12129 getAlignment(), Origin->getMemOperand()->getFlags());
12130 // If the final type is not the same as the loaded type, this means that
12131 // we have to pad with zero. Create a zero extend for that.
12132 EVT FinalType = Inst->getValueType(0);
12133 if (SliceType != FinalType)
12134 LastInst =
12135 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12136 return LastInst;
12137 }
12138
12139 /// \brief Check if this slice can be merged with an expensive cross register
12140 /// bank copy. E.g.,
12141 /// i = load i32
12142 /// f = bitcast i32 i to float
12143 bool canMergeExpensiveCrossRegisterBankCopy() const {
12144 if (!Inst || !Inst->hasOneUse())
12145 return false;
12146 SDNode *Use = *Inst->use_begin();
12147 if (Use->getOpcode() != ISD::BITCAST)
12148 return false;
12149 assert(DAG && "Missing context")(static_cast <bool> (DAG && "Missing context") ?
void (0) : __assert_fail ("DAG && \"Missing context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12149, __extension__ __PRETTY_FUNCTION__))
;
12150 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12151 EVT ResVT = Use->getValueType(0);
12152 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12153 const TargetRegisterClass *ArgRC =
12154 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12155 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12156 return false;
12157
12158 // At this point, we know that we perform a cross-register-bank copy.
12159 // Check if it is expensive.
12160 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12161 // Assume bitcasts are cheap, unless both register classes do not
12162 // explicitly share a common sub class.
12163 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12164 return false;
12165
12166 // Check if it will be merged with the load.
12167 // 1. Check the alignment constraint.
12168 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12169 ResVT.getTypeForEVT(*DAG->getContext()));
12170
12171 if (RequiredAlignment > getAlignment())
12172 return false;
12173
12174 // 2. Check that the load is a legal operation for that type.
12175 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12176 return false;
12177
12178 // 3. Check that we do not have a zext in the way.
12179 if (Inst->getValueType(0) != getLoadedType())
12180 return false;
12181
12182 return true;
12183 }
12184};
12185
12186} // end anonymous namespace
12187
12188/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
12189/// \p UsedBits looks like 0..0 1..1 0..0.
12190static bool areUsedBitsDense(const APInt &UsedBits) {
12191 // If all the bits are one, this is dense!
12192 if (UsedBits.isAllOnesValue())
12193 return true;
12194
12195 // Get rid of the unused bits on the right.
12196 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12197 // Get rid of the unused bits on the left.
12198 if (NarrowedUsedBits.countLeadingZeros())
12199 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12200 // Check that the chunk of bits is completely used.
12201 return NarrowedUsedBits.isAllOnesValue();
12202}
12203
12204/// \brief Check whether or not \p First and \p Second are next to each other
12205/// in memory. This means that there is no hole between the bits loaded
12206/// by \p First and the bits loaded by \p Second.
12207static bool areSlicesNextToEachOther(const LoadedSlice &First,
12208 const LoadedSlice &Second) {
12209 assert(First.Origin == Second.Origin && First.Origin &&(static_cast <bool> (First.Origin == Second.Origin &&
First.Origin && "Unable to match different memory origins."
) ? void (0) : __assert_fail ("First.Origin == Second.Origin && First.Origin && \"Unable to match different memory origins.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12210, __extension__ __PRETTY_FUNCTION__))
12210 "Unable to match different memory origins.")(static_cast <bool> (First.Origin == Second.Origin &&
First.Origin && "Unable to match different memory origins."
) ? void (0) : __assert_fail ("First.Origin == Second.Origin && First.Origin && \"Unable to match different memory origins.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12210, __extension__ __PRETTY_FUNCTION__))
;
12211 APInt UsedBits = First.getUsedBits();
12212 assert((UsedBits & Second.getUsedBits()) == 0 &&(static_cast <bool> ((UsedBits & Second.getUsedBits
()) == 0 && "Slices are not supposed to overlap.") ? void
(0) : __assert_fail ("(UsedBits & Second.getUsedBits()) == 0 && \"Slices are not supposed to overlap.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12213, __extension__ __PRETTY_FUNCTION__))
12213 "Slices are not supposed to overlap.")(static_cast <bool> ((UsedBits & Second.getUsedBits
()) == 0 && "Slices are not supposed to overlap.") ? void
(0) : __assert_fail ("(UsedBits & Second.getUsedBits()) == 0 && \"Slices are not supposed to overlap.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12213, __extension__ __PRETTY_FUNCTION__))
;
12214 UsedBits |= Second.getUsedBits();
12215 return areUsedBitsDense(UsedBits);
12216}
12217
12218/// \brief Adjust the \p GlobalLSCost according to the target
12219/// paring capabilities and the layout of the slices.
12220/// \pre \p GlobalLSCost should account for at least as many loads as
12221/// there is in the slices in \p LoadedSlices.
12222static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12223 LoadedSlice::Cost &GlobalLSCost) {
12224 unsigned NumberOfSlices = LoadedSlices.size();
12225 // If there is less than 2 elements, no pairing is possible.
12226 if (NumberOfSlices < 2)
12227 return;
12228
12229 // Sort the slices so that elements that are likely to be next to each
12230 // other in memory are next to each other in the list.
12231 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
12232 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12233 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.")(static_cast <bool> (LHS.Origin == RHS.Origin &&
"Different bases not implemented.") ? void (0) : __assert_fail
("LHS.Origin == RHS.Origin && \"Different bases not implemented.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12233, __extension__ __PRETTY_FUNCTION__))
;
12234 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12235 });
12236 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12237 // First (resp. Second) is the first (resp. Second) potentially candidate
12238 // to be placed in a paired load.
12239 const LoadedSlice *First = nullptr;
12240 const LoadedSlice *Second = nullptr;
12241 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12242 // Set the beginning of the pair.
12243 First = Second) {
12244 Second = &LoadedSlices[CurrSlice];
12245
12246 // If First is NULL, it means we start a new pair.
12247 // Get to the next slice.
12248 if (!First)
12249 continue;
12250
12251 EVT LoadedType = First->getLoadedType();
12252
12253 // If the types of the slices are different, we cannot pair them.
12254 if (LoadedType != Second->getLoadedType())
12255 continue;
12256
12257 // Check if the target supplies paired loads for this type.
12258 unsigned RequiredAlignment = 0;
12259 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12260 // move to the next pair, this type is hopeless.
12261 Second = nullptr;
12262 continue;
12263 }
12264 // Check if we meet the alignment requirement.
12265 if (RequiredAlignment > First->getAlignment())
12266 continue;
12267
12268 // Check that both loads are next to each other in memory.
12269 if (!areSlicesNextToEachOther(*First, *Second))
12270 continue;
12271
12272 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!")(static_cast <bool> (GlobalLSCost.Loads > 0 &&
"We save more loads than we created!") ? void (0) : __assert_fail
("GlobalLSCost.Loads > 0 && \"We save more loads than we created!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12272, __extension__ __PRETTY_FUNCTION__))
;
12273 --GlobalLSCost.Loads;
12274 // Move to the next pair.
12275 Second = nullptr;
12276 }
12277}
12278
12279/// \brief Check the profitability of all involved LoadedSlice.
12280/// Currently, it is considered profitable if there is exactly two
12281/// involved slices (1) which are (2) next to each other in memory, and
12282/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12283///
12284/// Note: The order of the elements in \p LoadedSlices may be modified, but not
12285/// the elements themselves.
12286///
12287/// FIXME: When the cost model will be mature enough, we can relax
12288/// constraints (1) and (2).
12289static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12290 const APInt &UsedBits, bool ForCodeSize) {
12291 unsigned NumberOfSlices = LoadedSlices.size();
12292 if (StressLoadSlicing)
12293 return NumberOfSlices > 1;
12294
12295 // Check (1).
12296 if (NumberOfSlices != 2)
12297 return false;
12298
12299 // Check (2).
12300 if (!areUsedBitsDense(UsedBits))
12301 return false;
12302
12303 // Check (3).
12304 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12305 // The original code has one big load.
12306 OrigCost.Loads = 1;
12307 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12308 const LoadedSlice &LS = LoadedSlices[CurrSlice];
12309 // Accumulate the cost of all the slices.
12310 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12311 GlobalSlicingCost += SliceCost;
12312
12313 // Account as cost in the original configuration the gain obtained
12314 // with the current slices.
12315 OrigCost.addSliceGain(LS);
12316 }
12317
12318 // If the target supports paired load, adjust the cost accordingly.
12319 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12320 return OrigCost > GlobalSlicingCost;
12321}
12322
12323/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12324/// operations, split it in the various pieces being extracted.
12325///
12326/// This sort of thing is introduced by SROA.
12327/// This slicing takes care not to insert overlapping loads.
12328/// \pre LI is a simple load (i.e., not an atomic or volatile load).
12329bool DAGCombiner::SliceUpLoad(SDNode *N) {
12330 if (Level < AfterLegalizeDAG)
12331 return false;
12332
12333 LoadSDNode *LD = cast<LoadSDNode>(N);
12334 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12335 !LD->getValueType(0).isInteger())
12336 return false;
12337
12338 // Keep track of already used bits to detect overlapping values.
12339 // In that case, we will just abort the transformation.
12340 APInt UsedBits(LD->getValueSizeInBits(0), 0);
12341
12342 SmallVector<LoadedSlice, 4> LoadedSlices;
12343
12344 // Check if this load is used as several smaller chunks of bits.
12345 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12346 // of computation for each trunc.
12347 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12348 UI != UIEnd; ++UI) {
12349 // Skip the uses of the chain.
12350 if (UI.getUse().getResNo() != 0)
12351 continue;
12352
12353 SDNode *User = *UI;
12354 unsigned Shift = 0;
12355
12356 // Check if this is a trunc(lshr).
12357 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12358 isa<ConstantSDNode>(User->getOperand(1))) {
12359 Shift = User->getConstantOperandVal(1);
12360 User = *User->use_begin();
12361 }
12362
12363 // At this point, User is a Truncate, iff we encountered, trunc or
12364 // trunc(lshr).
12365 if (User->getOpcode() != ISD::TRUNCATE)
12366 return false;
12367
12368 // The width of the type must be a power of 2 and greater than 8-bits.
12369 // Otherwise the load cannot be represented in LLVM IR.
12370 // Moreover, if we shifted with a non-8-bits multiple, the slice
12371 // will be across several bytes. We do not support that.
12372 unsigned Width = User->getValueSizeInBits(0);
12373 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12374 return false;
12375
12376 // Build the slice for this chain of computations.
12377 LoadedSlice LS(User, LD, Shift, &DAG);
12378 APInt CurrentUsedBits = LS.getUsedBits();
12379
12380 // Check if this slice overlaps with another.
12381 if ((CurrentUsedBits & UsedBits) != 0)
12382 return false;
12383 // Update the bits used globally.
12384 UsedBits |= CurrentUsedBits;
12385
12386 // Check if the new slice would be legal.
12387 if (!LS.isLegal())
12388 return false;
12389
12390 // Record the slice.
12391 LoadedSlices.push_back(LS);
12392 }
12393
12394 // Abort slicing if it does not seem to be profitable.
12395 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12396 return false;
12397
12398 ++SlicedLoads;
12399
12400 // Rewrite each chain to use an independent load.
12401 // By construction, each chain can be represented by a unique load.
12402
12403 // Prepare the argument for the new token factor for all the slices.
12404 SmallVector<SDValue, 8> ArgChains;
12405 for (SmallVectorImpl<LoadedSlice>::const_iterator
12406 LSIt = LoadedSlices.begin(),
12407 LSItEnd = LoadedSlices.end();
12408 LSIt != LSItEnd; ++LSIt) {
12409 SDValue SliceInst = LSIt->loadSlice();
12410 CombineTo(LSIt->Inst, SliceInst, true);
12411 if (SliceInst.getOpcode() != ISD::LOAD)
12412 SliceInst = SliceInst.getOperand(0);
12413 assert(SliceInst->getOpcode() == ISD::LOAD &&(static_cast <bool> (SliceInst->getOpcode() == ISD::
LOAD && "It takes more than a zext to get to the loaded slice!!"
) ? void (0) : __assert_fail ("SliceInst->getOpcode() == ISD::LOAD && \"It takes more than a zext to get to the loaded slice!!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12414, __extension__ __PRETTY_FUNCTION__))
12414 "It takes more than a zext to get to the loaded slice!!")(static_cast <bool> (SliceInst->getOpcode() == ISD::
LOAD && "It takes more than a zext to get to the loaded slice!!"
) ? void (0) : __assert_fail ("SliceInst->getOpcode() == ISD::LOAD && \"It takes more than a zext to get to the loaded slice!!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12414, __extension__ __PRETTY_FUNCTION__))
;
12415 ArgChains.push_back(SliceInst.getValue(1));
12416 }
12417
12418 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12419 ArgChains);
12420 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12421 AddToWorklist(Chain.getNode());
12422 return true;
12423}
12424
12425/// Check to see if V is (and load (ptr), imm), where the load is having
12426/// specific bytes cleared out. If so, return the byte size being masked out
12427/// and the shift amount.
12428static std::pair<unsigned, unsigned>
12429CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12430 std::pair<unsigned, unsigned> Result(0, 0);
12431
12432 // Check for the structure we're looking for.
12433 if (V->getOpcode() != ISD::AND ||
12434 !isa<ConstantSDNode>(V->getOperand(1)) ||
12435 !ISD::isNormalLoad(V->getOperand(0).getNode()))
12436 return Result;
12437
12438 // Check the chain and pointer.
12439 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12440 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
12441
12442 // The store should be chained directly to the load or be an operand of a
12443 // tokenfactor.
12444 if (LD == Chain.getNode())
12445 ; // ok.
12446 else if (Chain->getOpcode() != ISD::TokenFactor)
12447 return Result; // Fail.
12448 else {
12449 bool isOk = false;
12450 for (const SDValue &ChainOp : Chain->op_values())
12451 if (ChainOp.getNode() == LD) {
12452 isOk = true;
12453 break;
12454 }
12455 if (!isOk) return Result;
12456 }
12457
12458 // This only handles simple types.
12459 if (V.getValueType() != MVT::i16 &&
12460 V.getValueType() != MVT::i32 &&
12461 V.getValueType() != MVT::i64)
12462 return Result;
12463
12464 // Check the constant mask. Invert it so that the bits being masked out are
12465 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
12466 // follow the sign bit for uniformity.
12467 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12468 unsigned NotMaskLZ = countLeadingZeros(NotMask);
12469 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
12470 unsigned NotMaskTZ = countTrailingZeros(NotMask);
12471 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
12472 if (NotMaskLZ == 64) return Result; // All zero mask.
12473
12474 // See if we have a continuous run of bits. If so, we have 0*1+0*
12475 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12476 return Result;
12477
12478 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12479 if (V.getValueType() != MVT::i64 && NotMaskLZ)
12480 NotMaskLZ -= 64-V.getValueSizeInBits();
12481
12482 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12483 switch (MaskedBytes) {
12484 case 1:
12485 case 2:
12486 case 4: break;
12487 default: return Result; // All one mask, or 5-byte mask.
12488 }
12489
12490 // Verify that the first bit starts at a multiple of mask so that the access
12491 // is aligned the same as the access width.
12492 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12493
12494 Result.first = MaskedBytes;
12495 Result.second = NotMaskTZ/8;
12496 return Result;
12497}
12498
12499/// Check to see if IVal is something that provides a value as specified by
12500/// MaskInfo. If so, replace the specified store with a narrower store of
12501/// truncated IVal.
12502static SDNode *
12503ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12504 SDValue IVal, StoreSDNode *St,
12505 DAGCombiner *DC) {
12506 unsigned NumBytes = MaskInfo.first;
12507 unsigned ByteShift = MaskInfo.second;
12508 SelectionDAG &DAG = DC->getDAG();
12509
12510 // Check to see if IVal is all zeros in the part being masked in by the 'or'
12511 // that uses this. If not, this is not a replacement.
12512 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12513 ByteShift*8, (ByteShift+NumBytes)*8);
12514 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12515
12516 // Check that it is legal on the target to do this. It is legal if the new
12517 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12518 // legalization.
12519 MVT VT = MVT::getIntegerVT(NumBytes*8);
12520 if (!DC->isTypeLegal(VT))
12521 return nullptr;
12522
12523 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
12524 // shifted by ByteShift and truncated down to NumBytes.
12525 if (ByteShift) {
12526 SDLoc DL(IVal);
12527 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12528 DAG.getConstant(ByteShift*8, DL,
12529 DC->getShiftAmountTy(IVal.getValueType())));
12530 }
12531
12532 // Figure out the offset for the store and the alignment of the access.
12533 unsigned StOffset;
12534 unsigned NewAlign = St->getAlignment();
12535
12536 if (DAG.getDataLayout().isLittleEndian())
12537 StOffset = ByteShift;
12538 else
12539 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12540
12541 SDValue Ptr = St->getBasePtr();
12542 if (StOffset) {
12543 SDLoc DL(IVal);
12544 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12545 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12546 NewAlign = MinAlign(NewAlign, StOffset);
12547 }
12548
12549 // Truncate down to the new size.
12550 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12551
12552 ++OpsNarrowed;
12553 return DAG
12554 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12555 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12556 .getNode();
12557}
12558
12559/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12560/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12561/// narrowing the load and store if it would end up being a win for performance
12562/// or code size.
12563SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12564 StoreSDNode *ST = cast<StoreSDNode>(N);
12565 if (ST->isVolatile())
12566 return SDValue();
12567
12568 SDValue Chain = ST->getChain();
12569 SDValue Value = ST->getValue();
12570 SDValue Ptr = ST->getBasePtr();
12571 EVT VT = Value.getValueType();
12572
12573 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12574 return SDValue();
12575
12576 unsigned Opc = Value.getOpcode();
12577
12578 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12579 // is a byte mask indicating a consecutive number of bytes, check to see if
12580 // Y is known to provide just those bytes. If so, we try to replace the
12581 // load + replace + store sequence with a single (narrower) store, which makes
12582 // the load dead.
12583 if (Opc == ISD::OR) {
12584 std::pair<unsigned, unsigned> MaskedLoad;
12585 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12586 if (MaskedLoad.first)
12587 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12588 Value.getOperand(1), ST,this))
12589 return SDValue(NewST, 0);
12590
12591 // Or is commutative, so try swapping X and Y.
12592 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12593 if (MaskedLoad.first)
12594 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12595 Value.getOperand(0), ST,this))
12596 return SDValue(NewST, 0);
12597 }
12598
12599 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12600 Value.getOperand(1).getOpcode() != ISD::Constant)
12601 return SDValue();
12602
12603 SDValue N0 = Value.getOperand(0);
12604 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12605 Chain == SDValue(N0.getNode(), 1)) {
12606 LoadSDNode *LD = cast<LoadSDNode>(N0);
12607 if (LD->getBasePtr() != Ptr ||
12608 LD->getPointerInfo().getAddrSpace() !=
12609 ST->getPointerInfo().getAddrSpace())
12610 return SDValue();
12611
12612 // Find the type to narrow it the load / op / store to.
12613 SDValue N1 = Value.getOperand(1);
12614 unsigned BitWidth = N1.getValueSizeInBits();
12615 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12616 if (Opc == ISD::AND)
12617 Imm ^= APInt::getAllOnesValue(BitWidth);
12618 if (Imm == 0 || Imm.isAllOnesValue())
12619 return SDValue();
12620 unsigned ShAmt = Imm.countTrailingZeros();
12621 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12622 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12623 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12624 // The narrowing should be profitable, the load/store operation should be
12625 // legal (or custom) and the store size should be equal to the NewVT width.
12626 while (NewBW < BitWidth &&
12627 (NewVT.getStoreSizeInBits() != NewBW ||
12628 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12629 !TLI.isNarrowingProfitable(VT, NewVT))) {
12630 NewBW = NextPowerOf2(NewBW);
12631 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12632 }
12633 if (NewBW >= BitWidth)
12634 return SDValue();
12635
12636 // If the lsb changed does not start at the type bitwidth boundary,
12637 // start at the previous one.
12638 if (ShAmt % NewBW)
12639 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12640 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12641 std::min(BitWidth, ShAmt + NewBW));
12642 if ((Imm & Mask) == Imm) {
12643 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12644 if (Opc == ISD::AND)
12645 NewImm ^= APInt::getAllOnesValue(NewBW);
12646 uint64_t PtrOff = ShAmt / 8;
12647 // For big endian targets, we need to adjust the offset to the pointer to
12648 // load the correct bytes.
12649 if (DAG.getDataLayout().isBigEndian())
12650 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12651
12652 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12653 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12654 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12655 return SDValue();
12656
12657 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12658 Ptr.getValueType(), Ptr,
12659 DAG.getConstant(PtrOff, SDLoc(LD),
12660 Ptr.getValueType()));
12661 SDValue NewLD =
12662 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12663 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12664 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12665 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12666 DAG.getConstant(NewImm, SDLoc(Value),
12667 NewVT));
12668 SDValue NewST =
12669 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12670 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12671
12672 AddToWorklist(NewPtr.getNode());
12673 AddToWorklist(NewLD.getNode());
12674 AddToWorklist(NewVal.getNode());
12675 WorklistRemover DeadNodes(*this);
12676 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12677 ++OpsNarrowed;
12678 return NewST;
12679 }
12680 }
12681
12682 return SDValue();
12683}
12684
12685/// For a given floating point load / store pair, if the load value isn't used
12686/// by any other operations, then consider transforming the pair to integer
12687/// load / store operations if the target deems the transformation profitable.
12688SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12689 StoreSDNode *ST = cast<StoreSDNode>(N);
12690 SDValue Chain = ST->getChain();
12691 SDValue Value = ST->getValue();
12692 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12693 Value.hasOneUse() &&
12694 Chain == SDValue(Value.getNode(), 1)) {
12695 LoadSDNode *LD = cast<LoadSDNode>(Value);
12696 EVT VT = LD->getMemoryVT();
12697 if (!VT.isFloatingPoint() ||
12698 VT != ST->getMemoryVT() ||
12699 LD->isNonTemporal() ||
12700 ST->isNonTemporal() ||
12701 LD->getPointerInfo().getAddrSpace() != 0 ||
12702 ST->getPointerInfo().getAddrSpace() != 0)
12703 return SDValue();
12704
12705 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12706 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12707 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12708 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12709 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12710 return SDValue();
12711
12712 unsigned LDAlign = LD->getAlignment();
12713 unsigned STAlign = ST->getAlignment();
12714 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12715 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12716 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12717 return SDValue();
12718
12719 SDValue NewLD =
12720 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12721 LD->getPointerInfo(), LDAlign);
12722
12723 SDValue NewST =
12724 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12725 ST->getPointerInfo(), STAlign);
12726
12727 AddToWorklist(NewLD.getNode());
12728 AddToWorklist(NewST.getNode());
12729 WorklistRemover DeadNodes(*this);
12730 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12731 ++LdStFP2Int;
12732 return NewST;
12733 }
12734
12735 return SDValue();
12736}
12737
12738// This is a helper function for visitMUL to check the profitability
12739// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12740// MulNode is the original multiply, AddNode is (add x, c1),
12741// and ConstNode is c2.
12742//
12743// If the (add x, c1) has multiple uses, we could increase
12744// the number of adds if we make this transformation.
12745// It would only be worth doing this if we can remove a
12746// multiply in the process. Check for that here.
12747// To illustrate:
12748// (A + c1) * c3
12749// (A + c2) * c3
12750// We're checking for cases where we have common "c3 * A" expressions.
12751bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12752 SDValue &AddNode,
12753 SDValue &ConstNode) {
12754 APInt Val;
12755
12756 // If the add only has one use, this would be OK to do.
12757 if (AddNode.getNode()->hasOneUse())
12758 return true;
12759
12760 // Walk all the users of the constant with which we're multiplying.
12761 for (SDNode *Use : ConstNode->uses()) {
12762 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12763 continue;
12764
12765 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12766 SDNode *OtherOp;
12767 SDNode *MulVar = AddNode.getOperand(0).getNode();
12768
12769 // OtherOp is what we're multiplying against the constant.
12770 if (Use->getOperand(0) == ConstNode)
12771 OtherOp = Use->getOperand(1).getNode();
12772 else
12773 OtherOp = Use->getOperand(0).getNode();
12774
12775 // Check to see if multiply is with the same operand of our "add".
12776 //
12777 // ConstNode = CONST
12778 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12779 // ...
12780 // AddNode = (A + c1) <-- MulVar is A.
12781 // = AddNode * ConstNode <-- current visiting instruction.
12782 //
12783 // If we make this transformation, we will have a common
12784 // multiply (ConstNode * A) that we can save.
12785 if (OtherOp == MulVar)
12786 return true;
12787
12788 // Now check to see if a future expansion will give us a common
12789 // multiply.
12790 //
12791 // ConstNode = CONST
12792 // AddNode = (A + c1)
12793 // ... = AddNode * ConstNode <-- current visiting instruction.
12794 // ...
12795 // OtherOp = (A + c2)
12796 // Use = OtherOp * ConstNode <-- visiting Use.
12797 //
12798 // If we make this transformation, we will have a common
12799 // multiply (CONST * A) after we also do the same transformation
12800 // to the "t2" instruction.
12801 if (OtherOp->getOpcode() == ISD::ADD &&
12802 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12803 OtherOp->getOperand(0).getNode() == MulVar)
12804 return true;
12805 }
12806 }
12807
12808 // Didn't find a case where this would be profitable.
12809 return false;
12810}
12811
12812static SDValue peekThroughBitcast(SDValue V) {
12813 while (V.getOpcode() == ISD::BITCAST)
12814 V = V.getOperand(0);
12815 return V;
12816}
12817
12818SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12819 unsigned NumStores) {
12820 SmallVector<SDValue, 8> Chains;
12821 SmallPtrSet<const SDNode *, 8> Visited;
12822 SDLoc StoreDL(StoreNodes[0].MemNode);
12823
12824 for (unsigned i = 0; i < NumStores; ++i) {
12825 Visited.insert(StoreNodes[i].MemNode);
12826 }
12827
12828 // don't include nodes that are children
12829 for (unsigned i = 0; i < NumStores; ++i) {
12830 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12831 Chains.push_back(StoreNodes[i].MemNode->getChain());
12832 }
12833
12834 assert(Chains.size() > 0 && "Chain should have generated a chain")(static_cast <bool> (Chains.size() > 0 && "Chain should have generated a chain"
) ? void (0) : __assert_fail ("Chains.size() > 0 && \"Chain should have generated a chain\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12834, __extension__ __PRETTY_FUNCTION__))
;
12835 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12836}
12837
12838bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12839 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12840 bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12841 // Make sure we have something to merge.
12842 if (NumStores < 2)
12843 return false;
12844
12845 // The latest Node in the DAG.
12846 SDLoc DL(StoreNodes[0].MemNode);
12847
12848 int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
12849 unsigned SizeInBits = NumStores * ElementSizeBits;
12850 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12851
12852 EVT StoreTy;
12853 if (UseVector) {
12854 unsigned Elts = NumStores * NumMemElts;
12855 // Get the type for the merged vector store.
12856 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12857 } else
12858 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12859
12860 SDValue StoredVal;
12861 if (UseVector) {
12862 if (IsConstantSrc) {
12863 SmallVector<SDValue, 8> BuildVector;
12864 for (unsigned I = 0; I != NumStores; ++I) {
12865 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12866 SDValue Val = St->getValue();
12867 // If constant is of the wrong type, convert it now.
12868 if (MemVT != Val.getValueType()) {
12869 Val = peekThroughBitcast(Val);
12870 // Deal with constants of wrong size.
12871 if (ElementSizeBits != Val.getValueSizeInBits()) {
12872 EVT IntMemVT =
12873 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12874 if (isa<ConstantFPSDNode>(Val)) {
12875 // Not clear how to truncate FP values.
12876 return false;
12877 } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12878 Val = DAG.getConstant(C->getAPIntValue()
12879 .zextOrTrunc(Val.getValueSizeInBits())
12880 .zextOrTrunc(ElementSizeBits),
12881 SDLoc(C), IntMemVT);
12882 }
12883 // Make sure correctly size type is the correct type.
12884 Val = DAG.getBitcast(MemVT, Val);
12885 }
12886 BuildVector.push_back(Val);
12887 }
12888 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12889 : ISD::BUILD_VECTOR,
12890 DL, StoreTy, BuildVector);
12891 } else {
12892 SmallVector<SDValue, 8> Ops;
12893 for (unsigned i = 0; i < NumStores; ++i) {
12894 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12895 SDValue Val = peekThroughBitcast(St->getValue());
12896 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12897 // type MemVT. If the underlying value is not the correct
12898 // type, but it is an extraction of an appropriate vector we
12899 // can recast Val to be of the correct type. This may require
12900 // converting between EXTRACT_VECTOR_ELT and
12901 // EXTRACT_SUBVECTOR.
12902 if ((MemVT != Val.getValueType()) &&
12903 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12904 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12905 SDValue Vec = Val.getOperand(0);
12906 EVT MemVTScalarTy = MemVT.getScalarType();
12907 // We may need to add a bitcast here to get types to line up.
12908 if (MemVTScalarTy != Vec.getValueType()) {
12909 unsigned Elts = Vec.getValueType().getSizeInBits() /
12910 MemVTScalarTy.getSizeInBits();
12911 EVT NewVecTy =
12912 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12913 Vec = DAG.getBitcast(NewVecTy, Vec);
12914 }
12915 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12916 : ISD::EXTRACT_VECTOR_ELT;
12917 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12918 }
12919 Ops.push_back(Val);
12920 }
12921
12922 // Build the extracted vector elements back into a vector.
12923 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12924 : ISD::BUILD_VECTOR,
12925 DL, StoreTy, Ops);
12926 }
12927 } else {
12928 // We should always use a vector store when merging extracted vector
12929 // elements, so this path implies a store of constants.
12930 assert(IsConstantSrc && "Merged vector elements should use vector store")(static_cast <bool> (IsConstantSrc && "Merged vector elements should use vector store"
) ? void (0) : __assert_fail ("IsConstantSrc && \"Merged vector elements should use vector store\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12930, __extension__ __PRETTY_FUNCTION__))
;
12931
12932 APInt StoreInt(SizeInBits, 0);
12933
12934 // Construct a single integer constant which is made of the smaller
12935 // constant inputs.
12936 bool IsLE = DAG.getDataLayout().isLittleEndian();
12937 for (unsigned i = 0; i < NumStores; ++i) {
12938 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12939 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12940
12941 SDValue Val = St->getValue();
12942 StoreInt <<= ElementSizeBits;
12943 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12944 StoreInt |= C->getAPIntValue()
12945 .zextOrTrunc(ElementSizeBits)
12946 .zextOrTrunc(SizeInBits);
12947 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12948 StoreInt |= C->getValueAPF()
12949 .bitcastToAPInt()
12950 .zextOrTrunc(ElementSizeBits)
12951 .zextOrTrunc(SizeInBits);
12952 // If fp truncation is necessary give up for now.
12953 if (MemVT.getSizeInBits() != ElementSizeBits)
12954 return false;
12955 } else {
12956 llvm_unreachable("Invalid constant element type")::llvm::llvm_unreachable_internal("Invalid constant element type"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 12956)
;
12957 }
12958 }
12959
12960 // Create the new Load and Store operations.
12961 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12962 }
12963
12964 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12965 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12966
12967 // make sure we use trunc store if it's necessary to be legal.
12968 SDValue NewStore;
12969 if (!UseTrunc) {
12970 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12971 FirstInChain->getPointerInfo(),
12972 FirstInChain->getAlignment());
12973 } else { // Must be realized as a trunc store
12974 EVT LegalizedStoredValueTy =
12975 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12976 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12977 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12978 SDValue ExtendedStoreVal =
12979 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12980 LegalizedStoredValueTy);
12981 NewStore = DAG.getTruncStore(
12982 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12983 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12984 FirstInChain->getAlignment(),
12985 FirstInChain->getMemOperand()->getFlags());
12986 }
12987
12988 // Replace all merged stores with the new store.
12989 for (unsigned i = 0; i < NumStores; ++i)
12990 CombineTo(StoreNodes[i].MemNode, NewStore);
12991
12992 AddToWorklist(NewChain.getNode());
12993 return true;
12994}
12995
12996void DAGCombiner::getStoreMergeCandidates(
12997 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12998 // This holds the base pointer, index, and the offset in bytes from the base
12999 // pointer.
13000 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
13001 EVT MemVT = St->getMemoryVT();
13002
13003 SDValue Val = peekThroughBitcast(St->getValue());
13004 // We must have a base and an offset.
13005 if (!BasePtr.getBase().getNode())
13006 return;
13007
13008 // Do not handle stores to undef base pointers.
13009 if (BasePtr.getBase().isUndef())
13010 return;
13011
13012 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
13013 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13014 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13015 bool IsLoadSrc = isa<LoadSDNode>(Val);
13016 BaseIndexOffset LBasePtr;
13017 // Match on loadbaseptr if relevant.
13018 EVT LoadVT;
13019 if (IsLoadSrc) {
13020 auto *Ld = cast<LoadSDNode>(Val);
13021 LBasePtr = BaseIndexOffset::match(Ld, DAG);
13022 LoadVT = Ld->getMemoryVT();
13023 // Load and store should be the same type.
13024 if (MemVT != LoadVT)
13025 return;
13026 }
13027 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
13028 int64_t &Offset) -> bool {
13029 if (Other->isVolatile() || Other->isIndexed())
13030 return false;
13031 SDValue Val = peekThroughBitcast(Other->getValue());
13032 // Allow merging constants of different types as integers.
13033 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
13034 : Other->getMemoryVT() != MemVT;
13035 if (IsLoadSrc) {
13036 if (NoTypeMatch)
13037 return false;
13038 // The Load's Base Ptr must also match
13039 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
13040 auto LPtr = BaseIndexOffset::match(OtherLd, DAG);
13041 if (LoadVT != OtherLd->getMemoryVT())
13042 return false;
13043 if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
13044 return false;
13045 } else
13046 return false;
13047 }
13048 if (IsConstantSrc) {
13049 if (NoTypeMatch)
13050 return false;
13051 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
13052 return false;
13053 }
13054 if (IsExtractVecSrc) {
13055 // Do not merge truncated stores here.
13056 if (Other->isTruncatingStore())
13057 return false;
13058 if (!MemVT.bitsEq(Val.getValueType()))
13059 return false;
13060 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13061 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13062 return false;
13063 }
13064 Ptr = BaseIndexOffset::match(Other, DAG);
13065 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13066 };
13067
13068 // We looking for a root node which is an ancestor to all mergable
13069 // stores. We search up through a load, to our root and then down
13070 // through all children. For instance we will find Store{1,2,3} if
13071 // St is Store1, Store2. or Store3 where the root is not a load
13072 // which always true for nonvolatile ops. TODO: Expand
13073 // the search to find all valid candidates through multiple layers of loads.
13074 //
13075 // Root
13076 // |-------|-------|
13077 // Load Load Store3
13078 // | |
13079 // Store1 Store2
13080 //
13081 // FIXME: We should be able to climb and
13082 // descend TokenFactors to find candidates as well.
13083
13084 SDNode *RootNode = (St->getChain()).getNode();
13085
13086 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13087 RootNode = Ldn->getChain().getNode();
13088 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13089 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13090 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13091 if (I2.getOperandNo() == 0)
13092 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13093 BaseIndexOffset Ptr;
13094 int64_t PtrDiff;
13095 if (CandidateMatch(OtherST, Ptr, PtrDiff))
13096 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13097 }
13098 } else
13099 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13100 if (I.getOperandNo() == 0)
13101 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13102 BaseIndexOffset Ptr;
13103 int64_t PtrDiff;
13104 if (CandidateMatch(OtherST, Ptr, PtrDiff))
13105 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13106 }
13107}
13108
13109// We need to check that merging these stores does not cause a loop in
13110// the DAG. Any store candidate may depend on another candidate
13111// indirectly through its operand (we already consider dependencies
13112// through the chain). Check in parallel by searching up from
13113// non-chain operands of candidates.
13114bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13115 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
13116 // FIXME: We should be able to truncate a full search of
13117 // predecessors by doing a BFS and keeping tabs the originating
13118 // stores from which worklist nodes come from in a similar way to
13119 // TokenFactor simplfication.
13120
13121 SmallPtrSet<const SDNode *, 16> Visited;
13122 SmallVector<const SDNode *, 8> Worklist;
13123 unsigned int Max = 8192;
13124 // Search Ops of store candidates.
13125 for (unsigned i = 0; i < NumStores; ++i) {
13126 SDNode *n = StoreNodes[i].MemNode;
13127 // Potential loops may happen only through non-chain operands
13128 for (unsigned j = 1; j < n->getNumOperands(); ++j)
13129 Worklist.push_back(n->getOperand(j).getNode());
13130 }
13131 // Search through DAG. We can stop early if we find a store node.
13132 for (unsigned i = 0; i < NumStores; ++i) {
13133 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13134 Max))
13135 return false;
13136 // Check if we ended early, failing conservatively if so.
13137 if (Visited.size() >= Max)
13138 return false;
13139 }
13140 return true;
13141}
13142
13143bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13144 if (OptLevel == CodeGenOpt::None)
13145 return false;
13146
13147 EVT MemVT = St->getMemoryVT();
13148 int64_t ElementSizeBytes = MemVT.getStoreSize();
13149 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13150
13151 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13152 return false;
13153
13154 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13155 Attribute::NoImplicitFloat);
13156
13157 // This function cannot currently deal with non-byte-sized memory sizes.
13158 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13159 return false;
13160
13161 if (!MemVT.isSimple())
13162 return false;
13163
13164 // Perform an early exit check. Do not bother looking at stored values that
13165 // are not constants, loads, or extracted vector elements.
13166 SDValue StoredVal = peekThroughBitcast(St->getValue());
13167 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13168 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13169 isa<ConstantFPSDNode>(StoredVal);
13170 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13171 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13172
13173 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13174 return false;
13175
13176 SmallVector<MemOpLink, 8> StoreNodes;
13177 // Find potential store merge candidates by searching through chain sub-DAG
13178 getStoreMergeCandidates(St, StoreNodes);
13179
13180 // Check if there is anything to merge.
13181 if (StoreNodes.size() < 2)
13182 return false;
13183
13184 // Sort the memory operands according to their distance from the
13185 // base pointer.
13186 std::sort(StoreNodes.begin(), StoreNodes.end(),
13187 [](MemOpLink LHS, MemOpLink RHS) {
13188 return LHS.OffsetFromBase < RHS.OffsetFromBase;
13189 });
13190
13191 // Store Merge attempts to merge the lowest stores. This generally
13192 // works out as if successful, as the remaining stores are checked
13193 // after the first collection of stores is merged. However, in the
13194 // case that a non-mergeable store is found first, e.g., {p[-2],
13195 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13196 // mergeable cases. To prevent this, we prune such stores from the
13197 // front of StoreNodes here.
13198
13199 bool RV = false;
13200 while (StoreNodes.size() > 1) {
13201 unsigned StartIdx = 0;
13202 while ((StartIdx + 1 < StoreNodes.size()) &&
13203 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13204 StoreNodes[StartIdx + 1].OffsetFromBase)
13205 ++StartIdx;
13206
13207 // Bail if we don't have enough candidates to merge.
13208 if (StartIdx + 1 >= StoreNodes.size())
13209 return RV;
13210
13211 if (StartIdx)
13212 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13213
13214 // Scan the memory operations on the chain and find the first
13215 // non-consecutive store memory address.
13216 unsigned NumConsecutiveStores = 1;
13217 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13218 // Check that the addresses are consecutive starting from the second
13219 // element in the list of stores.
13220 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13221 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13222 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13223 break;
13224 NumConsecutiveStores = i + 1;
13225 }
13226
13227 if (NumConsecutiveStores < 2) {
13228 StoreNodes.erase(StoreNodes.begin(),
13229 StoreNodes.begin() + NumConsecutiveStores);
13230 continue;
13231 }
13232
13233 // Check that we can merge these candidates without causing a cycle
13234 if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
13235 NumConsecutiveStores)) {
13236 StoreNodes.erase(StoreNodes.begin(),
13237 StoreNodes.begin() + NumConsecutiveStores);
13238 continue;
13239 }
13240
13241 // The node with the lowest store address.
13242 LLVMContext &Context = *DAG.getContext();
13243 const DataLayout &DL = DAG.getDataLayout();
13244
13245 // Store the constants into memory as one consecutive store.
13246 if (IsConstantSrc) {
13247 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13248 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13249 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13250 unsigned LastLegalType = 1;
13251 unsigned LastLegalVectorType = 1;
13252 bool LastIntegerTrunc = false;
13253 bool NonZero = false;
13254 unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13255 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13256 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13257 SDValue StoredVal = ST->getValue();
13258 bool IsElementZero = false;
13259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13260 IsElementZero = C->isNullValue();
13261 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13262 IsElementZero = C->getConstantFPValue()->isNullValue();
13263 if (IsElementZero) {
13264 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13265 FirstZeroAfterNonZero = i;
13266 }
13267 NonZero |= !IsElementZero;
13268
13269 // Find a legal type for the constant store.
13270 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13271 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13272 bool IsFast = false;
13273 if (TLI.isTypeLegal(StoreTy) &&
13274 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13275 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13276 FirstStoreAlign, &IsFast) &&
13277 IsFast) {
13278 LastIntegerTrunc = false;
13279 LastLegalType = i + 1;
13280 // Or check whether a truncstore is legal.
13281 } else if (TLI.getTypeAction(Context, StoreTy) ==
13282 TargetLowering::TypePromoteInteger) {
13283 EVT LegalizedStoredValueTy =
13284 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13285 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13286 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13287 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13288 FirstStoreAlign, &IsFast) &&
13289 IsFast) {
13290 LastIntegerTrunc = true;
13291 LastLegalType = i + 1;
13292 }
13293 }
13294
13295 // We only use vectors if the constant is known to be zero or the target
13296 // allows it and the function is not marked with the noimplicitfloat
13297 // attribute.
13298 if ((!NonZero ||
13299 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13300 !NoVectors) {
13301 // Find a legal type for the vector store.
13302 unsigned Elts = (i + 1) * NumMemElts;
13303 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13304 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13305 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13306 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13307 FirstStoreAlign, &IsFast) &&
13308 IsFast)
13309 LastLegalVectorType = i + 1;
13310 }
13311 }
13312
13313 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13314 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13315
13316 // Check if we found a legal integer type that creates a meaningful merge.
13317 if (NumElem < 2) {
13318 // We know that candidate stores are in order and of correct
13319 // shape. While there is no mergeable sequence from the
13320 // beginning one may start later in the sequence. The only
13321 // reason a merge of size N could have failed where another of
13322 // the same size would not have, is if the alignment has
13323 // improved or we've dropped a non-zero value. Drop as many
13324 // candidates as we can here.
13325 unsigned NumSkip = 1;
13326 while (
13327 (NumSkip < NumConsecutiveStores) &&
13328 (NumSkip < FirstZeroAfterNonZero) &&
13329 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13330 NumSkip++;
13331 }
13332 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13333 continue;
13334 }
13335
13336 bool Merged = MergeStoresOfConstantsOrVecElts(
13337 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13338 RV |= Merged;
13339
13340 // Remove merged stores for next iteration.
13341 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13342 continue;
13343 }
13344
13345 // When extracting multiple vector elements, try to store them
13346 // in one vector store rather than a sequence of scalar stores.
13347 if (IsExtractVecSrc) {
13348 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13349 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13350 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13351 unsigned NumStoresToMerge = 1;
13352 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13353 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13354 SDValue StVal = peekThroughBitcast(St->getValue());
13355 // This restriction could be loosened.
13356 // Bail out if any stored values are not elements extracted from a
13357 // vector. It should be possible to handle mixed sources, but load
13358 // sources need more careful handling (see the block of code below that
13359 // handles consecutive loads).
13360 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13361 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13362 return RV;
13363
13364 // Find a legal type for the vector store.
13365 unsigned Elts = (i + 1) * NumMemElts;
13366 EVT Ty =
13367 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13368 bool IsFast;
13369 if (TLI.isTypeLegal(Ty) &&
13370 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13371 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13372 FirstStoreAlign, &IsFast) &&
13373 IsFast)
13374 NumStoresToMerge = i + 1;
13375 }
13376
13377 // Check if we found a legal integer type that creates a meaningful merge.
13378 if (NumStoresToMerge < 2) {
13379 // We know that candidate stores are in order and of correct
13380 // shape. While there is no mergeable sequence from the
13381 // beginning one may start later in the sequence. The only
13382 // reason a merge of size N could have failed where another of
13383 // the same size would not have, is if the alignment has
13384 // improved. Drop as many candidates as we can here.
13385 unsigned NumSkip = 1;
13386 while ((NumSkip < NumConsecutiveStores) &&
13387 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13388 NumSkip++;
13389
13390 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13391 continue;
13392 }
13393
13394 bool Merged = MergeStoresOfConstantsOrVecElts(
13395 StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13396 if (!Merged) {
13397 StoreNodes.erase(StoreNodes.begin(),
13398 StoreNodes.begin() + NumStoresToMerge);
13399 continue;
13400 }
13401 // Remove merged stores for next iteration.
13402 StoreNodes.erase(StoreNodes.begin(),
13403 StoreNodes.begin() + NumStoresToMerge);
13404 RV = true;
13405 continue;
13406 }
13407
13408 // Below we handle the case of multiple consecutive stores that
13409 // come from multiple consecutive loads. We merge them into a single
13410 // wide load and a single wide store.
13411
13412 // Look for load nodes which are used by the stored values.
13413 SmallVector<MemOpLink, 8> LoadNodes;
13414
13415 // Find acceptable loads. Loads need to have the same chain (token factor),
13416 // must not be zext, volatile, indexed, and they must be consecutive.
13417 BaseIndexOffset LdBasePtr;
13418 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13419 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13420 SDValue Val = peekThroughBitcast(St->getValue());
13421 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13422 if (!Ld)
13423 break;
13424
13425 // Loads must only have one use.
13426 if (!Ld->hasNUsesOfValue(1, 0))
13427 break;
13428
13429 // The memory operands must not be volatile.
13430 if (Ld->isVolatile() || Ld->isIndexed())
13431 break;
13432
13433 // The stored memory type must be the same.
13434 if (Ld->getMemoryVT() != MemVT)
13435 break;
13436
13437 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
13438 // If this is not the first ptr that we check.
13439 int64_t LdOffset = 0;
13440 if (LdBasePtr.getBase().getNode()) {
13441 // The base ptr must be the same.
13442 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13443 break;
13444 } else {
13445 // Check that all other base pointers are the same as this one.
13446 LdBasePtr = LdPtr;
13447 }
13448
13449 // We found a potential memory operand to merge.
13450 LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13451 }
13452
13453 if (LoadNodes.size() < 2) {
13454 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13455 continue;
13456 }
13457
13458 // If we have load/store pair instructions and we only have two values,
13459 // don't bother merging.
13460 unsigned RequiredAlignment;
13461 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13462 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13463 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13464 continue;
13465 }
13466 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13467 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13468 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13469 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13470 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13471 unsigned FirstLoadAlign = FirstLoad->getAlignment();
13472
13473 // Scan the memory operations on the chain and find the first
13474 // non-consecutive load memory address. These variables hold the index in
13475 // the store node array.
13476 unsigned LastConsecutiveLoad = 1;
13477 // This variable refers to the size and not index in the array.
13478 unsigned LastLegalVectorType = 1;
13479 unsigned LastLegalIntegerType = 1;
13480 bool isDereferenceable = true;
13481 bool DoIntegerTruncate = false;
13482 StartAddress = LoadNodes[0].OffsetFromBase;
13483 SDValue FirstChain = FirstLoad->getChain();
13484 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13485 // All loads must share the same chain.
13486 if (LoadNodes[i].MemNode->getChain() != FirstChain)
13487 break;
13488
13489 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13490 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13491 break;
13492 LastConsecutiveLoad = i;
13493
13494 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13495 isDereferenceable = false;
13496
13497 // Find a legal type for the vector store.
13498 unsigned Elts = (i + 1) * NumMemElts;
13499 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13500
13501 bool IsFastSt, IsFastLd;
13502 if (TLI.isTypeLegal(StoreTy) &&
13503 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13504 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13505 FirstStoreAlign, &IsFastSt) &&
13506 IsFastSt &&
13507 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13508 FirstLoadAlign, &IsFastLd) &&
13509 IsFastLd) {
13510 LastLegalVectorType = i + 1;
13511 }
13512
13513 // Find a legal type for the integer store.
13514 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13515 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13516 if (TLI.isTypeLegal(StoreTy) &&
13517 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13518 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13519 FirstStoreAlign, &IsFastSt) &&
13520 IsFastSt &&
13521 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13522 FirstLoadAlign, &IsFastLd) &&
13523 IsFastLd) {
13524 LastLegalIntegerType = i + 1;
13525 DoIntegerTruncate = false;
13526 // Or check whether a truncstore and extload is legal.
13527 } else if (TLI.getTypeAction(Context, StoreTy) ==
13528 TargetLowering::TypePromoteInteger) {
13529 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13530 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13531 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13532 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13533 StoreTy) &&
13534 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13535 StoreTy) &&
13536 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13537 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13538 FirstStoreAlign, &IsFastSt) &&
13539 IsFastSt &&
13540 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13541 FirstLoadAlign, &IsFastLd) &&
13542 IsFastLd) {
13543 LastLegalIntegerType = i + 1;
13544 DoIntegerTruncate = true;
13545 }
13546 }
13547 }
13548
13549 // Only use vector types if the vector type is larger than the integer type.
13550 // If they are the same, use integers.
13551 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13552 unsigned LastLegalType =
13553 std::max(LastLegalVectorType, LastLegalIntegerType);
13554
13555 // We add +1 here because the LastXXX variables refer to location while
13556 // the NumElem refers to array/index size.
13557 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13558 NumElem = std::min(LastLegalType, NumElem);
13559
13560 if (NumElem < 2) {
13561 // We know that candidate stores are in order and of correct
13562 // shape. While there is no mergeable sequence from the
13563 // beginning one may start later in the sequence. The only
13564 // reason a merge of size N could have failed where another of
13565 // the same size would not have is if the alignment or either
13566 // the load or store has improved. Drop as many candidates as we
13567 // can here.
13568 unsigned NumSkip = 1;
13569 while ((NumSkip < LoadNodes.size()) &&
13570 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13571 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13572 NumSkip++;
13573 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13574 continue;
13575 }
13576
13577 // Find if it is better to use vectors or integers to load and store
13578 // to memory.
13579 EVT JointMemOpVT;
13580 if (UseVectorTy) {
13581 // Find a legal type for the vector store.
13582 unsigned Elts = NumElem * NumMemElts;
13583 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13584 } else {
13585 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13586 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13587 }
13588
13589 SDLoc LoadDL(LoadNodes[0].MemNode);
13590 SDLoc StoreDL(StoreNodes[0].MemNode);
13591
13592 // The merged loads are required to have the same incoming chain, so
13593 // using the first's chain is acceptable.
13594
13595 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13596 AddToWorklist(NewStoreChain.getNode());
13597
13598 MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13599 MachineMemOperand::MODereferenceable:
13600 MachineMemOperand::MONone;
13601
13602 SDValue NewLoad, NewStore;
13603 if (UseVectorTy || !DoIntegerTruncate) {
13604 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13605 FirstLoad->getBasePtr(),
13606 FirstLoad->getPointerInfo(), FirstLoadAlign,
13607 MMOFlags);
13608 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13609 FirstInChain->getBasePtr(),
13610 FirstInChain->getPointerInfo(), FirstStoreAlign);
13611 } else { // This must be the truncstore/extload case
13612 EVT ExtendedTy =
13613 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13614 NewLoad =
13615 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13616 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13617 JointMemOpVT, FirstLoadAlign, MMOFlags);
13618 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13619 FirstInChain->getBasePtr(),
13620 FirstInChain->getPointerInfo(), JointMemOpVT,
13621 FirstInChain->getAlignment(),
13622 FirstInChain->getMemOperand()->getFlags());
13623 }
13624
13625 // Transfer chain users from old loads to the new load.
13626 for (unsigned i = 0; i < NumElem; ++i) {
13627 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13628 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13629 SDValue(NewLoad.getNode(), 1));
13630 }
13631
13632 // Replace the all stores with the new store. Recursively remove
13633 // corresponding value if its no longer used.
13634 for (unsigned i = 0; i < NumElem; ++i) {
13635 SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13636 CombineTo(StoreNodes[i].MemNode, NewStore);
13637 if (Val.getNode()->use_empty())
13638 recursivelyDeleteUnusedNodes(Val.getNode());
13639 }
13640
13641 RV = true;
13642 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13643 }
13644 return RV;
13645}
13646
13647SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13648 SDLoc SL(ST);
13649 SDValue ReplStore;
13650
13651 // Replace the chain to avoid dependency.
13652 if (ST->isTruncatingStore()) {
13653 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13654 ST->getBasePtr(), ST->getMemoryVT(),
13655 ST->getMemOperand());
13656 } else {
13657 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13658 ST->getMemOperand());
13659 }
13660
13661 // Create token to keep both nodes around.
13662 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13663 MVT::Other, ST->getChain(), ReplStore);
13664
13665 // Make sure the new and old chains are cleaned up.
13666 AddToWorklist(Token.getNode());
13667
13668 // Don't add users to work list.
13669 return CombineTo(ST, Token, false);
13670}
13671
13672SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13673 SDValue Value = ST->getValue();
13674 if (Value.getOpcode() == ISD::TargetConstantFP)
13675 return SDValue();
13676
13677 SDLoc DL(ST);
13678
13679 SDValue Chain = ST->getChain();
13680 SDValue Ptr = ST->getBasePtr();
13681
13682 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13683
13684 // NOTE: If the original store is volatile, this transform must not increase
13685 // the number of stores. For example, on x86-32 an f64 can be stored in one
13686 // processor operation but an i64 (which is not legal) requires two. So the
13687 // transform should not be done in this case.
13688
13689 SDValue Tmp;
13690 switch (CFP->getSimpleValueType(0).SimpleTy) {
13691 default:
13692 llvm_unreachable("Unknown FP type")::llvm::llvm_unreachable_internal("Unknown FP type", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 13692)
;
13693 case MVT::f16: // We don't do this for these yet.
13694 case MVT::f80:
13695 case MVT::f128:
13696 case MVT::ppcf128:
13697 return SDValue();
13698 case MVT::f32:
13699 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13700 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13701 ;
13702 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13703 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13704 MVT::i32);
13705 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13706 }
13707
13708 return SDValue();
13709 case MVT::f64:
13710 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13711 !ST->isVolatile()) ||
13712 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13713 ;
13714 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13715 getZExtValue(), SDLoc(CFP), MVT::i64);
13716 return DAG.getStore(Chain, DL, Tmp,
13717 Ptr, ST->getMemOperand());
13718 }
13719
13720 if (!ST->isVolatile() &&
13721 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13722 // Many FP stores are not made apparent until after legalize, e.g. for
13723 // argument passing. Since this is so common, custom legalize the
13724 // 64-bit integer store into two 32-bit stores.
13725 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13726 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13727 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13728 if (DAG.getDataLayout().isBigEndian())
13729 std::swap(Lo, Hi);
13730
13731 unsigned Alignment = ST->getAlignment();
13732 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13733 AAMDNodes AAInfo = ST->getAAInfo();
13734
13735 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13736 ST->getAlignment(), MMOFlags, AAInfo);
13737 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13738 DAG.getConstant(4, DL, Ptr.getValueType()));
13739 Alignment = MinAlign(Alignment, 4U);
13740 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13741 ST->getPointerInfo().getWithOffset(4),
13742 Alignment, MMOFlags, AAInfo);
13743 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13744 St0, St1);
13745 }
13746
13747 return SDValue();
13748 }
13749}
13750
13751SDValue DAGCombiner::visitSTORE(SDNode *N) {
13752 StoreSDNode *ST = cast<StoreSDNode>(N);
13753 SDValue Chain = ST->getChain();
13754 SDValue Value = ST->getValue();
13755 SDValue Ptr = ST->getBasePtr();
13756
13757 // If this is a store of a bit convert, store the input value if the
13758 // resultant store does not need a higher alignment than the original.
13759 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13760 ST->isUnindexed()) {
13761 EVT SVT = Value.getOperand(0).getValueType();
13762 if (((!LegalOperations && !ST->isVolatile()) ||
13763 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13764 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13765 unsigned OrigAlign = ST->getAlignment();
13766 bool Fast = false;
13767 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13768 ST->getAddressSpace(), OrigAlign, &Fast) &&
13769 Fast) {
13770 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13771 ST->getPointerInfo(), OrigAlign,
13772 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13773 }
13774 }
13775 }
13776
13777 // Turn 'store undef, Ptr' -> nothing.
13778 if (Value.isUndef() && ST->isUnindexed())
13779 return Chain;
13780
13781 // Try to infer better alignment information than the store already has.
13782 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13783 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13784 if (Align > ST->getAlignment()) {
13785 SDValue NewStore =
13786 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13787 ST->getMemoryVT(), Align,
13788 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13789 if (NewStore.getNode() != N)
13790 return CombineTo(ST, NewStore, true);
13791 }
13792 }
13793 }
13794
13795 // Try transforming a pair floating point load / store ops to integer
13796 // load / store ops.
13797 if (SDValue NewST = TransformFPLoadStorePair(N))
13798 return NewST;
13799
13800 if (ST->isUnindexed()) {
13801 // Walk up chain skipping non-aliasing memory nodes, on this store and any
13802 // adjacent stores.
13803 if (findBetterNeighborChains(ST)) {
13804 // replaceStoreChain uses CombineTo, which handled all of the worklist
13805 // manipulation. Return the original node to not do anything else.
13806 return SDValue(ST, 0);
13807 }
13808 Chain = ST->getChain();
13809 }
13810
13811 // FIXME: is there such a thing as a truncating indexed store?
13812 if (ST->isTruncatingStore() && ST->isUnindexed() &&
13813 Value.getValueType().isInteger()) {
13814 // See if we can simplify the input to this truncstore with knowledge that
13815 // only the low bits are being used. For example:
13816 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
13817 SDValue Shorter = DAG.GetDemandedBits(
13818 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13819 ST->getMemoryVT().getScalarSizeInBits()));
13820 AddToWorklist(Value.getNode());
13821 if (Shorter.getNode())
13822 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13823 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13824
13825 // Otherwise, see if we can simplify the operation with
13826 // SimplifyDemandedBits, which only works if the value has a single use.
13827 if (SimplifyDemandedBits(
13828 Value,
13829 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13830 ST->getMemoryVT().getScalarSizeInBits()))) {
13831 // Re-visit the store if anything changed and the store hasn't been merged
13832 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13833 // node back to the worklist if necessary, but we also need to re-visit
13834 // the Store node itself.
13835 if (N->getOpcode() != ISD::DELETED_NODE)
13836 AddToWorklist(N);
13837 return SDValue(N, 0);
13838 }
13839 }
13840
13841 // If this is a load followed by a store to the same location, then the store
13842 // is dead/noop.
13843 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13844 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13845 ST->isUnindexed() && !ST->isVolatile() &&
13846 // There can't be any side effects between the load and store, such as
13847 // a call or store.
13848 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13849 // The store is dead, remove it.
13850 return Chain;
13851 }
13852 }
13853
13854 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13855 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13856 !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13857 ST->getMemoryVT() == ST1->getMemoryVT()) {
13858 // If this is a store followed by a store with the same value to the same
13859 // location, then the store is dead/noop.
13860 if (ST1->getValue() == Value) {
13861 // The store is dead, remove it.
13862 return Chain;
13863 }
13864
13865 // If this is a store who's preceeding store to the same location
13866 // and no one other node is chained to that store we can effectively
13867 // drop the store. Do not remove stores to undef as they may be used as
13868 // data sinks.
13869 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13870 !ST1->getBasePtr().isUndef()) {
13871 // ST1 is fully overwritten and can be elided. Combine with it's chain
13872 // value.
13873 CombineTo(ST1, ST1->getChain());
13874 return SDValue();
13875 }
13876 }
13877 }
13878
13879 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13880 // truncating store. We can do this even if this is already a truncstore.
13881 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13882 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13883 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13884 ST->getMemoryVT())) {
13885 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13886 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13887 }
13888
13889 // Always perform this optimization before types are legal. If the target
13890 // prefers, also try this after legalization to catch stores that were created
13891 // by intrinsics or other nodes.
13892 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
13893 while (true) {
13894 // There can be multiple store sequences on the same chain.
13895 // Keep trying to merge store sequences until we are unable to do so
13896 // or until we merge the last store on the chain.
13897 bool Changed = MergeConsecutiveStores(ST);
13898 if (!Changed) break;
13899 // Return N as merge only uses CombineTo and no worklist clean
13900 // up is necessary.
13901 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13902 return SDValue(N, 0);
13903 }
13904 }
13905
13906 // Try transforming N to an indexed store.
13907 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13908 return SDValue(N, 0);
13909
13910 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13911 //
13912 // Make sure to do this only after attempting to merge stores in order to
13913 // avoid changing the types of some subset of stores due to visit order,
13914 // preventing their merging.
13915 if (isa<ConstantFPSDNode>(ST->getValue())) {
13916 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13917 return NewSt;
13918 }
13919
13920 if (SDValue NewSt = splitMergedValStore(ST))
13921 return NewSt;
13922
13923 return ReduceLoadOpStoreWidth(N);
13924}
13925
13926/// For the instruction sequence of store below, F and I values
13927/// are bundled together as an i64 value before being stored into memory.
13928/// Sometimes it is more efficent to generate separate stores for F and I,
13929/// which can remove the bitwise instructions or sink them to colder places.
13930///
13931/// (store (or (zext (bitcast F to i32) to i64),
13932/// (shl (zext I to i64), 32)), addr) -->
13933/// (store F, addr) and (store I, addr+4)
13934///
13935/// Similarly, splitting for other merged store can also be beneficial, like:
13936/// For pair of {i32, i32}, i64 store --> two i32 stores.
13937/// For pair of {i32, i16}, i64 store --> two i32 stores.
13938/// For pair of {i16, i16}, i32 store --> two i16 stores.
13939/// For pair of {i16, i8}, i32 store --> two i16 stores.
13940/// For pair of {i8, i8}, i16 store --> two i8 stores.
13941///
13942/// We allow each target to determine specifically which kind of splitting is
13943/// supported.
13944///
13945/// The store patterns are commonly seen from the simple code snippet below
13946/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13947/// void goo(const std::pair<int, float> &);
13948/// hoo() {
13949/// ...
13950/// goo(std::make_pair(tmp, ftmp));
13951/// ...
13952/// }
13953///
13954SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13955 if (OptLevel == CodeGenOpt::None)
13956 return SDValue();
13957
13958 SDValue Val = ST->getValue();
13959 SDLoc DL(ST);
13960
13961 // Match OR operand.
13962 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13963 return SDValue();
13964
13965 // Match SHL operand and get Lower and Higher parts of Val.
13966 SDValue Op1 = Val.getOperand(0);
13967 SDValue Op2 = Val.getOperand(1);
13968 SDValue Lo, Hi;
13969 if (Op1.getOpcode() != ISD::SHL) {
13970 std::swap(Op1, Op2);
13971 if (Op1.getOpcode() != ISD::SHL)
13972 return SDValue();
13973 }
13974 Lo = Op2;
13975 Hi = Op1.getOperand(0);
13976 if (!Op1.hasOneUse())
13977 return SDValue();
13978
13979 // Match shift amount to HalfValBitSize.
13980 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13981 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13982 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13983 return SDValue();
13984
13985 // Lo and Hi are zero-extended from int with size less equal than 32
13986 // to i64.
13987 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13988 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13989 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13990 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13991 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13992 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13993 return SDValue();
13994
13995 // Use the EVT of low and high parts before bitcast as the input
13996 // of target query.
13997 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13998 ? Lo.getOperand(0).getValueType()
13999 : Lo.getValueType();
14000 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
14001 ? Hi.getOperand(0).getValueType()
14002 : Hi.getValueType();
14003 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
14004 return SDValue();
14005
14006 // Start to split store.
14007 unsigned Alignment = ST->getAlignment();
14008 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14009 AAMDNodes AAInfo = ST->getAAInfo();
14010
14011 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
14012 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
14013 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
14014 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
14015
14016 SDValue Chain = ST->getChain();
14017 SDValue Ptr = ST->getBasePtr();
14018 // Lower value store.
14019 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14020 ST->getAlignment(), MMOFlags, AAInfo);
14021 Ptr =
14022 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14023 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
14024 // Higher value store.
14025 SDValue St1 =
14026 DAG.getStore(St0, DL, Hi, Ptr,
14027 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
14028 Alignment / 2, MMOFlags, AAInfo);
14029 return St1;
14030}
14031
14032/// Convert a disguised subvector insertion into a shuffle:
14033/// insert_vector_elt V, (bitcast X from vector type), IdxC -->
14034/// bitcast(shuffle (bitcast V), (extended X), Mask)
14035/// Note: We do not use an insert_subvector node because that requires a legal
14036/// subvector type.
14037SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
14038 SDValue InsertVal = N->getOperand(1);
14039 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
14040 !InsertVal.getOperand(0).getValueType().isVector())
14041 return SDValue();
14042
14043 SDValue SubVec = InsertVal.getOperand(0);
14044 SDValue DestVec = N->getOperand(0);
14045 EVT SubVecVT = SubVec.getValueType();
14046 EVT VT = DestVec.getValueType();
14047 unsigned NumSrcElts = SubVecVT.getVectorNumElements();
14048 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
14049 unsigned NumMaskVals = ExtendRatio * NumSrcElts;
14050
14051 // Step 1: Create a shuffle mask that implements this insert operation. The
14052 // vector that we are inserting into will be operand 0 of the shuffle, so
14053 // those elements are just 'i'. The inserted subvector is in the first
14054 // positions of operand 1 of the shuffle. Example:
14055 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
14056 SmallVector<int, 16> Mask(NumMaskVals);
14057 for (unsigned i = 0; i != NumMaskVals; ++i) {
14058 if (i / NumSrcElts == InsIndex)
14059 Mask[i] = (i % NumSrcElts) + NumMaskVals;
14060 else
14061 Mask[i] = i;
14062 }
14063
14064 // Bail out if the target can not handle the shuffle we want to create.
14065 EVT SubVecEltVT = SubVecVT.getVectorElementType();
14066 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14067 if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14068 return SDValue();
14069
14070 // Step 2: Create a wide vector from the inserted source vector by appending
14071 // undefined elements. This is the same size as our destination vector.
14072 SDLoc DL(N);
14073 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14074 ConcatOps[0] = SubVec;
14075 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14076
14077 // Step 3: Shuffle in the padded subvector.
14078 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14079 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14080 AddToWorklist(PaddedSubV.getNode());
14081 AddToWorklist(DestVecBC.getNode());
14082 AddToWorklist(Shuf.getNode());
14083 return DAG.getBitcast(VT, Shuf);
14084}
14085
14086SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14087 SDValue InVec = N->getOperand(0);
14088 SDValue InVal = N->getOperand(1);
14089 SDValue EltNo = N->getOperand(2);
14090 SDLoc DL(N);
14091
14092 // If the inserted element is an UNDEF, just use the input vector.
14093 if (InVal.isUndef())
14094 return InVec;
14095
14096 EVT VT = InVec.getValueType();
14097
14098 // Remove redundant insertions:
14099 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14100 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14101 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14102 return InVec;
14103
14104 // We must know which element is being inserted for folds below here.
14105 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14106 if (!IndexC)
14107 return SDValue();
14108 unsigned Elt = IndexC->getZExtValue();
14109
14110 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14111 return Shuf;
14112
14113 // Canonicalize insert_vector_elt dag nodes.
14114 // Example:
14115 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14116 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14117 //
14118 // Do this only if the child insert_vector node has one use; also
14119 // do this only if indices are both constants and Idx1 < Idx0.
14120 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14121 && isa<ConstantSDNode>(InVec.getOperand(2))) {
14122 unsigned OtherElt = InVec.getConstantOperandVal(2);
14123 if (Elt < OtherElt) {
14124 // Swap nodes.
14125 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14126 InVec.getOperand(0), InVal, EltNo);
14127 AddToWorklist(NewOp.getNode());
14128 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14129 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14130 }
14131 }
14132
14133 // If we can't generate a legal BUILD_VECTOR, exit
14134 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14135 return SDValue();
14136
14137 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14138 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
14139 // vector elements.
14140 SmallVector<SDValue, 8> Ops;
14141 // Do not combine these two vectors if the output vector will not replace
14142 // the input vector.
14143 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14144 Ops.append(InVec.getNode()->op_begin(),
14145 InVec.getNode()->op_end());
14146 } else if (InVec.isUndef()) {
14147 unsigned NElts = VT.getVectorNumElements();
14148 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14149 } else {
14150 return SDValue();
14151 }
14152
14153 // Insert the element
14154 if (Elt < Ops.size()) {
14155 // All the operands of BUILD_VECTOR must have the same type;
14156 // we enforce that here.
14157 EVT OpVT = Ops[0].getValueType();
14158 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14159 }
14160
14161 // Return the new vector
14162 return DAG.getBuildVector(VT, DL, Ops);
14163}
14164
14165SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14166 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14167 assert(!OriginalLoad->isVolatile())(static_cast <bool> (!OriginalLoad->isVolatile()) ? void
(0) : __assert_fail ("!OriginalLoad->isVolatile()", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14167, __extension__ __PRETTY_FUNCTION__))
;
14168
14169 EVT ResultVT = EVE->getValueType(0);
14170 EVT VecEltVT = InVecVT.getVectorElementType();
14171 unsigned Align = OriginalLoad->getAlignment();
14172 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14173 VecEltVT.getTypeForEVT(*DAG.getContext()));
14174
14175 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14176 return SDValue();
14177
14178 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14179 ISD::NON_EXTLOAD : ISD::EXTLOAD;
14180 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14181 return SDValue();
14182
14183 Align = NewAlign;
14184
14185 SDValue NewPtr = OriginalLoad->getBasePtr();
14186 SDValue Offset;
14187 EVT PtrType = NewPtr.getValueType();
14188 MachinePointerInfo MPI;
14189 SDLoc DL(EVE);
14190 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14191 int Elt = ConstEltNo->getZExtValue();
14192 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14193 Offset = DAG.getConstant(PtrOff, DL, PtrType);
14194 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14195 } else {
14196 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14197 Offset = DAG.getNode(
14198 ISD::MUL, DL, PtrType, Offset,
14199 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14200 MPI = OriginalLoad->getPointerInfo();
14201 }
14202 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14203
14204 // The replacement we need to do here is a little tricky: we need to
14205 // replace an extractelement of a load with a load.
14206 // Use ReplaceAllUsesOfValuesWith to do the replacement.
14207 // Note that this replacement assumes that the extractvalue is the only
14208 // use of the load; that's okay because we don't want to perform this
14209 // transformation in other cases anyway.
14210 SDValue Load;
14211 SDValue Chain;
14212 if (ResultVT.bitsGT(VecEltVT)) {
14213 // If the result type of vextract is wider than the load, then issue an
14214 // extending load instead.
14215 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14216 VecEltVT)
14217 ? ISD::ZEXTLOAD
14218 : ISD::EXTLOAD;
14219 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14220 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14221 Align, OriginalLoad->getMemOperand()->getFlags(),
14222 OriginalLoad->getAAInfo());
14223 Chain = Load.getValue(1);
14224 } else {
14225 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14226 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14227 OriginalLoad->getAAInfo());
14228 Chain = Load.getValue(1);
14229 if (ResultVT.bitsLT(VecEltVT))
14230 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14231 else
14232 Load = DAG.getBitcast(ResultVT, Load);
14233 }
14234 WorklistRemover DeadNodes(*this);
14235 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14236 SDValue To[] = { Load, Chain };
14237 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14238 // Since we're explicitly calling ReplaceAllUses, add the new node to the
14239 // worklist explicitly as well.
14240 AddToWorklist(Load.getNode());
14241 AddUsersToWorklist(Load.getNode()); // Add users too
14242 // Make sure to revisit this node to clean it up; it will usually be dead.
14243 AddToWorklist(EVE);
14244 ++OpsNarrowed;
14245 return SDValue(EVE, 0);
14246}
14247
14248SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14249 // (vextract (scalar_to_vector val, 0) -> val
14250 SDValue InVec = N->getOperand(0);
14251 EVT VT = InVec.getValueType();
14252 EVT NVT = N->getValueType(0);
14253
14254 if (InVec.isUndef())
14255 return DAG.getUNDEF(NVT);
14256
14257 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14258 // Check if the result type doesn't match the inserted element type. A
14259 // SCALAR_TO_VECTOR may truncate the inserted element and the
14260 // EXTRACT_VECTOR_ELT may widen the extracted vector.
14261 SDValue InOp = InVec.getOperand(0);
14262 if (InOp.getValueType() != NVT) {
14263 assert(InOp.getValueType().isInteger() && NVT.isInteger())(static_cast <bool> (InOp.getValueType().isInteger() &&
NVT.isInteger()) ? void (0) : __assert_fail ("InOp.getValueType().isInteger() && NVT.isInteger()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14263, __extension__ __PRETTY_FUNCTION__))
;
14264 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14265 }
14266 return InOp;
14267 }
14268
14269 SDValue EltNo = N->getOperand(1);
14270 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14271
14272 // extract_vector_elt of out-of-bounds element -> UNDEF
14273 if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements()))
14274 return DAG.getUNDEF(NVT);
14275
14276 // extract_vector_elt (build_vector x, y), 1 -> y
14277 if (ConstEltNo &&
14278 InVec.getOpcode() == ISD::BUILD_VECTOR &&
14279 TLI.isTypeLegal(VT) &&
14280 (InVec.hasOneUse() ||
14281 TLI.aggressivelyPreferBuildVectorSources(VT))) {
14282 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14283 EVT InEltVT = Elt.getValueType();
14284
14285 // Sometimes build_vector's scalar input types do not match result type.
14286 if (NVT == InEltVT)
14287 return Elt;
14288
14289 // TODO: It may be useful to truncate if free if the build_vector implicitly
14290 // converts.
14291 }
14292
14293 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14294 bool isLE = DAG.getDataLayout().isLittleEndian();
14295 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14296 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14297 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14298 SDValue BCSrc = InVec.getOperand(0);
14299 if (BCSrc.getValueType().isScalarInteger())
14300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14301 }
14302
14303 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14304 //
14305 // This only really matters if the index is non-constant since other combines
14306 // on the constant elements already work.
14307 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14308 EltNo == InVec.getOperand(2)) {
14309 SDValue Elt = InVec.getOperand(1);
14310 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14311 }
14312
14313 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14314 // We only perform this optimization before the op legalization phase because
14315 // we may introduce new vector instructions which are not backed by TD
14316 // patterns. For example on AVX, extracting elements from a wide vector
14317 // without using extract_subvector. However, if we can find an underlying
14318 // scalar value, then we can always use that.
14319 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14320 int NumElem = VT.getVectorNumElements();
14321 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14322 // Find the new index to extract from.
14323 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14324
14325 // Extracting an undef index is undef.
14326 if (OrigElt == -1)
14327 return DAG.getUNDEF(NVT);
14328
14329 // Select the right vector half to extract from.
14330 SDValue SVInVec;
14331 if (OrigElt < NumElem) {
14332 SVInVec = InVec->getOperand(0);
14333 } else {
14334 SVInVec = InVec->getOperand(1);
14335 OrigElt -= NumElem;
14336 }
14337
14338 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14339 SDValue InOp = SVInVec.getOperand(OrigElt);
14340 if (InOp.getValueType() != NVT) {
14341 assert(InOp.getValueType().isInteger() && NVT.isInteger())(static_cast <bool> (InOp.getValueType().isInteger() &&
NVT.isInteger()) ? void (0) : __assert_fail ("InOp.getValueType().isInteger() && NVT.isInteger()"
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14341, __extension__ __PRETTY_FUNCTION__))
;
14342 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14343 }
14344
14345 return InOp;
14346 }
14347
14348 // FIXME: We should handle recursing on other vector shuffles and
14349 // scalar_to_vector here as well.
14350
14351 if (!LegalOperations ||
14352 // FIXME: Should really be just isOperationLegalOrCustom.
14353 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14354 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14355 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14356 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14357 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14358 }
14359 }
14360
14361 bool BCNumEltsChanged = false;
14362 EVT ExtVT = VT.getVectorElementType();
14363 EVT LVT = ExtVT;
14364
14365 // If the result of load has to be truncated, then it's not necessarily
14366 // profitable.
14367 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14368 return SDValue();
14369
14370 if (InVec.getOpcode() == ISD::BITCAST) {
14371 // Don't duplicate a load with other uses.
14372 if (!InVec.hasOneUse())
14373 return SDValue();
14374
14375 EVT BCVT = InVec.getOperand(0).getValueType();
14376 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14377 return SDValue();
14378 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14379 BCNumEltsChanged = true;
14380 InVec = InVec.getOperand(0);
14381 ExtVT = BCVT.getVectorElementType();
14382 }
14383
14384 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14385 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14386 ISD::isNormalLoad(InVec.getNode()) &&
14387 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14388 SDValue Index = N->getOperand(1);
14389 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14390 if (!OrigLoad->isVolatile()) {
14391 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14392 OrigLoad);
14393 }
14394 }
14395 }
14396
14397 // Perform only after legalization to ensure build_vector / vector_shuffle
14398 // optimizations have already been done.
14399 if (!LegalOperations) return SDValue();
14400
14401 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14402 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14403 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14404
14405 if (ConstEltNo) {
14406 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14407
14408 LoadSDNode *LN0 = nullptr;
14409 const ShuffleVectorSDNode *SVN = nullptr;
14410 if (ISD::isNormalLoad(InVec.getNode())) {
14411 LN0 = cast<LoadSDNode>(InVec);
14412 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14413 InVec.getOperand(0).getValueType() == ExtVT &&
14414 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14415 // Don't duplicate a load with other uses.
14416 if (!InVec.hasOneUse())
14417 return SDValue();
14418
14419 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14420 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14421 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14422 // =>
14423 // (load $addr+1*size)
14424
14425 // Don't duplicate a load with other uses.
14426 if (!InVec.hasOneUse())
14427 return SDValue();
14428
14429 // If the bit convert changed the number of elements, it is unsafe
14430 // to examine the mask.
14431 if (BCNumEltsChanged)
14432 return SDValue();
14433
14434 // Select the input vector, guarding against out of range extract vector.
14435 unsigned NumElems = VT.getVectorNumElements();
14436 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14437 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14438
14439 if (InVec.getOpcode() == ISD::BITCAST) {
14440 // Don't duplicate a load with other uses.
14441 if (!InVec.hasOneUse())
14442 return SDValue();
14443
14444 InVec = InVec.getOperand(0);
14445 }
14446 if (ISD::isNormalLoad(InVec.getNode())) {
14447 LN0 = cast<LoadSDNode>(InVec);
14448 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14449 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14450 }
14451 }
14452
14453 // Make sure we found a non-volatile load and the extractelement is
14454 // the only use.
14455 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14456 return SDValue();
14457
14458 // If Idx was -1 above, Elt is going to be -1, so just return undef.
14459 if (Elt == -1)
14460 return DAG.getUNDEF(LVT);
14461
14462 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14463 }
14464
14465 return SDValue();
14466}
14467
14468// Simplify (build_vec (ext )) to (bitcast (build_vec ))
14469SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14470 // We perform this optimization post type-legalization because
14471 // the type-legalizer often scalarizes integer-promoted vectors.
14472 // Performing this optimization before may create bit-casts which
14473 // will be type-legalized to complex code sequences.
14474 // We perform this optimization only before the operation legalizer because we
14475 // may introduce illegal operations.
14476 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14477 return SDValue();
14478
14479 unsigned NumInScalars = N->getNumOperands();
14480 SDLoc DL(N);
14481 EVT VT = N->getValueType(0);
14482
14483 // Check to see if this is a BUILD_VECTOR of a bunch of values
14484 // which come from any_extend or zero_extend nodes. If so, we can create
14485 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14486 // optimizations. We do not handle sign-extend because we can't fill the sign
14487 // using shuffles.
14488 EVT SourceType = MVT::Other;
14489 bool AllAnyExt = true;
14490
14491 for (unsigned i = 0; i != NumInScalars; ++i) {
14492 SDValue In = N->getOperand(i);
14493 // Ignore undef inputs.
14494 if (In.isUndef()) continue;
14495
14496 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
14497 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14498
14499 // Abort if the element is not an extension.
14500 if (!ZeroExt && !AnyExt) {
14501 SourceType = MVT::Other;
14502 break;
14503 }
14504
14505 // The input is a ZeroExt or AnyExt. Check the original type.
14506 EVT InTy = In.getOperand(0).getValueType();
14507
14508 // Check that all of the widened source types are the same.
14509 if (SourceType == MVT::Other)
14510 // First time.
14511 SourceType = InTy;
14512 else if (InTy != SourceType) {
14513 // Multiple income types. Abort.
14514 SourceType = MVT::Other;
14515 break;
14516 }
14517
14518 // Check if all of the extends are ANY_EXTENDs.
14519 AllAnyExt &= AnyExt;
14520 }
14521
14522 // In order to have valid types, all of the inputs must be extended from the
14523 // same source type and all of the inputs must be any or zero extend.
14524 // Scalar sizes must be a power of two.
14525 EVT OutScalarTy = VT.getScalarType();
14526 bool ValidTypes = SourceType != MVT::Other &&
14527 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14528 isPowerOf2_32(SourceType.getSizeInBits());
14529
14530 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14531 // turn into a single shuffle instruction.
14532 if (!ValidTypes)
14533 return SDValue();
14534
14535 bool isLE = DAG.getDataLayout().isLittleEndian();
14536 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14537 assert(ElemRatio > 1 && "Invalid element size ratio")(static_cast <bool> (ElemRatio > 1 && "Invalid element size ratio"
) ? void (0) : __assert_fail ("ElemRatio > 1 && \"Invalid element size ratio\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14537, __extension__ __PRETTY_FUNCTION__))
;
14538 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14539 DAG.getConstant(0, DL, SourceType);
14540
14541 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14542 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14543
14544 // Populate the new build_vector
14545 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14546 SDValue Cast = N->getOperand(i);
14547 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||(static_cast <bool> ((Cast.getOpcode() == ISD::ANY_EXTEND
|| Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) &&
"Invalid cast opcode") ? void (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14549, __extension__ __PRETTY_FUNCTION__))
14548 Cast.getOpcode() == ISD::ZERO_EXTEND ||(static_cast <bool> ((Cast.getOpcode() == ISD::ANY_EXTEND
|| Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) &&
"Invalid cast opcode") ? void (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14549, __extension__ __PRETTY_FUNCTION__))
14549 Cast.isUndef()) && "Invalid cast opcode")(static_cast <bool> ((Cast.getOpcode() == ISD::ANY_EXTEND
|| Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) &&
"Invalid cast opcode") ? void (0) : __assert_fail ("(Cast.getOpcode() == ISD::ANY_EXTEND || Cast.getOpcode() == ISD::ZERO_EXTEND || Cast.isUndef()) && \"Invalid cast opcode\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14549, __extension__ __PRETTY_FUNCTION__))
;
14550 SDValue In;
14551 if (Cast.isUndef())
14552 In = DAG.getUNDEF(SourceType);
14553 else
14554 In = Cast->getOperand(0);
14555 unsigned Index = isLE ? (i * ElemRatio) :
14556 (i * ElemRatio + (ElemRatio - 1));
14557
14558 assert(Index < Ops.size() && "Invalid index")(static_cast <bool> (Index < Ops.size() && "Invalid index"
) ? void (0) : __assert_fail ("Index < Ops.size() && \"Invalid index\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14558, __extension__ __PRETTY_FUNCTION__))
;
14559 Ops[Index] = In;
14560 }
14561
14562 // The type of the new BUILD_VECTOR node.
14563 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14564 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&(static_cast <bool> (VecVT.getSizeInBits() == VT.getSizeInBits
() && "Invalid vector size") ? void (0) : __assert_fail
("VecVT.getSizeInBits() == VT.getSizeInBits() && \"Invalid vector size\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14565, __extension__ __PRETTY_FUNCTION__))
14565 "Invalid vector size")(static_cast <bool> (VecVT.getSizeInBits() == VT.getSizeInBits
() && "Invalid vector size") ? void (0) : __assert_fail
("VecVT.getSizeInBits() == VT.getSizeInBits() && \"Invalid vector size\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14565, __extension__ __PRETTY_FUNCTION__))
;
14566 // Check if the new vector type is legal.
14567 if (!isTypeLegal(VecVT)) return SDValue();
14568
14569 // Make the new BUILD_VECTOR.
14570 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14571
14572 // The new BUILD_VECTOR node has the potential to be further optimized.
14573 AddToWorklist(BV.getNode());
14574 // Bitcast to the desired type.
14575 return DAG.getBitcast(VT, BV);
14576}
14577
14578SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14579 EVT VT = N->getValueType(0);
14580
14581 unsigned NumInScalars = N->getNumOperands();
14582 SDLoc DL(N);
14583
14584 EVT SrcVT = MVT::Other;
14585 unsigned Opcode = ISD::DELETED_NODE;
14586 unsigned NumDefs = 0;
14587
14588 for (unsigned i = 0; i != NumInScalars; ++i) {
14589 SDValue In = N->getOperand(i);
14590 unsigned Opc = In.getOpcode();
14591
14592 if (Opc == ISD::UNDEF)
14593 continue;
14594
14595 // If all scalar values are floats and converted from integers.
14596 if (Opcode == ISD::DELETED_NODE &&
14597 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14598 Opcode = Opc;
14599 }
14600
14601 if (Opc != Opcode)
14602 return SDValue();
14603
14604 EVT InVT = In.getOperand(0).getValueType();
14605
14606 // If all scalar values are typed differently, bail out. It's chosen to
14607 // simplify BUILD_VECTOR of integer types.
14608 if (SrcVT == MVT::Other)
14609 SrcVT = InVT;
14610 if (SrcVT != InVT)
14611 return SDValue();
14612 NumDefs++;
14613 }
14614
14615 // If the vector has just one element defined, it's not worth to fold it into
14616 // a vectorized one.
14617 if (NumDefs < 2)
14618 return SDValue();
14619
14620 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)(static_cast <bool> ((Opcode == ISD::UINT_TO_FP || Opcode
== ISD::SINT_TO_FP) && "Should only handle conversion from integer to float."
) ? void (0) : __assert_fail ("(Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) && \"Should only handle conversion from integer to float.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14621, __extension__ __PRETTY_FUNCTION__))
14621 && "Should only handle conversion from integer to float.")(static_cast <bool> ((Opcode == ISD::UINT_TO_FP || Opcode
== ISD::SINT_TO_FP) && "Should only handle conversion from integer to float."
) ? void (0) : __assert_fail ("(Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) && \"Should only handle conversion from integer to float.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14621, __extension__ __PRETTY_FUNCTION__))
;
14622 assert(SrcVT != MVT::Other && "Cannot determine source type!")(static_cast <bool> (SrcVT != MVT::Other && "Cannot determine source type!"
) ? void (0) : __assert_fail ("SrcVT != MVT::Other && \"Cannot determine source type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14622, __extension__ __PRETTY_FUNCTION__))
;
14623
14624 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14625
14626 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14627 return SDValue();
14628
14629 // Just because the floating-point vector type is legal does not necessarily
14630 // mean that the corresponding integer vector type is.
14631 if (!isTypeLegal(NVT))
14632 return SDValue();
14633
14634 SmallVector<SDValue, 8> Opnds;
14635 for (unsigned i = 0; i != NumInScalars; ++i) {
14636 SDValue In = N->getOperand(i);
14637
14638 if (In.isUndef())
14639 Opnds.push_back(DAG.getUNDEF(SrcVT));
14640 else
14641 Opnds.push_back(In.getOperand(0));
14642 }
14643 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14644 AddToWorklist(BV.getNode());
14645
14646 return DAG.getNode(Opcode, DL, VT, BV);
14647}
14648
14649SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14650 ArrayRef<int> VectorMask,
14651 SDValue VecIn1, SDValue VecIn2,
14652 unsigned LeftIdx) {
14653 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14654 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14655
14656 EVT VT = N->getValueType(0);
14657 EVT InVT1 = VecIn1.getValueType();
14658 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14659
14660 unsigned Vec2Offset = 0;
14661 unsigned NumElems = VT.getVectorNumElements();
14662 unsigned ShuffleNumElems = NumElems;
14663
14664 // In case both the input vectors are extracted from same base
14665 // vector we do not need extra addend (Vec2Offset) while
14666 // computing shuffle mask.
14667 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14668 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14669 !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14670 Vec2Offset = InVT1.getVectorNumElements();
14671
14672 // We can't generate a shuffle node with mismatched input and output types.
14673 // Try to make the types match the type of the output.
14674 if (InVT1 != VT || InVT2 != VT) {
14675 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14676 // If the output vector length is a multiple of both input lengths,
14677 // we can concatenate them and pad the rest with undefs.
14678 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14679 assert(NumConcats >= 2 && "Concat needs at least two inputs!")(static_cast <bool> (NumConcats >= 2 && "Concat needs at least two inputs!"
) ? void (0) : __assert_fail ("NumConcats >= 2 && \"Concat needs at least two inputs!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14679, __extension__ __PRETTY_FUNCTION__))
;
14680 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14681 ConcatOps[0] = VecIn1;
14682 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14683 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14684 VecIn2 = SDValue();
14685 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14686 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14687 return SDValue();
14688
14689 if (!VecIn2.getNode()) {
14690 // If we only have one input vector, and it's twice the size of the
14691 // output, split it in two.
14692 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14693 DAG.getConstant(NumElems, DL, IdxTy));
14694 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14695 // Since we now have shorter input vectors, adjust the offset of the
14696 // second vector's start.
14697 Vec2Offset = NumElems;
14698 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14699 // VecIn1 is wider than the output, and we have another, possibly
14700 // smaller input. Pad the smaller input with undefs, shuffle at the
14701 // input vector width, and extract the output.
14702 // The shuffle type is different than VT, so check legality again.
14703 if (LegalOperations &&
14704 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14705 return SDValue();
14706
14707 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14708 // lower it back into a BUILD_VECTOR. So if the inserted type is
14709 // illegal, don't even try.
14710 if (InVT1 != InVT2) {
14711 if (!TLI.isTypeLegal(InVT2))
14712 return SDValue();
14713 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14714 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14715 }
14716 ShuffleNumElems = NumElems * 2;
14717 } else {
14718 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14719 // than VecIn1. We can't handle this for now - this case will disappear
14720 // when we start sorting the vectors by type.
14721 return SDValue();
14722 }
14723 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14724 InVT1.getSizeInBits() == VT.getSizeInBits()) {
14725 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14726 ConcatOps[0] = VecIn2;
14727 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14728 } else {
14729 // TODO: Support cases where the length mismatch isn't exactly by a
14730 // factor of 2.
14731 // TODO: Move this check upwards, so that if we have bad type
14732 // mismatches, we don't create any DAG nodes.
14733 return SDValue();
14734 }
14735 }
14736
14737 // Initialize mask to undef.
14738 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14739
14740 // Only need to run up to the number of elements actually used, not the
14741 // total number of elements in the shuffle - if we are shuffling a wider
14742 // vector, the high lanes should be set to undef.
14743 for (unsigned i = 0; i != NumElems; ++i) {
14744 if (VectorMask[i] <= 0)
14745 continue;
14746
14747 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14748 if (VectorMask[i] == (int)LeftIdx) {
14749 Mask[i] = ExtIndex;
14750 } else if (VectorMask[i] == (int)LeftIdx + 1) {
14751 Mask[i] = Vec2Offset + ExtIndex;
14752 }
14753 }
14754
14755 // The type the input vectors may have changed above.
14756 InVT1 = VecIn1.getValueType();
14757
14758 // If we already have a VecIn2, it should have the same type as VecIn1.
14759 // If we don't, get an undef/zero vector of the appropriate type.
14760 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14761 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.")(static_cast <bool> (InVT1 == VecIn2.getValueType() &&
"Unexpected second input type.") ? void (0) : __assert_fail (
"InVT1 == VecIn2.getValueType() && \"Unexpected second input type.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 14761, __extension__ __PRETTY_FUNCTION__))
;
14762
14763 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14764 if (ShuffleNumElems > NumElems)
14765 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14766
14767 return Shuffle;
14768}
14769
14770// Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14771// operations. If the types of the vectors we're extracting from allow it,
14772// turn this into a vector_shuffle node.
14773SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14774 SDLoc DL(N);
14775 EVT VT = N->getValueType(0);
14776
14777 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14778 if (!isTypeLegal(VT))
14779 return SDValue();
14780
14781 // May only combine to shuffle after legalize if shuffle is legal.
14782 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14783 return SDValue();
14784
14785 bool UsesZeroVector = false;
14786 unsigned NumElems = N->getNumOperands();
14787
14788 // Record, for each element of the newly built vector, which input vector
14789 // that element comes from. -1 stands for undef, 0 for the zero vector,
14790 // and positive values for the input vectors.
14791 // VectorMask maps each element to its vector number, and VecIn maps vector
14792 // numbers to their initial SDValues.
14793
14794 SmallVector<int, 8> VectorMask(NumElems, -1);
14795 SmallVector<SDValue, 8> VecIn;
14796 VecIn.push_back(SDValue());
14797
14798 for (unsigned i = 0; i != NumElems; ++i) {
14799 SDValue Op = N->getOperand(i);
14800
14801 if (Op.isUndef())
14802 continue;
14803
14804 // See if we can use a blend with a zero vector.
14805 // TODO: Should we generalize this to a blend with an arbitrary constant
14806 // vector?
14807 if (isNullConstant(Op) || isNullFPConstant(Op)) {
14808 UsesZeroVector = true;
14809 VectorMask[i] = 0;
14810 continue;
14811 }
14812
14813 // Not an undef or zero. If the input is something other than an
14814 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
14815 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14816 !isa<ConstantSDNode>(Op.getOperand(1)))
14817 return SDValue();
14818 SDValue ExtractedFromVec = Op.getOperand(0);
14819
14820 APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
14821 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
14822 return SDValue();
14823
14824 // All inputs must have the same element type as the output.
14825 if (VT.getVectorElementType() !=
14826 ExtractedFromVec.getValueType().getVectorElementType())
14827 return SDValue();
14828
14829 // Have we seen this input vector before?
14830 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14831 // a map back from SDValues to numbers isn't worth it.
14832 unsigned Idx = std::distance(
14833 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14834 if (Idx == VecIn.size())
14835 VecIn.push_back(ExtractedFromVec);
14836
14837 VectorMask[i] = Idx;
14838 }
14839
14840 // If we didn't find at least one input vector, bail out.
14841 if (VecIn.size() < 2)
14842 return SDValue();
14843
14844 // If all the Operands of BUILD_VECTOR extract from same
14845 // vector, then split the vector efficiently based on the maximum
14846 // vector access index and adjust the VectorMask and
14847 // VecIn accordingly.
14848 if (VecIn.size() == 2) {
14849 unsigned MaxIndex = 0;
14850 unsigned NearestPow2 = 0;
14851 SDValue Vec = VecIn.back();
14852 EVT InVT = Vec.getValueType();
14853 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14854 SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14855
14856 for (unsigned i = 0; i < NumElems; i++) {
14857 if (VectorMask[i] <= 0)
14858 continue;
14859 unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14860 IndexVec[i] = Index;
14861 MaxIndex = std::max(MaxIndex, Index);
14862 }
14863
14864 NearestPow2 = PowerOf2Ceil(MaxIndex);
14865 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14866 NumElems * 2 < NearestPow2) {
14867 unsigned SplitSize = NearestPow2 / 2;
14868 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14869 InVT.getVectorElementType(), SplitSize);
14870 if (TLI.isTypeLegal(SplitVT)) {
14871 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14872 DAG.getConstant(SplitSize, DL, IdxTy));
14873 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14874 DAG.getConstant(0, DL, IdxTy));
14875 VecIn.pop_back();
14876 VecIn.push_back(VecIn1);
14877 VecIn.push_back(VecIn2);
14878
14879 for (unsigned i = 0; i < NumElems; i++) {
14880 if (VectorMask[i] <= 0)
14881 continue;
14882 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14883 }
14884 }
14885 }
14886 }
14887
14888 // TODO: We want to sort the vectors by descending length, so that adjacent
14889 // pairs have similar length, and the longer vector is always first in the
14890 // pair.
14891
14892 // TODO: Should this fire if some of the input vectors has illegal type (like
14893 // it does now), or should we let legalization run its course first?
14894
14895 // Shuffle phase:
14896 // Take pairs of vectors, and shuffle them so that the result has elements
14897 // from these vectors in the correct places.
14898 // For example, given:
14899 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14900 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14901 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14902 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14903 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14904 // We will generate:
14905 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14906 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14907 SmallVector<SDValue, 4> Shuffles;
14908 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14909 unsigned LeftIdx = 2 * In + 1;
14910 SDValue VecLeft = VecIn[LeftIdx];
14911 SDValue VecRight =
14912 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14913
14914 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14915 VecRight, LeftIdx))
14916 Shuffles.push_back(Shuffle);
14917 else
14918 return SDValue();
14919 }
14920
14921 // If we need the zero vector as an "ingredient" in the blend tree, add it
14922 // to the list of shuffles.
14923 if (UsesZeroVector)
14924 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14925 : DAG.getConstantFP(0.0, DL, VT));
14926
14927 // If we only have one shuffle, we're done.
14928 if (Shuffles.size() == 1)
14929 return Shuffles[0];
14930
14931 // Update the vector mask to point to the post-shuffle vectors.
14932 for (int &Vec : VectorMask)
14933 if (Vec == 0)
14934 Vec = Shuffles.size() - 1;
14935 else
14936 Vec = (Vec - 1) / 2;
14937
14938 // More than one shuffle. Generate a binary tree of blends, e.g. if from
14939 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14940 // generate:
14941 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14942 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14943 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14944 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14945 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14946 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14947 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14948
14949 // Make sure the initial size of the shuffle list is even.
14950 if (Shuffles.size() % 2)
14951 Shuffles.push_back(DAG.getUNDEF(VT));
14952
14953 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14954 if (CurSize % 2) {
14955 Shuffles[CurSize] = DAG.getUNDEF(VT);
14956 CurSize++;
14957 }
14958 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14959 int Left = 2 * In;
14960 int Right = 2 * In + 1;
14961 SmallVector<int, 8> Mask(NumElems, -1);
14962 for (unsigned i = 0; i != NumElems; ++i) {
14963 if (VectorMask[i] == Left) {
14964 Mask[i] = i;
14965 VectorMask[i] = In;
14966 } else if (VectorMask[i] == Right) {
14967 Mask[i] = i + NumElems;
14968 VectorMask[i] = In;
14969 }
14970 }
14971
14972 Shuffles[In] =
14973 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14974 }
14975 }
14976 return Shuffles[0];
14977}
14978
14979SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14980 EVT VT = N->getValueType(0);
14981
14982 // A vector built entirely of undefs is undef.
14983 if (ISD::allOperandsUndef(N))
14984 return DAG.getUNDEF(VT);
14985
14986 // If this is a splat of a bitcast from another vector, change to a
14987 // concat_vector.
14988 // For example:
14989 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
14990 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
14991 //
14992 // If X is a build_vector itself, the concat can become a larger build_vector.
14993 // TODO: Maybe this is useful for non-splat too?
14994 if (!LegalOperations) {
14995 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
14996 Splat = peekThroughBitcast(Splat);
14997 EVT SrcVT = Splat.getValueType();
14998 if (SrcVT.isVector()) {
14999 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
15000 EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
15001 SrcVT.getVectorElementType(), NumElts);
15002 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
15003 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), NewVT, Ops);
15004 return DAG.getBitcast(VT, Concat);
15005 }
15006 }
15007 }
15008
15009 // Check if we can express BUILD VECTOR via subvector extract.
15010 if (!LegalTypes && (N->getNumOperands() > 1)) {
15011 SDValue Op0 = N->getOperand(0);
15012 auto checkElem = [&](SDValue Op) -> uint64_t {
15013 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
15014 (Op0.getOperand(0) == Op.getOperand(0)))
15015 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
15016 return CNode->getZExtValue();
15017 return -1;
15018 };
15019
15020 int Offset = checkElem(Op0);
15021 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
15022 if (Offset + i != checkElem(N->getOperand(i))) {
15023 Offset = -1;
15024 break;
15025 }
15026 }
15027
15028 if ((Offset == 0) &&
15029 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
15030 return Op0.getOperand(0);
15031 if ((Offset != -1) &&
15032 ((Offset % N->getValueType(0).getVectorNumElements()) ==
15033 0)) // IDX must be multiple of output size.
15034 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
15035 Op0.getOperand(0), Op0.getOperand(1));
15036 }
15037
15038 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
15039 return V;
15040
15041 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
15042 return V;
15043
15044 if (SDValue V = reduceBuildVecToShuffle(N))
15045 return V;
15046
15047 return SDValue();
15048}
15049
15050static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
15051 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15052 EVT OpVT = N->getOperand(0).getValueType();
15053
15054 // If the operands are legal vectors, leave them alone.
15055 if (TLI.isTypeLegal(OpVT))
15056 return SDValue();
15057
15058 SDLoc DL(N);
15059 EVT VT = N->getValueType(0);
15060 SmallVector<SDValue, 8> Ops;
15061
15062 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
15063 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15064
15065 // Keep track of what we encounter.
15066 bool AnyInteger = false;
15067 bool AnyFP = false;
15068 for (const SDValue &Op : N->ops()) {
15069 if (ISD::BITCAST == Op.getOpcode() &&
15070 !Op.getOperand(0).getValueType().isVector())
15071 Ops.push_back(Op.getOperand(0));
15072 else if (ISD::UNDEF == Op.getOpcode())
15073 Ops.push_back(ScalarUndef);
15074 else
15075 return SDValue();
15076
15077 // Note whether we encounter an integer or floating point scalar.
15078 // If it's neither, bail out, it could be something weird like x86mmx.
15079 EVT LastOpVT = Ops.back().getValueType();
15080 if (LastOpVT.isFloatingPoint())
15081 AnyFP = true;
15082 else if (LastOpVT.isInteger())
15083 AnyInteger = true;
15084 else
15085 return SDValue();
15086 }
15087
15088 // If any of the operands is a floating point scalar bitcast to a vector,
15089 // use floating point types throughout, and bitcast everything.
15090 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
15091 if (AnyFP) {
15092 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
15093 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15094 if (AnyInteger) {
15095 for (SDValue &Op : Ops) {
15096 if (Op.getValueType() == SVT)
15097 continue;
15098 if (Op.isUndef())
15099 Op = ScalarUndef;
15100 else
15101 Op = DAG.getBitcast(SVT, Op);
15102 }
15103 }
15104 }
15105
15106 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15107 VT.getSizeInBits() / SVT.getSizeInBits());
15108 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15109}
15110
15111// Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15112// operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15113// most two distinct vectors the same size as the result, attempt to turn this
15114// into a legal shuffle.
15115static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15116 EVT VT = N->getValueType(0);
15117 EVT OpVT = N->getOperand(0).getValueType();
15118 int NumElts = VT.getVectorNumElements();
15119 int NumOpElts = OpVT.getVectorNumElements();
15120
15121 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15122 SmallVector<int, 8> Mask;
15123
15124 for (SDValue Op : N->ops()) {
15125 // Peek through any bitcast.
15126 Op = peekThroughBitcast(Op);
15127
15128 // UNDEF nodes convert to UNDEF shuffle mask values.
15129 if (Op.isUndef()) {
15130 Mask.append((unsigned)NumOpElts, -1);
15131 continue;
15132 }
15133
15134 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15135 return SDValue();
15136
15137 // What vector are we extracting the subvector from and at what index?
15138 SDValue ExtVec = Op.getOperand(0);
15139
15140 // We want the EVT of the original extraction to correctly scale the
15141 // extraction index.
15142 EVT ExtVT = ExtVec.getValueType();
15143
15144 // Peek through any bitcast.
15145 ExtVec = peekThroughBitcast(ExtVec);
15146
15147 // UNDEF nodes convert to UNDEF shuffle mask values.
15148 if (ExtVec.isUndef()) {
15149 Mask.append((unsigned)NumOpElts, -1);
15150 continue;
15151 }
15152
15153 if (!isa<ConstantSDNode>(Op.getOperand(1)))
15154 return SDValue();
15155 int ExtIdx = Op.getConstantOperandVal(1);
15156
15157 // Ensure that we are extracting a subvector from a vector the same
15158 // size as the result.
15159 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15160 return SDValue();
15161
15162 // Scale the subvector index to account for any bitcast.
15163 int NumExtElts = ExtVT.getVectorNumElements();
15164 if (0 == (NumExtElts % NumElts))
15165 ExtIdx /= (NumExtElts / NumElts);
15166 else if (0 == (NumElts % NumExtElts))
15167 ExtIdx *= (NumElts / NumExtElts);
15168 else
15169 return SDValue();
15170
15171 // At most we can reference 2 inputs in the final shuffle.
15172 if (SV0.isUndef() || SV0 == ExtVec) {
15173 SV0 = ExtVec;
15174 for (int i = 0; i != NumOpElts; ++i)
15175 Mask.push_back(i + ExtIdx);
15176 } else if (SV1.isUndef() || SV1 == ExtVec) {
15177 SV1 = ExtVec;
15178 for (int i = 0; i != NumOpElts; ++i)
15179 Mask.push_back(i + ExtIdx + NumElts);
15180 } else {
15181 return SDValue();
15182 }
15183 }
15184
15185 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15186 return SDValue();
15187
15188 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15189 DAG.getBitcast(VT, SV1), Mask);
15190}
15191
15192SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15193 // If we only have one input vector, we don't need to do any concatenation.
15194 if (N->getNumOperands() == 1)
15195 return N->getOperand(0);
15196
15197 // Check if all of the operands are undefs.
15198 EVT VT = N->getValueType(0);
15199 if (ISD::allOperandsUndef(N))
15200 return DAG.getUNDEF(VT);
15201
15202 // Optimize concat_vectors where all but the first of the vectors are undef.
15203 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15204 return Op.isUndef();
15205 })) {
15206 SDValue In = N->getOperand(0);
15207 assert(In.getValueType().isVector() && "Must concat vectors")(static_cast <bool> (In.getValueType().isVector() &&
"Must concat vectors") ? void (0) : __assert_fail ("In.getValueType().isVector() && \"Must concat vectors\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15207, __extension__ __PRETTY_FUNCTION__))
;
15208
15209 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15210 if (In->getOpcode() == ISD::BITCAST &&
15211 !In->getOperand(0).getValueType().isVector()) {
15212 SDValue Scalar = In->getOperand(0);
15213
15214 // If the bitcast type isn't legal, it might be a trunc of a legal type;
15215 // look through the trunc so we can still do the transform:
15216 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15217 if (Scalar->getOpcode() == ISD::TRUNCATE &&
15218 !TLI.isTypeLegal(Scalar.getValueType()) &&
15219 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15220 Scalar = Scalar->getOperand(0);
15221
15222 EVT SclTy = Scalar->getValueType(0);
15223
15224 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15225 return SDValue();
15226
15227 // Bail out if the vector size is not a multiple of the scalar size.
15228 if (VT.getSizeInBits() % SclTy.getSizeInBits())
15229 return SDValue();
15230
15231 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15232 if (VNTNumElms < 2)
15233 return SDValue();
15234
15235 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15236 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15237 return SDValue();
15238
15239 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15240 return DAG.getBitcast(VT, Res);
15241 }
15242 }
15243
15244 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15245 // We have already tested above for an UNDEF only concatenation.
15246 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15247 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15248 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15249 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15250 };
15251 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15252 SmallVector<SDValue, 8> Opnds;
15253 EVT SVT = VT.getScalarType();
15254
15255 EVT MinVT = SVT;
15256 if (!SVT.isFloatingPoint()) {
15257 // If BUILD_VECTOR are from built from integer, they may have different
15258 // operand types. Get the smallest type and truncate all operands to it.
15259 bool FoundMinVT = false;
15260 for (const SDValue &Op : N->ops())
15261 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15262 EVT OpSVT = Op.getOperand(0).getValueType();
15263 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15264 FoundMinVT = true;
15265 }
15266 assert(FoundMinVT && "Concat vector type mismatch")(static_cast <bool> (FoundMinVT && "Concat vector type mismatch"
) ? void (0) : __assert_fail ("FoundMinVT && \"Concat vector type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15266, __extension__ __PRETTY_FUNCTION__))
;
15267 }
15268
15269 for (const SDValue &Op : N->ops()) {
15270 EVT OpVT = Op.getValueType();
15271 unsigned NumElts = OpVT.getVectorNumElements();
15272
15273 if (ISD::UNDEF == Op.getOpcode())
15274 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15275
15276 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15277 if (SVT.isFloatingPoint()) {
15278 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch")(static_cast <bool> (SVT == OpVT.getScalarType() &&
"Concat vector type mismatch") ? void (0) : __assert_fail ("SVT == OpVT.getScalarType() && \"Concat vector type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15278, __extension__ __PRETTY_FUNCTION__))
;
15279 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15280 } else {
15281 for (unsigned i = 0; i != NumElts; ++i)
15282 Opnds.push_back(
15283 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15284 }
15285 }
15286 }
15287
15288 assert(VT.getVectorNumElements() == Opnds.size() &&(static_cast <bool> (VT.getVectorNumElements() == Opnds
.size() && "Concat vector type mismatch") ? void (0) :
__assert_fail ("VT.getVectorNumElements() == Opnds.size() && \"Concat vector type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15289, __extension__ __PRETTY_FUNCTION__))
15289 "Concat vector type mismatch")(static_cast <bool> (VT.getVectorNumElements() == Opnds
.size() && "Concat vector type mismatch") ? void (0) :
__assert_fail ("VT.getVectorNumElements() == Opnds.size() && \"Concat vector type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15289, __extension__ __PRETTY_FUNCTION__))
;
15290 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15291 }
15292
15293 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15294 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15295 return V;
15296
15297 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15298 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15299 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15300 return V;
15301
15302 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15303 // nodes often generate nop CONCAT_VECTOR nodes.
15304 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15305 // place the incoming vectors at the exact same location.
15306 SDValue SingleSource = SDValue();
15307 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15308
15309 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15310 SDValue Op = N->getOperand(i);
15311
15312 if (Op.isUndef())
15313 continue;
15314
15315 // Check if this is the identity extract:
15316 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15317 return SDValue();
15318
15319 // Find the single incoming vector for the extract_subvector.
15320 if (SingleSource.getNode()) {
15321 if (Op.getOperand(0) != SingleSource)
15322 return SDValue();
15323 } else {
15324 SingleSource = Op.getOperand(0);
15325
15326 // Check the source type is the same as the type of the result.
15327 // If not, this concat may extend the vector, so we can not
15328 // optimize it away.
15329 if (SingleSource.getValueType() != N->getValueType(0))
15330 return SDValue();
15331 }
15332
15333 unsigned IdentityIndex = i * PartNumElem;
15334 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15335 // The extract index must be constant.
15336 if (!CS)
15337 return SDValue();
15338
15339 // Check that we are reading from the identity index.
15340 if (CS->getZExtValue() != IdentityIndex)
15341 return SDValue();
15342 }
15343
15344 if (SingleSource.getNode())
15345 return SingleSource;
15346
15347 return SDValue();
15348}
15349
15350/// If we are extracting a subvector produced by a wide binary operator with at
15351/// at least one operand that was the result of a vector concatenation, then try
15352/// to use the narrow vector operands directly to avoid the concatenation and
15353/// extraction.
15354static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15355 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15356 // some of these bailouts with other transforms.
15357
15358 // The extract index must be a constant, so we can map it to a concat operand.
15359 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15360 if (!ExtractIndex)
15361 return SDValue();
15362
15363 // Only handle the case where we are doubling and then halving. A larger ratio
15364 // may require more than two narrow binops to replace the wide binop.
15365 EVT VT = Extract->getValueType(0);
15366 unsigned NumElems = VT.getVectorNumElements();
15367 assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&(static_cast <bool> ((ExtractIndex->getZExtValue() %
NumElems) == 0 && "Extract index is not a multiple of the vector length."
) ? void (0) : __assert_fail ("(ExtractIndex->getZExtValue() % NumElems) == 0 && \"Extract index is not a multiple of the vector length.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15368, __extension__ __PRETTY_FUNCTION__))
15368 "Extract index is not a multiple of the vector length.")(static_cast <bool> ((ExtractIndex->getZExtValue() %
NumElems) == 0 && "Extract index is not a multiple of the vector length."
) ? void (0) : __assert_fail ("(ExtractIndex->getZExtValue() % NumElems) == 0 && \"Extract index is not a multiple of the vector length.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15368, __extension__ __PRETTY_FUNCTION__))
;
15369 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15370 return SDValue();
15371
15372 // We are looking for an optionally bitcasted wide vector binary operator
15373 // feeding an extract subvector.
15374 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15375
15376 // TODO: The motivating case for this transform is an x86 AVX1 target. That
15377 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15378 // flavors, but no other 256-bit integer support. This could be extended to
15379 // handle any binop, but that may require fixing/adding other folds to avoid
15380 // codegen regressions.
15381 unsigned BOpcode = BinOp.getOpcode();
15382 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15383 return SDValue();
15384
15385 // The binop must be a vector type, so we can chop it in half.
15386 EVT WideBVT = BinOp.getValueType();
15387 if (!WideBVT.isVector())
15388 return SDValue();
15389
15390 // Bail out if the target does not support a narrower version of the binop.
15391 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15392 WideBVT.getVectorNumElements() / 2);
15393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15394 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15395 return SDValue();
15396
15397 // Peek through bitcasts of the binary operator operands if needed.
15398 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15399 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15400
15401 // We need at least one concatenation operation of a binop operand to make
15402 // this transform worthwhile. The concat must double the input vector sizes.
15403 // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15404 bool ConcatL =
15405 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15406 bool ConcatR =
15407 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15408 if (!ConcatL && !ConcatR)
15409 return SDValue();
15410
15411 // If one of the binop operands was not the result of a concat, we must
15412 // extract a half-sized operand for our new narrow binop. We can't just reuse
15413 // the original extract index operand because we may have bitcasted.
15414 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15415 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15416 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15417 SDLoc DL(Extract);
15418
15419 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15420 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15421 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15422 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15423 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15424 BinOp.getOperand(0),
15425 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15426
15427 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15428 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15429 BinOp.getOperand(1),
15430 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15431
15432 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15433 return DAG.getBitcast(VT, NarrowBinOp);
15434}
15435
15436/// If we are extracting a subvector from a wide vector load, convert to a
15437/// narrow load to eliminate the extraction:
15438/// (extract_subvector (load wide vector)) --> (load narrow vector)
15439static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15440 // TODO: Add support for big-endian. The offset calculation must be adjusted.
15441 if (DAG.getDataLayout().isBigEndian())
15442 return SDValue();
15443
15444 // TODO: The one-use check is overly conservative. Check the cost of the
15445 // extract instead or remove that condition entirely.
15446 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15447 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15448 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15449 !ExtIdx)
15450 return SDValue();
15451
15452 // The narrow load will be offset from the base address of the old load if
15453 // we are extracting from something besides index 0 (little-endian).
15454 EVT VT = Extract->getValueType(0);
15455 SDLoc DL(Extract);
15456 SDValue BaseAddr = Ld->getOperand(1);
15457 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15458
15459 // TODO: Use "BaseIndexOffset" to make this more effective.
15460 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15461 MachineFunction &MF = DAG.getMachineFunction();
15462 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15463 VT.getStoreSize());
15464 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15465 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15466 return NewLd;
15467}
15468
15469SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15470 EVT NVT = N->getValueType(0);
15471 SDValue V = N->getOperand(0);
15472
15473 // Extract from UNDEF is UNDEF.
15474 if (V.isUndef())
15475 return DAG.getUNDEF(NVT);
15476
15477 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15478 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15479 return NarrowLoad;
15480
15481 // Combine:
15482 // (extract_subvec (concat V1, V2, ...), i)
15483 // Into:
15484 // Vi if possible
15485 // Only operand 0 is checked as 'concat' assumes all inputs of the same
15486 // type.
15487 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15488 isa<ConstantSDNode>(N->getOperand(1)) &&
15489 V->getOperand(0).getValueType() == NVT) {
15490 unsigned Idx = N->getConstantOperandVal(1);
15491 unsigned NumElems = NVT.getVectorNumElements();
15492 assert((Idx % NumElems) == 0 &&(static_cast <bool> ((Idx % NumElems) == 0 && "IDX in concat is not a multiple of the result vector length."
) ? void (0) : __assert_fail ("(Idx % NumElems) == 0 && \"IDX in concat is not a multiple of the result vector length.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15493, __extension__ __PRETTY_FUNCTION__))
15493 "IDX in concat is not a multiple of the result vector length.")(static_cast <bool> ((Idx % NumElems) == 0 && "IDX in concat is not a multiple of the result vector length."
) ? void (0) : __assert_fail ("(Idx % NumElems) == 0 && \"IDX in concat is not a multiple of the result vector length.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15493, __extension__ __PRETTY_FUNCTION__))
;
15494 return V->getOperand(Idx / NumElems);
15495 }
15496
15497 // Skip bitcasting
15498 V = peekThroughBitcast(V);
15499
15500 // If the input is a build vector. Try to make a smaller build vector.
15501 if (V->getOpcode() == ISD::BUILD_VECTOR) {
15502 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15503 EVT InVT = V->getValueType(0);
15504 unsigned ExtractSize = NVT.getSizeInBits();
15505 unsigned EltSize = InVT.getScalarSizeInBits();
15506 // Only do this if we won't split any elements.
15507 if (ExtractSize % EltSize == 0) {
15508 unsigned NumElems = ExtractSize / EltSize;
15509 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15510 InVT.getVectorElementType(), NumElems);
15511 if ((!LegalOperations ||
15512 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15513 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15514 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15515 EltSize;
15516
15517 // Extract the pieces from the original build_vector.
15518 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15519 makeArrayRef(V->op_begin() + IdxVal,
15520 NumElems));
15521 return DAG.getBitcast(NVT, BuildVec);
15522 }
15523 }
15524 }
15525 }
15526
15527 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15528 // Handle only simple case where vector being inserted and vector
15529 // being extracted are of same size.
15530 EVT SmallVT = V->getOperand(1).getValueType();
15531 if (!NVT.bitsEq(SmallVT))
15532 return SDValue();
15533
15534 // Only handle cases where both indexes are constants.
15535 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15536 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15537
15538 if (InsIdx && ExtIdx) {
15539 // Combine:
15540 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15541 // Into:
15542 // indices are equal or bit offsets are equal => V1
15543 // otherwise => (extract_subvec V1, ExtIdx)
15544 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15545 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15546 return DAG.getBitcast(NVT, V->getOperand(1));
15547 return DAG.getNode(
15548 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15549 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15550 N->getOperand(1));
15551 }
15552 }
15553
15554 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15555 return NarrowBOp;
15556
15557 return SDValue();
15558}
15559
15560static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15561 SDValue V, SelectionDAG &DAG) {
15562 SDLoc DL(V);
15563 EVT VT = V.getValueType();
15564
15565 switch (V.getOpcode()) {
15566 default:
15567 return V;
15568
15569 case ISD::CONCAT_VECTORS: {
15570 EVT OpVT = V->getOperand(0).getValueType();
15571 int OpSize = OpVT.getVectorNumElements();
15572 SmallBitVector OpUsedElements(OpSize, false);
15573 bool FoundSimplification = false;
15574 SmallVector<SDValue, 4> NewOps;
15575 NewOps.reserve(V->getNumOperands());
15576 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15577 SDValue Op = V->getOperand(i);
15578 bool OpUsed = false;
15579 for (int j = 0; j < OpSize; ++j)
15580 if (UsedElements[i * OpSize + j]) {
15581 OpUsedElements[j] = true;
15582 OpUsed = true;
15583 }
15584 NewOps.push_back(
15585 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15586 : DAG.getUNDEF(OpVT));
15587 FoundSimplification |= Op == NewOps.back();
15588 OpUsedElements.reset();
15589 }
15590 if (FoundSimplification)
15591 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15592 return V;
15593 }
15594
15595 case ISD::INSERT_SUBVECTOR: {
15596 SDValue BaseV = V->getOperand(0);
15597 SDValue SubV = V->getOperand(1);
15598 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15599 if (!IdxN)
15600 return V;
15601
15602 int SubSize = SubV.getValueType().getVectorNumElements();
15603 int Idx = IdxN->getZExtValue();
15604 bool SubVectorUsed = false;
15605 SmallBitVector SubUsedElements(SubSize, false);
15606 for (int i = 0; i < SubSize; ++i)
15607 if (UsedElements[i + Idx]) {
15608 SubVectorUsed = true;
15609 SubUsedElements[i] = true;
15610 UsedElements[i + Idx] = false;
15611 }
15612
15613 // Now recurse on both the base and sub vectors.
15614 SDValue SimplifiedSubV =
15615 SubVectorUsed
15616 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15617 : DAG.getUNDEF(SubV.getValueType());
15618 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15619 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15620 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15621 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15622 return V;
15623 }
15624 }
15625}
15626
15627static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15628 SDValue N1, SelectionDAG &DAG) {
15629 EVT VT = SVN->getValueType(0);
15630 int NumElts = VT.getVectorNumElements();
15631 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
9
Calling constructor for 'SmallBitVector'
13
Returning from constructor for 'SmallBitVector'
15632 for (int M : SVN->getMask())
14
Assuming '__begin' is equal to '__end'
15633 if (M >= 0 && M < NumElts)
15634 N0UsedElements[M] = true;
15635 else if (M >= NumElts)
15636 N1UsedElements[M - NumElts] = true;
15637
15638 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15639 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15640 if (S0 == N0 && S1 == N1)
15
Taking true branch
15641 return SDValue();
15642
15643 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15644}
16
Potential leak of memory pointed to by 'N0UsedElements.X'
15645
15646static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15647 SDValue N1, SelectionDAG &DAG) {
15648 auto isUndefElt = [](SDValue V, int Idx) {
15649 // TODO - handle more cases as required.
15650 if (V.getOpcode() == ISD::BUILD_VECTOR)
15651 return V.getOperand(Idx).isUndef();
15652 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
15653 return (Idx != 0) || V.getOperand(0).isUndef();
15654 return false;
15655 };
15656
15657 EVT VT = SVN->getValueType(0);
15658 unsigned NumElts = VT.getVectorNumElements();
15659
15660 bool Changed = false;
15661 SmallVector<int, 8> NewMask;
15662 for (unsigned i = 0; i != NumElts; ++i) {
15663 int Idx = SVN->getMaskElt(i);
15664 if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15665 ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15666 Changed = true;
15667 Idx = -1;
15668 }
15669 NewMask.push_back(Idx);
15670 }
15671 if (Changed)
15672 return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15673
15674 return SDValue();
15675}
15676
15677// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15678// or turn a shuffle of a single concat into simpler shuffle then concat.
15679static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15680 EVT VT = N->getValueType(0);
15681 unsigned NumElts = VT.getVectorNumElements();
15682
15683 SDValue N0 = N->getOperand(0);
15684 SDValue N1 = N->getOperand(1);
15685 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15686
15687 SmallVector<SDValue, 4> Ops;
15688 EVT ConcatVT = N0.getOperand(0).getValueType();
15689 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15690 unsigned NumConcats = NumElts / NumElemsPerConcat;
15691
15692 // Special case: shuffle(concat(A,B)) can be more efficiently represented
15693 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15694 // half vector elements.
15695 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15696 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15697 SVN->getMask().end(), [](int i) { return i == -1; })) {
15698 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15699 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15700 N1 = DAG.getUNDEF(ConcatVT);
15701 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15702 }
15703
15704 // Look at every vector that's inserted. We're looking for exact
15705 // subvector-sized copies from a concatenated vector
15706 for (unsigned I = 0; I != NumConcats; ++I) {
15707 // Make sure we're dealing with a copy.
15708 unsigned Begin = I * NumElemsPerConcat;
15709 bool AllUndef = true, NoUndef = true;
15710 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15711 if (SVN->getMaskElt(J) >= 0)
15712 AllUndef = false;
15713 else
15714 NoUndef = false;
15715 }
15716
15717 if (NoUndef) {
15718 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15719 return SDValue();
15720
15721 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15722 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15723 return SDValue();
15724
15725 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15726 if (FirstElt < N0.getNumOperands())
15727 Ops.push_back(N0.getOperand(FirstElt));
15728 else
15729 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15730
15731 } else if (AllUndef) {
15732 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15733 } else { // Mixed with general masks and undefs, can't do optimization.
15734 return SDValue();
15735 }
15736 }
15737
15738 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15739}
15740
15741// Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15742// BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15743//
15744// SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15745// a simplification in some sense, but it isn't appropriate in general: some
15746// BUILD_VECTORs are substantially cheaper than others. The general case
15747// of a BUILD_VECTOR requires inserting each element individually (or
15748// performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15749// all constants is a single constant pool load. A BUILD_VECTOR where each
15750// element is identical is a splat. A BUILD_VECTOR where most of the operands
15751// are undef lowers to a small number of element insertions.
15752//
15753// To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15754// We don't fold shuffles where one side is a non-zero constant, and we don't
15755// fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15756// non-constant operands. This seems to work out reasonably well in practice.
15757static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15758 SelectionDAG &DAG,
15759 const TargetLowering &TLI) {
15760 EVT VT = SVN->getValueType(0);
15761 unsigned NumElts = VT.getVectorNumElements();
15762 SDValue N0 = SVN->getOperand(0);
15763 SDValue N1 = SVN->getOperand(1);
15764
15765 if (!N0->hasOneUse() || !N1->hasOneUse())
15766 return SDValue();
15767
15768 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15769 // discussed above.
15770 if (!N1.isUndef()) {
15771 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15772 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15773 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15774 return SDValue();
15775 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15776 return SDValue();
15777 }
15778
15779 // If both inputs are splats of the same value then we can safely merge this
15780 // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
15781 bool IsSplat = false;
15782 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
15783 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
15784 if (BV0 && BV1)
15785 if (SDValue Splat0 = BV0->getSplatValue())
15786 IsSplat = (Splat0 == BV1->getSplatValue());
15787
15788 SmallVector<SDValue, 8> Ops;
15789 SmallSet<SDValue, 16> DuplicateOps;
15790 for (int M : SVN->getMask()) {
15791 SDValue Op = DAG.getUNDEF(VT.getScalarType());
15792 if (M >= 0) {
15793 int Idx = M < (int)NumElts ? M : M - NumElts;
15794 SDValue &S = (M < (int)NumElts ? N0 : N1);
15795 if (S.getOpcode() == ISD::BUILD_VECTOR) {
15796 Op = S.getOperand(Idx);
15797 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15798 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.")(static_cast <bool> (Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."
) ? void (0) : __assert_fail ("Idx == 0 && \"Unexpected SCALAR_TO_VECTOR operand index.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15798, __extension__ __PRETTY_FUNCTION__))
;
15799 Op = S.getOperand(0);
15800 } else {
15801 // Operand can't be combined - bail out.
15802 return SDValue();
15803 }
15804 }
15805
15806 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
15807 // generating a splat; semantically, this is fine, but it's likely to
15808 // generate low-quality code if the target can't reconstruct an appropriate
15809 // shuffle.
15810 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15811 if (!IsSplat && !DuplicateOps.insert(Op).second)
15812 return SDValue();
15813
15814 Ops.push_back(Op);
15815 }
15816
15817 // BUILD_VECTOR requires all inputs to be of the same type, find the
15818 // maximum type and extend them all.
15819 EVT SVT = VT.getScalarType();
15820 if (SVT.isInteger())
15821 for (SDValue &Op : Ops)
15822 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15823 if (SVT != VT.getScalarType())
15824 for (SDValue &Op : Ops)
15825 Op = TLI.isZExtFree(Op.getValueType(), SVT)
15826 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15827 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15828 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15829}
15830
15831// Match shuffles that can be converted to any_vector_extend_in_reg.
15832// This is often generated during legalization.
15833// e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15834// TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15835static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15836 SelectionDAG &DAG,
15837 const TargetLowering &TLI,
15838 bool LegalOperations,
15839 bool LegalTypes) {
15840 EVT VT = SVN->getValueType(0);
15841 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15842
15843 // TODO Add support for big-endian when we have a test case.
15844 if (!VT.isInteger() || IsBigEndian)
15845 return SDValue();
15846
15847 unsigned NumElts = VT.getVectorNumElements();
15848 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15849 ArrayRef<int> Mask = SVN->getMask();
15850 SDValue N0 = SVN->getOperand(0);
15851
15852 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15853 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15854 for (unsigned i = 0; i != NumElts; ++i) {
15855 if (Mask[i] < 0)
15856 continue;
15857 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15858 continue;
15859 return false;
15860 }
15861 return true;
15862 };
15863
15864 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15865 // power-of-2 extensions as they are the most likely.
15866 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15867 // Check for non power of 2 vector sizes
15868 if (NumElts % Scale != 0)
15869 continue;
15870 if (!isAnyExtend(Scale))
15871 continue;
15872
15873 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15874 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15875 if (!LegalTypes || TLI.isTypeLegal(OutVT))
15876 if (!LegalOperations ||
15877 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15878 return DAG.getBitcast(VT,
15879 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15880 }
15881
15882 return SDValue();
15883}
15884
15885// Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15886// each source element of a large type into the lowest elements of a smaller
15887// destination type. This is often generated during legalization.
15888// If the source node itself was a '*_extend_vector_inreg' node then we should
15889// then be able to remove it.
15890static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15891 SelectionDAG &DAG) {
15892 EVT VT = SVN->getValueType(0);
15893 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15894
15895 // TODO Add support for big-endian when we have a test case.
15896 if (!VT.isInteger() || IsBigEndian)
15897 return SDValue();
15898
15899 SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15900
15901 unsigned Opcode = N0.getOpcode();
15902 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15903 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15904 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15905 return SDValue();
15906
15907 SDValue N00 = N0.getOperand(0);
15908 ArrayRef<int> Mask = SVN->getMask();
15909 unsigned NumElts = VT.getVectorNumElements();
15910 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15911 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15912 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15913
15914 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15915 return SDValue();
15916 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15917
15918 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15919 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15920 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15921 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15922 for (unsigned i = 0; i != NumElts; ++i) {
15923 if (Mask[i] < 0)
15924 continue;
15925 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15926 continue;
15927 return false;
15928 }
15929 return true;
15930 };
15931
15932 // At the moment we just handle the case where we've truncated back to the
15933 // same size as before the extension.
15934 // TODO: handle more extension/truncation cases as cases arise.
15935 if (EltSizeInBits != ExtSrcSizeInBits)
15936 return SDValue();
15937
15938 // We can remove *extend_vector_inreg only if the truncation happens at
15939 // the same scale as the extension.
15940 if (isTruncate(ExtScale))
15941 return DAG.getBitcast(VT, N00);
15942
15943 return SDValue();
15944}
15945
15946// Combine shuffles of splat-shuffles of the form:
15947// shuffle (shuffle V, undef, splat-mask), undef, M
15948// If splat-mask contains undef elements, we need to be careful about
15949// introducing undef's in the folded mask which are not the result of composing
15950// the masks of the shuffles.
15951static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15952 ShuffleVectorSDNode *Splat,
15953 SelectionDAG &DAG) {
15954 ArrayRef<int> SplatMask = Splat->getMask();
15955 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch")(static_cast <bool> (UserMask.size() == SplatMask.size(
) && "Mask length mismatch") ? void (0) : __assert_fail
("UserMask.size() == SplatMask.size() && \"Mask length mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 15955, __extension__ __PRETTY_FUNCTION__))
;
15956
15957 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15958 // every undef mask element in the splat-shuffle has a corresponding undef
15959 // element in the user-shuffle's mask or if the composition of mask elements
15960 // would result in undef.
15961 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15962 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15963 // In this case it is not legal to simplify to the splat-shuffle because we
15964 // may be exposing the users of the shuffle an undef element at index 1
15965 // which was not there before the combine.
15966 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15967 // In this case the composition of masks yields SplatMask, so it's ok to
15968 // simplify to the splat-shuffle.
15969 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15970 // In this case the composed mask includes all undef elements of SplatMask
15971 // and in addition sets element zero to undef. It is safe to simplify to
15972 // the splat-shuffle.
15973 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15974 ArrayRef<int> SplatMask) {
15975 for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15976 if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15977 SplatMask[UserMask[i]] != -1)
15978 return false;
15979 return true;
15980 };
15981 if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15982 return SDValue(Splat, 0);
15983
15984 // Create a new shuffle with a mask that is composed of the two shuffles'
15985 // masks.
15986 SmallVector<int, 32> NewMask;
15987 for (int Idx : UserMask)
15988 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15989
15990 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15991 Splat->getOperand(0), Splat->getOperand(1),
15992 NewMask);
15993}
15994
15995/// If the shuffle mask is taking exactly one element from the first vector
15996/// operand and passing through all other elements from the second vector
15997/// operand, return the index of the mask element that is choosing an element
15998/// from the first operand. Otherwise, return -1.
15999static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
16000 int MaskSize = Mask.size();
16001 int EltFromOp0 = -1;
16002 // TODO: This does not match if there are undef elements in the shuffle mask.
16003 // Should we ignore undefs in the shuffle mask instead? The trade-off is
16004 // removing an instruction (a shuffle), but losing the knowledge that some
16005 // vector lanes are not needed.
16006 for (int i = 0; i != MaskSize; ++i) {
16007 if (Mask[i] >= 0 && Mask[i] < MaskSize) {
16008 // We're looking for a shuffle of exactly one element from operand 0.
16009 if (EltFromOp0 != -1)
16010 return -1;
16011 EltFromOp0 = i;
16012 } else if (Mask[i] != i + MaskSize) {
16013 // Nothing from operand 1 can change lanes.
16014 return -1;
16015 }
16016 }
16017 return EltFromOp0;
16018}
16019
16020/// If a shuffle inserts exactly one element from a source vector operand into
16021/// another vector operand and we can access the specified element as a scalar,
16022/// then we can eliminate the shuffle.
16023static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
16024 SelectionDAG &DAG) {
16025 // First, check if we are taking one element of a vector and shuffling that
16026 // element into another vector.
16027 ArrayRef<int> Mask = Shuf->getMask();
16028 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
16029 SDValue Op0 = Shuf->getOperand(0);
16030 SDValue Op1 = Shuf->getOperand(1);
16031 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
16032 if (ShufOp0Index == -1) {
16033 // Commute mask and check again.
16034 ShuffleVectorSDNode::commuteMask(CommutedMask);
16035 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
16036 if (ShufOp0Index == -1)
16037 return SDValue();
16038 // Commute operands to match the commuted shuffle mask.
16039 std::swap(Op0, Op1);
16040 Mask = CommutedMask;
16041 }
16042
16043 // The shuffle inserts exactly one element from operand 0 into operand 1.
16044 // Now see if we can access that element as a scalar via a real insert element
16045 // instruction.
16046 // TODO: We can try harder to locate the element as a scalar. Examples: it
16047 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
16048 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&(static_cast <bool> (Mask[ShufOp0Index] >= 0 &&
Mask[ShufOp0Index] < (int)Mask.size() && "Shuffle mask value must be from operand 0"
) ? void (0) : __assert_fail ("Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && \"Shuffle mask value must be from operand 0\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16049, __extension__ __PRETTY_FUNCTION__))
16049 "Shuffle mask value must be from operand 0")(static_cast <bool> (Mask[ShufOp0Index] >= 0 &&
Mask[ShufOp0Index] < (int)Mask.size() && "Shuffle mask value must be from operand 0"
) ? void (0) : __assert_fail ("Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && \"Shuffle mask value must be from operand 0\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16049, __extension__ __PRETTY_FUNCTION__))
;
16050 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
16051 return SDValue();
16052
16053 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
16054 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
16055 return SDValue();
16056
16057 // There's an existing insertelement with constant insertion index, so we
16058 // don't need to check the legality/profitability of a replacement operation
16059 // that differs at most in the constant value. The target should be able to
16060 // lower any of those in a similar way. If not, legalization will expand this
16061 // to a scalar-to-vector plus shuffle.
16062 //
16063 // Note that the shuffle may move the scalar from the position that the insert
16064 // element used. Therefore, our new insert element occurs at the shuffle's
16065 // mask index value, not the insert's index value.
16066 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
16067 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
16068 Op0.getOperand(2).getValueType());
16069 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
16070 Op1, Op0.getOperand(1), NewInsIndex);
16071}
16072
16073SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
16074 EVT VT = N->getValueType(0);
16075 unsigned NumElts = VT.getVectorNumElements();
16076
16077 SDValue N0 = N->getOperand(0);
16078 SDValue N1 = N->getOperand(1);
16079
16080 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG")(static_cast <bool> (N0.getValueType() == VT &&
"Vector shuffle must be normalized in DAG") ? void (0) : __assert_fail
("N0.getValueType() == VT && \"Vector shuffle must be normalized in DAG\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16080, __extension__ __PRETTY_FUNCTION__))
;
16081
16082 // Canonicalize shuffle undef, undef -> undef
16083 if (N0.isUndef() && N1.isUndef())
16084 return DAG.getUNDEF(VT);
16085
16086 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16087
16088 // Canonicalize shuffle v, v -> v, undef
16089 if (N0 == N1) {
1
Taking false branch
16090 SmallVector<int, 8> NewMask;
16091 for (unsigned i = 0; i != NumElts; ++i) {
16092 int Idx = SVN->getMaskElt(i);
16093 if (Idx >= (int)NumElts) Idx -= NumElts;
16094 NewMask.push_back(Idx);
16095 }
16096 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
16097 }
16098
16099 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
16100 if (N0.isUndef())
2
Taking false branch
16101 return DAG.getCommutedVectorShuffle(*SVN);
16102
16103 // Remove references to rhs if it is undef
16104 if (N1.isUndef()) {
3
Taking false branch
16105 bool Changed = false;
16106 SmallVector<int, 8> NewMask;
16107 for (unsigned i = 0; i != NumElts; ++i) {
16108 int Idx = SVN->getMaskElt(i);
16109 if (Idx >= (int)NumElts) {
16110 Idx = -1;
16111 Changed = true;
16112 }
16113 NewMask.push_back(Idx);
16114 }
16115 if (Changed)
16116 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16117 }
16118
16119 // Simplify shuffle mask if a referenced element is UNDEF.
16120 if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
4
Taking false branch
16121 return V;
16122
16123 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
5
Taking false branch
16124 return InsElt;
16125
16126 // A shuffle of a single vector that is a splat can always be folded.
16127 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
6
Taking false branch
16128 if (N1->isUndef() && N0Shuf->isSplat())
16129 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16130
16131 // If it is a splat, check if the argument vector is another splat or a
16132 // build_vector.
16133 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7
Assuming the condition is false
16134 SDNode *V = N0.getNode();
16135
16136 // If this is a bit convert that changes the element type of the vector but
16137 // not the number of vector elements, look through it. Be careful not to
16138 // look though conversions that change things like v4f32 to v2f64.
16139 if (V->getOpcode() == ISD::BITCAST) {
16140 SDValue ConvInput = V->getOperand(0);
16141 if (ConvInput.getValueType().isVector() &&
16142 ConvInput.getValueType().getVectorNumElements() == NumElts)
16143 V = ConvInput.getNode();
16144 }
16145
16146 if (V->getOpcode() == ISD::BUILD_VECTOR) {
16147 assert(V->getNumOperands() == NumElts &&(static_cast <bool> (V->getNumOperands() == NumElts &&
"BUILD_VECTOR has wrong number of operands") ? void (0) : __assert_fail
("V->getNumOperands() == NumElts && \"BUILD_VECTOR has wrong number of operands\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16148, __extension__ __PRETTY_FUNCTION__))
16148 "BUILD_VECTOR has wrong number of operands")(static_cast <bool> (V->getNumOperands() == NumElts &&
"BUILD_VECTOR has wrong number of operands") ? void (0) : __assert_fail
("V->getNumOperands() == NumElts && \"BUILD_VECTOR has wrong number of operands\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16148, __extension__ __PRETTY_FUNCTION__))
;
16149 SDValue Base;
16150 bool AllSame = true;
16151 for (unsigned i = 0; i != NumElts; ++i) {
16152 if (!V->getOperand(i).isUndef()) {
16153 Base = V->getOperand(i);
16154 break;
16155 }
16156 }
16157 // Splat of <u, u, u, u>, return <u, u, u, u>
16158 if (!Base.getNode())
16159 return N0;
16160 for (unsigned i = 0; i != NumElts; ++i) {
16161 if (V->getOperand(i) != Base) {
16162 AllSame = false;
16163 break;
16164 }
16165 }
16166 // Splat of <x, x, x, x>, return <x, x, x, x>
16167 if (AllSame)
16168 return N0;
16169
16170 // Canonicalize any other splat as a build_vector.
16171 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16172 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16173 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16174
16175 // We may have jumped through bitcasts, so the type of the
16176 // BUILD_VECTOR may not match the type of the shuffle.
16177 if (V->getValueType(0) != VT)
16178 NewBV = DAG.getBitcast(VT, NewBV);
16179 return NewBV;
16180 }
16181 }
16182
16183 // There are various patterns used to build up a vector from smaller vectors,
16184 // subvectors, or elements. Scan chains of these and replace unused insertions
16185 // or components with undef.
16186 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
8
Calling 'simplifyShuffleOperands'
16187 return S;
16188
16189 // Match shuffles that can be converted to any_vector_extend_in_reg.
16190 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16191 return V;
16192
16193 // Combine "truncate_vector_in_reg" style shuffles.
16194 if (SDValue V = combineTruncationShuffle(SVN, DAG))
16195 return V;
16196
16197 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16198 Level < AfterLegalizeVectorOps &&
16199 (N1.isUndef() ||
16200 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16201 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16202 if (SDValue V = partitionShuffleOfConcats(N, DAG))
16203 return V;
16204 }
16205
16206 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16207 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16208 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16209 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16210 return Res;
16211
16212 // If this shuffle only has a single input that is a bitcasted shuffle,
16213 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16214 // back to their original types.
16215 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16216 N1.isUndef() && Level < AfterLegalizeVectorOps &&
16217 TLI.isTypeLegal(VT)) {
16218
16219 // Peek through the bitcast only if there is one user.
16220 SDValue BC0 = N0;
16221 while (BC0.getOpcode() == ISD::BITCAST) {
16222 if (!BC0.hasOneUse())
16223 break;
16224 BC0 = BC0.getOperand(0);
16225 }
16226
16227 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16228 if (Scale == 1)
16229 return SmallVector<int, 8>(Mask.begin(), Mask.end());
16230
16231 SmallVector<int, 8> NewMask;
16232 for (int M : Mask)
16233 for (int s = 0; s != Scale; ++s)
16234 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16235 return NewMask;
16236 };
16237
16238 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16239 EVT SVT = VT.getScalarType();
16240 EVT InnerVT = BC0->getValueType(0);
16241 EVT InnerSVT = InnerVT.getScalarType();
16242
16243 // Determine which shuffle works with the smaller scalar type.
16244 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16245 EVT ScaleSVT = ScaleVT.getScalarType();
16246
16247 if (TLI.isTypeLegal(ScaleVT) &&
16248 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16249 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16250 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16251 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16252
16253 // Scale the shuffle masks to the smaller scalar type.
16254 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16255 SmallVector<int, 8> InnerMask =
16256 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16257 SmallVector<int, 8> OuterMask =
16258 ScaleShuffleMask(SVN->getMask(), OuterScale);
16259
16260 // Merge the shuffle masks.
16261 SmallVector<int, 8> NewMask;
16262 for (int M : OuterMask)
16263 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16264
16265 // Test for shuffle mask legality over both commutations.
16266 SDValue SV0 = BC0->getOperand(0);
16267 SDValue SV1 = BC0->getOperand(1);
16268 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16269 if (!LegalMask) {
16270 std::swap(SV0, SV1);
16271 ShuffleVectorSDNode::commuteMask(NewMask);
16272 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16273 }
16274
16275 if (LegalMask) {
16276 SV0 = DAG.getBitcast(ScaleVT, SV0);
16277 SV1 = DAG.getBitcast(ScaleVT, SV1);
16278 return DAG.getBitcast(
16279 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16280 }
16281 }
16282 }
16283 }
16284
16285 // Canonicalize shuffles according to rules:
16286 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16287 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16288 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16289 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16290 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16291 TLI.isTypeLegal(VT)) {
16292 // The incoming shuffle must be of the same type as the result of the
16293 // current shuffle.
16294 assert(N1->getOperand(0).getValueType() == VT &&(static_cast <bool> (N1->getOperand(0).getValueType(
) == VT && "Shuffle types don't match") ? void (0) : __assert_fail
("N1->getOperand(0).getValueType() == VT && \"Shuffle types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16295, __extension__ __PRETTY_FUNCTION__))
16295 "Shuffle types don't match")(static_cast <bool> (N1->getOperand(0).getValueType(
) == VT && "Shuffle types don't match") ? void (0) : __assert_fail
("N1->getOperand(0).getValueType() == VT && \"Shuffle types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16295, __extension__ __PRETTY_FUNCTION__))
;
16296
16297 SDValue SV0 = N1->getOperand(0);
16298 SDValue SV1 = N1->getOperand(1);
16299 bool HasSameOp0 = N0 == SV0;
16300 bool IsSV1Undef = SV1.isUndef();
16301 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16302 // Commute the operands of this shuffle so that next rule
16303 // will trigger.
16304 return DAG.getCommutedVectorShuffle(*SVN);
16305 }
16306
16307 // Try to fold according to rules:
16308 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16309 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16310 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16311 // Don't try to fold shuffles with illegal type.
16312 // Only fold if this shuffle is the only user of the other shuffle.
16313 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16314 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16315 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16316
16317 // Don't try to fold splats; they're likely to simplify somehow, or they
16318 // might be free.
16319 if (OtherSV->isSplat())
16320 return SDValue();
16321
16322 // The incoming shuffle must be of the same type as the result of the
16323 // current shuffle.
16324 assert(OtherSV->getOperand(0).getValueType() == VT &&(static_cast <bool> (OtherSV->getOperand(0).getValueType
() == VT && "Shuffle types don't match") ? void (0) :
__assert_fail ("OtherSV->getOperand(0).getValueType() == VT && \"Shuffle types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16325, __extension__ __PRETTY_FUNCTION__))
16325 "Shuffle types don't match")(static_cast <bool> (OtherSV->getOperand(0).getValueType
() == VT && "Shuffle types don't match") ? void (0) :
__assert_fail ("OtherSV->getOperand(0).getValueType() == VT && \"Shuffle types don't match\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16325, __extension__ __PRETTY_FUNCTION__))
;
16326
16327 SDValue SV0, SV1;
16328 SmallVector<int, 4> Mask;
16329 // Compute the combined shuffle mask for a shuffle with SV0 as the first
16330 // operand, and SV1 as the second operand.
16331 for (unsigned i = 0; i != NumElts; ++i) {
16332 int Idx = SVN->getMaskElt(i);
16333 if (Idx < 0) {
16334 // Propagate Undef.
16335 Mask.push_back(Idx);
16336 continue;
16337 }
16338
16339 SDValue CurrentVec;
16340 if (Idx < (int)NumElts) {
16341 // This shuffle index refers to the inner shuffle N0. Lookup the inner
16342 // shuffle mask to identify which vector is actually referenced.
16343 Idx = OtherSV->getMaskElt(Idx);
16344 if (Idx < 0) {
16345 // Propagate Undef.
16346 Mask.push_back(Idx);
16347 continue;
16348 }
16349
16350 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16351 : OtherSV->getOperand(1);
16352 } else {
16353 // This shuffle index references an element within N1.
16354 CurrentVec = N1;
16355 }
16356
16357 // Simple case where 'CurrentVec' is UNDEF.
16358 if (CurrentVec.isUndef()) {
16359 Mask.push_back(-1);
16360 continue;
16361 }
16362
16363 // Canonicalize the shuffle index. We don't know yet if CurrentVec
16364 // will be the first or second operand of the combined shuffle.
16365 Idx = Idx % NumElts;
16366 if (!SV0.getNode() || SV0 == CurrentVec) {
16367 // Ok. CurrentVec is the left hand side.
16368 // Update the mask accordingly.
16369 SV0 = CurrentVec;
16370 Mask.push_back(Idx);
16371 continue;
16372 }
16373
16374 // Bail out if we cannot convert the shuffle pair into a single shuffle.
16375 if (SV1.getNode() && SV1 != CurrentVec)
16376 return SDValue();
16377
16378 // Ok. CurrentVec is the right hand side.
16379 // Update the mask accordingly.
16380 SV1 = CurrentVec;
16381 Mask.push_back(Idx + NumElts);
16382 }
16383
16384 // Check if all indices in Mask are Undef. In case, propagate Undef.
16385 bool isUndefMask = true;
16386 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16387 isUndefMask &= Mask[i] < 0;
16388
16389 if (isUndefMask)
16390 return DAG.getUNDEF(VT);
16391
16392 if (!SV0.getNode())
16393 SV0 = DAG.getUNDEF(VT);
16394 if (!SV1.getNode())
16395 SV1 = DAG.getUNDEF(VT);
16396
16397 // Avoid introducing shuffles with illegal mask.
16398 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16399 ShuffleVectorSDNode::commuteMask(Mask);
16400
16401 if (!TLI.isShuffleMaskLegal(Mask, VT))
16402 return SDValue();
16403
16404 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16405 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16406 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16407 std::swap(SV0, SV1);
16408 }
16409
16410 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16411 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16412 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16413 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16414 }
16415
16416 return SDValue();
16417}
16418
16419SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16420 SDValue InVal = N->getOperand(0);
16421 EVT VT = N->getValueType(0);
16422
16423 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16424 // with a VECTOR_SHUFFLE and possible truncate.
16425 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16426 SDValue InVec = InVal->getOperand(0);
16427 SDValue EltNo = InVal->getOperand(1);
16428 auto InVecT = InVec.getValueType();
16429 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16430 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16431 int Elt = C0->getZExtValue();
16432 NewMask[0] = Elt;
16433 SDValue Val;
16434 // If we have an implict truncate do truncate here as long as it's legal.
16435 // if it's not legal, this should
16436 if (VT.getScalarType() != InVal.getValueType() &&
16437 InVal.getValueType().isScalarInteger() &&
16438 isTypeLegal(VT.getScalarType())) {
16439 Val =
16440 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16441 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16442 }
16443 if (VT.getScalarType() == InVecT.getScalarType() &&
16444 VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16445 TLI.isShuffleMaskLegal(NewMask, VT)) {
16446 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16447 DAG.getUNDEF(InVecT), NewMask);
16448 // If the initial vector is the correct size this shuffle is a
16449 // valid result.
16450 if (VT == InVecT)
16451 return Val;
16452 // If not we must truncate the vector.
16453 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16454 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16455 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16456 EVT SubVT =
16457 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16458 VT.getVectorNumElements());
16459 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16460 ZeroIdx);
16461 return Val;
16462 }
16463 }
16464 }
16465 }
16466
16467 return SDValue();
16468}
16469
16470SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16471 EVT VT = N->getValueType(0);
16472 SDValue N0 = N->getOperand(0);
16473 SDValue N1 = N->getOperand(1);
16474 SDValue N2 = N->getOperand(2);
16475
16476 // If inserting an UNDEF, just return the original vector.
16477 if (N1.isUndef())
16478 return N0;
16479
16480 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16481 // us to pull BITCASTs from input to output.
16482 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16483 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16484 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16485
16486 // If this is an insert of an extracted vector into an undef vector, we can
16487 // just use the input to the extract.
16488 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16489 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16490 return N1.getOperand(0);
16491
16492 // If we are inserting a bitcast value into an undef, with the same
16493 // number of elements, just use the bitcast input of the extract.
16494 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16495 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16496 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16497 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16498 N1.getOperand(0).getOperand(1) == N2 &&
16499 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16500 VT.getVectorNumElements() &&
16501 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
16502 VT.getSizeInBits()) {
16503 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16504 }
16505
16506 // If both N1 and N2 are bitcast values on which insert_subvector
16507 // would makes sense, pull the bitcast through.
16508 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16509 // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16510 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16511 SDValue CN0 = N0.getOperand(0);
16512 SDValue CN1 = N1.getOperand(0);
16513 if (CN0.getValueType().getVectorElementType() ==
16514 CN1.getValueType().getVectorElementType() &&
16515 CN0.getValueType().getVectorNumElements() ==
16516 VT.getVectorNumElements()) {
16517 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16518 CN0.getValueType(), CN0, CN1, N2);
16519 return DAG.getBitcast(VT, NewINSERT);
16520 }
16521 }
16522
16523 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16524 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16525 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16526 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16527 N0.getOperand(1).getValueType() == N1.getValueType() &&
16528 N0.getOperand(2) == N2)
16529 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16530 N1, N2);
16531
16532 if (!isa<ConstantSDNode>(N2))
16533 return SDValue();
16534
16535 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16536
16537 // Canonicalize insert_subvector dag nodes.
16538 // Example:
16539 // (insert_subvector (insert_subvector A, Idx0), Idx1)
16540 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16541 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16542 N1.getValueType() == N0.getOperand(1).getValueType() &&
16543 isa<ConstantSDNode>(N0.getOperand(2))) {
16544 unsigned OtherIdx = N0.getConstantOperandVal(2);
16545 if (InsIdx < OtherIdx) {
16546 // Swap nodes.
16547 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16548 N0.getOperand(0), N1, N2);
16549 AddToWorklist(NewOp.getNode());
16550 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16551 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16552 }
16553 }
16554
16555 // If the input vector is a concatenation, and the insert replaces
16556 // one of the pieces, we can optimize into a single concat_vectors.
16557 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16558 N0.getOperand(0).getValueType() == N1.getValueType()) {
16559 unsigned Factor = N1.getValueType().getVectorNumElements();
16560
16561 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16562 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16563
16564 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16565 }
16566
16567 return SDValue();
16568}
16569
16570SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16571 SDValue N0 = N->getOperand(0);
16572
16573 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16574 if (N0->getOpcode() == ISD::FP16_TO_FP)
16575 return N0->getOperand(0);
16576
16577 return SDValue();
16578}
16579
16580SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16581 SDValue N0 = N->getOperand(0);
16582
16583 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16584 if (N0->getOpcode() == ISD::AND) {
16585 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16586 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16587 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16588 N0.getOperand(0));
16589 }
16590 }
16591
16592 return SDValue();
16593}
16594
16595/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16596/// with the destination vector and a zero vector.
16597/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16598/// vector_shuffle V, Zero, <0, 4, 2, 4>
16599SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16600 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!")(static_cast <bool> (N->getOpcode() == ISD::AND &&
"Unexpected opcode!") ? void (0) : __assert_fail ("N->getOpcode() == ISD::AND && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16600, __extension__ __PRETTY_FUNCTION__))
;
16601
16602 EVT VT = N->getValueType(0);
16603 SDValue LHS = N->getOperand(0);
16604 SDValue RHS = peekThroughBitcast(N->getOperand(1));
16605 SDLoc DL(N);
16606
16607 // Make sure we're not running after operation legalization where it
16608 // may have custom lowered the vector shuffles.
16609 if (LegalOperations)
16610 return SDValue();
16611
16612 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16613 return SDValue();
16614
16615 EVT RVT = RHS.getValueType();
16616 unsigned NumElts = RHS.getNumOperands();
16617
16618 // Attempt to create a valid clear mask, splitting the mask into
16619 // sub elements and checking to see if each is
16620 // all zeros or all ones - suitable for shuffle masking.
16621 auto BuildClearMask = [&](int Split) {
16622 int NumSubElts = NumElts * Split;
16623 int NumSubBits = RVT.getScalarSizeInBits() / Split;
16624
16625 SmallVector<int, 8> Indices;
16626 for (int i = 0; i != NumSubElts; ++i) {
16627 int EltIdx = i / Split;
16628 int SubIdx = i % Split;
16629 SDValue Elt = RHS.getOperand(EltIdx);
16630 if (Elt.isUndef()) {
16631 Indices.push_back(-1);
16632 continue;
16633 }
16634
16635 APInt Bits;
16636 if (isa<ConstantSDNode>(Elt))
16637 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16638 else if (isa<ConstantFPSDNode>(Elt))
16639 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16640 else
16641 return SDValue();
16642
16643 // Extract the sub element from the constant bit mask.
16644 if (DAG.getDataLayout().isBigEndian()) {
16645 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16646 } else {
16647 Bits.lshrInPlace(SubIdx * NumSubBits);
16648 }
16649
16650 if (Split > 1)
16651 Bits = Bits.trunc(NumSubBits);
16652
16653 if (Bits.isAllOnesValue())
16654 Indices.push_back(i);
16655 else if (Bits == 0)
16656 Indices.push_back(i + NumSubElts);
16657 else
16658 return SDValue();
16659 }
16660
16661 // Let's see if the target supports this vector_shuffle.
16662 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16663 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16664 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16665 return SDValue();
16666
16667 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16668 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16669 DAG.getBitcast(ClearVT, LHS),
16670 Zero, Indices));
16671 };
16672
16673 // Determine maximum split level (byte level masking).
16674 int MaxSplit = 1;
16675 if (RVT.getScalarSizeInBits() % 8 == 0)
16676 MaxSplit = RVT.getScalarSizeInBits() / 8;
16677
16678 for (int Split = 1; Split <= MaxSplit; ++Split)
16679 if (RVT.getScalarSizeInBits() % Split == 0)
16680 if (SDValue S = BuildClearMask(Split))
16681 return S;
16682
16683 return SDValue();
16684}
16685
16686/// Visit a binary vector operation, like ADD.
16687SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16688 assert(N->getValueType(0).isVector() &&(static_cast <bool> (N->getValueType(0).isVector() &&
"SimplifyVBinOp only works on vectors!") ? void (0) : __assert_fail
("N->getValueType(0).isVector() && \"SimplifyVBinOp only works on vectors!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16689, __extension__ __PRETTY_FUNCTION__))
16689 "SimplifyVBinOp only works on vectors!")(static_cast <bool> (N->getValueType(0).isVector() &&
"SimplifyVBinOp only works on vectors!") ? void (0) : __assert_fail
("N->getValueType(0).isVector() && \"SimplifyVBinOp only works on vectors!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16689, __extension__ __PRETTY_FUNCTION__))
;
16690
16691 SDValue LHS = N->getOperand(0);
16692 SDValue RHS = N->getOperand(1);
16693 SDValue Ops[] = {LHS, RHS};
16694
16695 // See if we can constant fold the vector operation.
16696 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16697 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16698 return Fold;
16699
16700 // Type legalization might introduce new shuffles in the DAG.
16701 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16702 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
16703 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16704 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16705 LHS.getOperand(1).isUndef() &&
16706 RHS.getOperand(1).isUndef()) {
16707 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16708 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16709
16710 if (SVN0->getMask().equals(SVN1->getMask())) {
16711 EVT VT = N->getValueType(0);
16712 SDValue UndefVector = LHS.getOperand(1);
16713 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16714 LHS.getOperand(0), RHS.getOperand(0),
16715 N->getFlags());
16716 AddUsersToWorklist(N);
16717 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16718 SVN0->getMask());
16719 }
16720 }
16721
16722 return SDValue();
16723}
16724
16725SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16726 SDValue N2) {
16727 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!")(static_cast <bool> (N0.getOpcode() ==ISD::SETCC &&
"First argument must be a SetCC node!") ? void (0) : __assert_fail
("N0.getOpcode() ==ISD::SETCC && \"First argument must be a SetCC node!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 16727, __extension__ __PRETTY_FUNCTION__))
;
16728
16729 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16730 cast<CondCodeSDNode>(N0.getOperand(2))->get());
16731
16732 // If we got a simplified select_cc node back from SimplifySelectCC, then
16733 // break it down into a new SETCC node, and a new SELECT node, and then return
16734 // the SELECT node, since we were called with a SELECT node.
16735 if (SCC.getNode()) {
16736 // Check to see if we got a select_cc back (to turn into setcc/select).
16737 // Otherwise, just return whatever node we got back, like fabs.
16738 if (SCC.getOpcode() == ISD::SELECT_CC) {
16739 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16740 N0.getValueType(),
16741 SCC.getOperand(0), SCC.getOperand(1),
16742 SCC.getOperand(4));
16743 AddToWorklist(SETCC.getNode());
16744 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16745 SCC.getOperand(2), SCC.getOperand(3));
16746 }
16747
16748 return SCC;
16749 }
16750 return SDValue();
16751}
16752
16753/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16754/// being selected between, see if we can simplify the select. Callers of this
16755/// should assume that TheSelect is deleted if this returns true. As such, they
16756/// should return the appropriate thing (e.g. the node) back to the top-level of
16757/// the DAG combiner loop to avoid it being looked at.
16758bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16759 SDValue RHS) {
16760 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16761 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16762 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16763 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16764 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16765 SDValue Sqrt = RHS;
16766 ISD::CondCode CC;
16767 SDValue CmpLHS;
16768 const ConstantFPSDNode *Zero = nullptr;
16769
16770 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16771 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16772 CmpLHS = TheSelect->getOperand(0);
16773 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16774 } else {
16775 // SELECT or VSELECT
16776 SDValue Cmp = TheSelect->getOperand(0);
16777 if (Cmp.getOpcode() == ISD::SETCC) {
16778 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16779 CmpLHS = Cmp.getOperand(0);
16780 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16781 }
16782 }
16783 if (Zero && Zero->isZero() &&
16784 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16785 CC == ISD::SETULT || CC == ISD::SETLT)) {
16786 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16787 CombineTo(TheSelect, Sqrt);
16788 return true;
16789 }
16790 }
16791 }
16792 // Cannot simplify select with vector condition
16793 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16794
16795 // If this is a select from two identical things, try to pull the operation
16796 // through the select.
16797 if (LHS.getOpcode() != RHS.getOpcode() ||
16798 !LHS.hasOneUse() || !RHS.hasOneUse())
16799 return false;
16800
16801 // If this is a load and the token chain is identical, replace the select
16802 // of two loads with a load through a select of the address to load from.
16803 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16804 // constants have been dropped into the constant pool.
16805 if (LHS.getOpcode() == ISD::LOAD) {
16806 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16807 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16808
16809 // Token chains must be identical.
16810 if (LHS.getOperand(0) != RHS.getOperand(0) ||
16811 // Do not let this transformation reduce the number of volatile loads.
16812 LLD->isVolatile() || RLD->isVolatile() ||
16813 // FIXME: If either is a pre/post inc/dec load,
16814 // we'd need to split out the address adjustment.
16815 LLD->isIndexed() || RLD->isIndexed() ||
16816 // If this is an EXTLOAD, the VT's must match.
16817 LLD->getMemoryVT() != RLD->getMemoryVT() ||
16818 // If this is an EXTLOAD, the kind of extension must match.
16819 (LLD->getExtensionType() != RLD->getExtensionType() &&
16820 // The only exception is if one of the extensions is anyext.
16821 LLD->getExtensionType() != ISD::EXTLOAD &&
16822 RLD->getExtensionType() != ISD::EXTLOAD) ||
16823 // FIXME: this discards src value information. This is
16824 // over-conservative. It would be beneficial to be able to remember
16825 // both potential memory locations. Since we are discarding
16826 // src value info, don't do the transformation if the memory
16827 // locations are not in the default address space.
16828 LLD->getPointerInfo().getAddrSpace() != 0 ||
16829 RLD->getPointerInfo().getAddrSpace() != 0 ||
16830 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16831 LLD->getBasePtr().getValueType()))
16832 return false;
16833
16834 // Check that the select condition doesn't reach either load. If so,
16835 // folding this will induce a cycle into the DAG. If not, this is safe to
16836 // xform, so create a select of the addresses.
16837 SDValue Addr;
16838 if (TheSelect->getOpcode() == ISD::SELECT) {
16839 SDNode *CondNode = TheSelect->getOperand(0).getNode();
16840 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16841 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16842 return false;
16843 // The loads must not depend on one another.
16844 if (LLD->isPredecessorOf(RLD) ||
16845 RLD->isPredecessorOf(LLD))
16846 return false;
16847 Addr = DAG.getSelect(SDLoc(TheSelect),
16848 LLD->getBasePtr().getValueType(),
16849 TheSelect->getOperand(0), LLD->getBasePtr(),
16850 RLD->getBasePtr());
16851 } else { // Otherwise SELECT_CC
16852 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16853 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16854
16855 if ((LLD->hasAnyUseOfValue(1) &&
16856 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16857 (RLD->hasAnyUseOfValue(1) &&
16858 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16859 return false;
16860
16861 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16862 LLD->getBasePtr().getValueType(),
16863 TheSelect->getOperand(0),
16864 TheSelect->getOperand(1),
16865 LLD->getBasePtr(), RLD->getBasePtr(),
16866 TheSelect->getOperand(4));
16867 }
16868
16869 SDValue Load;
16870 // It is safe to replace the two loads if they have different alignments,
16871 // but the new load must be the minimum (most restrictive) alignment of the
16872 // inputs.
16873 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16874 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16875 if (!RLD->isInvariant())
16876 MMOFlags &= ~MachineMemOperand::MOInvariant;
16877 if (!RLD->isDereferenceable())
16878 MMOFlags &= ~MachineMemOperand::MODereferenceable;
16879 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16880 // FIXME: Discards pointer and AA info.
16881 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16882 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16883 MMOFlags);
16884 } else {
16885 // FIXME: Discards pointer and AA info.
16886 Load = DAG.getExtLoad(
16887 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16888 : LLD->getExtensionType(),
16889 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16890 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16891 }
16892
16893 // Users of the select now use the result of the load.
16894 CombineTo(TheSelect, Load);
16895
16896 // Users of the old loads now use the new load's chain. We know the
16897 // old-load value is dead now.
16898 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16899 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16900 return true;
16901 }
16902
16903 return false;
16904}
16905
16906/// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16907/// bitwise 'and'.
16908SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16909 SDValue N1, SDValue N2, SDValue N3,
16910 ISD::CondCode CC) {
16911 // If this is a select where the false operand is zero and the compare is a
16912 // check of the sign bit, see if we can perform the "gzip trick":
16913 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16914 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16915 EVT XType = N0.getValueType();
16916 EVT AType = N2.getValueType();
16917 if (!isNullConstant(N3) || !XType.bitsGE(AType))
16918 return SDValue();
16919
16920 // If the comparison is testing for a positive value, we have to invert
16921 // the sign bit mask, so only do that transform if the target has a bitwise
16922 // 'and not' instruction (the invert is free).
16923 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16924 // (X > -1) ? A : 0
16925 // (X > 0) ? X : 0 <-- This is canonical signed max.
16926 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16927 return SDValue();
16928 } else if (CC == ISD::SETLT) {
16929 // (X < 0) ? A : 0
16930 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
16931 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16932 return SDValue();
16933 } else {
16934 return SDValue();
16935 }
16936
16937 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16938 // constant.
16939 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16940 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16941 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16942 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16943 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16944 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16945 AddToWorklist(Shift.getNode());
16946
16947 if (XType.bitsGT(AType)) {
16948 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16949 AddToWorklist(Shift.getNode());
16950 }
16951
16952 if (CC == ISD::SETGT)
16953 Shift = DAG.getNOT(DL, Shift, AType);
16954
16955 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16956 }
16957
16958 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16959 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16960 AddToWorklist(Shift.getNode());
16961
16962 if (XType.bitsGT(AType)) {
16963 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16964 AddToWorklist(Shift.getNode());
16965 }
16966
16967 if (CC == ISD::SETGT)
16968 Shift = DAG.getNOT(DL, Shift, AType);
16969
16970 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16971}
16972
16973/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16974/// where 'cond' is the comparison specified by CC.
16975SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16976 SDValue N2, SDValue N3, ISD::CondCode CC,
16977 bool NotExtCompare) {
16978 // (x ? y : y) -> y.
16979 if (N2 == N3) return N2;
16980
16981 EVT VT = N2.getValueType();
16982 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16983 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16984
16985 // Determine if the condition we're dealing with is constant
16986 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16987 N0, N1, CC, DL, false);
16988 if (SCC.getNode()) AddToWorklist(SCC.getNode());
16989
16990 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16991 // fold select_cc true, x, y -> x
16992 // fold select_cc false, x, y -> y
16993 return !SCCC->isNullValue() ? N2 : N3;
16994 }
16995
16996 // Check to see if we can simplify the select into an fabs node
16997 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16998 // Allow either -0.0 or 0.0
16999 if (CFP->isZero()) {
17000 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
17001 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
17002 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
17003 N2 == N3.getOperand(0))
17004 return DAG.getNode(ISD::FABS, DL, VT, N0);
17005
17006 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
17007 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
17008 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
17009 N2.getOperand(0) == N3)
17010 return DAG.getNode(ISD::FABS, DL, VT, N3);
17011 }
17012 }
17013
17014 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
17015 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
17016 // in it. This is a win when the constant is not otherwise available because
17017 // it replaces two constant pool loads with one. We only do this if the FP
17018 // type is known to be legal, because if it isn't, then we are before legalize
17019 // types an we want the other legalization to happen first (e.g. to avoid
17020 // messing with soft float) and if the ConstantFP is not legal, because if
17021 // it is legal, we may not need to store the FP constant in a constant pool.
17022 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
17023 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
17024 if (TLI.isTypeLegal(N2.getValueType()) &&
17025 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
17026 TargetLowering::Legal &&
17027 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
17028 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
17029 // If both constants have multiple uses, then we won't need to do an
17030 // extra load, they are likely around in registers for other users.
17031 (TV->hasOneUse() || FV->hasOneUse())) {
17032 Constant *Elts[] = {
17033 const_cast<ConstantFP*>(FV->getConstantFPValue()),
17034 const_cast<ConstantFP*>(TV->getConstantFPValue())
17035 };
17036 Type *FPTy = Elts[0]->getType();
17037 const DataLayout &TD = DAG.getDataLayout();
17038
17039 // Create a ConstantArray of the two constants.
17040 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
17041 SDValue CPIdx =
17042 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
17043 TD.getPrefTypeAlignment(FPTy));
17044 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
17045
17046 // Get the offsets to the 0 and 1 element of the array so that we can
17047 // select between them.
17048 SDValue Zero = DAG.getIntPtrConstant(0, DL);
17049 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
17050 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
17051
17052 SDValue Cond = DAG.getSetCC(DL,
17053 getSetCCResultType(N0.getValueType()),
17054 N0, N1, CC);
17055 AddToWorklist(Cond.getNode());
17056 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
17057 Cond, One, Zero);
17058 AddToWorklist(CstOffset.getNode());
17059 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
17060 CstOffset);
17061 AddToWorklist(CPIdx.getNode());
17062 return DAG.getLoad(
17063 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
17064 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17065 Alignment);
17066 }
17067 }
17068
17069 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
17070 return V;
17071
17072 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
17073 // where y is has a single bit set.
17074 // A plaintext description would be, we can turn the SELECT_CC into an AND
17075 // when the condition can be materialized as an all-ones register. Any
17076 // single bit-test can be materialized as an all-ones register with
17077 // shift-left and shift-right-arith.
17078 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
17079 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
17080 SDValue AndLHS = N0->getOperand(0);
17081 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17082 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
17083 // Shift the tested bit over the sign bit.
17084 const APInt &AndMask = ConstAndRHS->getAPIntValue();
17085 SDValue ShlAmt =
17086 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
17087 getShiftAmountTy(AndLHS.getValueType()));
17088 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
17089
17090 // Now arithmetic right shift it all the way over, so the result is either
17091 // all-ones, or zero.
17092 SDValue ShrAmt =
17093 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
17094 getShiftAmountTy(Shl.getValueType()));
17095 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
17096
17097 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17098 }
17099 }
17100
17101 // fold select C, 16, 0 -> shl C, 4
17102 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17103 TLI.getBooleanContents(N0.getValueType()) ==
17104 TargetLowering::ZeroOrOneBooleanContent) {
17105
17106 // If the caller doesn't want us to simplify this into a zext of a compare,
17107 // don't do it.
17108 if (NotExtCompare && N2C->isOne())
17109 return SDValue();
17110
17111 // Get a SetCC of the condition
17112 // NOTE: Don't create a SETCC if it's not legal on this target.
17113 if (!LegalOperations ||
17114 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17115 SDValue Temp, SCC;
17116 // cast from setcc result type to select result type
17117 if (LegalTypes) {
17118 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17119 N0, N1, CC);
17120 if (N2.getValueType().bitsLT(SCC.getValueType()))
17121 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17122 N2.getValueType());
17123 else
17124 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17125 N2.getValueType(), SCC);
17126 } else {
17127 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17128 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17129 N2.getValueType(), SCC);
17130 }
17131
17132 AddToWorklist(SCC.getNode());
17133 AddToWorklist(Temp.getNode());
17134
17135 if (N2C->isOne())
17136 return Temp;
17137
17138 // shl setcc result by log2 n2c
17139 return DAG.getNode(
17140 ISD::SHL, DL, N2.getValueType(), Temp,
17141 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17142 getShiftAmountTy(Temp.getValueType())));
17143 }
17144 }
17145
17146 // Check to see if this is an integer abs.
17147 // select_cc setg[te] X, 0, X, -X ->
17148 // select_cc setgt X, -1, X, -X ->
17149 // select_cc setl[te] X, 0, -X, X ->
17150 // select_cc setlt X, 1, -X, X ->
17151 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17152 if (N1C) {
17153 ConstantSDNode *SubC = nullptr;
17154 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17155 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17156 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17157 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17158 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17159 (N1C->isOne() && CC == ISD::SETLT)) &&
17160 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17161 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17162
17163 EVT XType = N0.getValueType();
17164 if (SubC && SubC->isNullValue() && XType.isInteger()) {
17165 SDLoc DL(N0);
17166 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17167 N0,
17168 DAG.getConstant(XType.getSizeInBits() - 1, DL,
17169 getShiftAmountTy(N0.getValueType())));
17170 SDValue Add = DAG.getNode(ISD::ADD, DL,
17171 XType, N0, Shift);
17172 AddToWorklist(Shift.getNode());
17173 AddToWorklist(Add.getNode());
17174 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17175 }
17176 }
17177
17178 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17179 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17180 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17181 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17182 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17183 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17184 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17185 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17186 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17187 SDValue ValueOnZero = N2;
17188 SDValue Count = N3;
17189 // If the condition is NE instead of E, swap the operands.
17190 if (CC == ISD::SETNE)
17191 std::swap(ValueOnZero, Count);
17192 // Check if the value on zero is a constant equal to the bits in the type.
17193 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17194 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17195 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17196 // legal, combine to just cttz.
17197 if ((Count.getOpcode() == ISD::CTTZ ||
17198 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17199 N0 == Count.getOperand(0) &&
17200 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17201 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17202 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17203 // legal, combine to just ctlz.
17204 if ((Count.getOpcode() == ISD::CTLZ ||
17205 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17206 N0 == Count.getOperand(0) &&
17207 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17208 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17209 }
17210 }
17211 }
17212
17213 return SDValue();
17214}
17215
17216/// This is a stub for TargetLowering::SimplifySetCC.
17217SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17218 ISD::CondCode Cond, const SDLoc &DL,
17219 bool foldBooleans) {
17220 TargetLowering::DAGCombinerInfo
17221 DagCombineInfo(DAG, Level, false, this);
17222 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17223}
17224
17225/// Given an ISD::SDIV node expressing a divide by constant, return
17226/// a DAG expression to select that will generate the same value by multiplying
17227/// by a magic number.
17228/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17229SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17230 // when optimising for minimum size, we don't want to expand a div to a mul
17231 // and a shift.
17232 if (DAG.getMachineFunction().getFunction().optForMinSize())
17233 return SDValue();
17234
17235 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17236 if (!C)
17237 return SDValue();
17238
17239 // Avoid division by zero.
17240 if (C->isNullValue())
17241 return SDValue();
17242
17243 std::vector<SDNode *> Built;
17244 SDValue S =
17245 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17246
17247 for (SDNode *N : Built)
17248 AddToWorklist(N);
17249 return S;
17250}
17251
17252/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17253/// DAG expression that will generate the same value by right shifting.
17254SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17255 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17256 if (!C)
17257 return SDValue();
17258
17259 // Avoid division by zero.
17260 if (C->isNullValue())
17261 return SDValue();
17262
17263 std::vector<SDNode *> Built;
17264 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17265
17266 for (SDNode *N : Built)
17267 AddToWorklist(N);
17268 return S;
17269}
17270
17271/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17272/// expression that will generate the same value by multiplying by a magic
17273/// number.
17274/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17275SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17276 // when optimising for minimum size, we don't want to expand a div to a mul
17277 // and a shift.
17278 if (DAG.getMachineFunction().getFunction().optForMinSize())
17279 return SDValue();
17280
17281 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17282 if (!C)
17283 return SDValue();
17284
17285 // Avoid division by zero.
17286 if (C->isNullValue())
17287 return SDValue();
17288
17289 std::vector<SDNode *> Built;
17290 SDValue S =
17291 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17292
17293 for (SDNode *N : Built)
17294 AddToWorklist(N);
17295 return S;
17296}
17297
17298/// Determines the LogBase2 value for a non-null input value using the
17299/// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17300SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17301 EVT VT = V.getValueType();
17302 unsigned EltBits = VT.getScalarSizeInBits();
17303 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17304 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17305 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17306 return LogBase2;
17307}
17308
17309/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17310/// For the reciprocal, we need to find the zero of the function:
17311/// F(X) = A X - 1 [which has a zero at X = 1/A]
17312/// =>
17313/// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17314/// does not require additional intermediate precision]
17315SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17316 if (Level >= AfterLegalizeDAG)
17317 return SDValue();
17318
17319 // TODO: Handle half and/or extended types?
17320 EVT VT = Op.getValueType();
17321 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17322 return SDValue();
17323
17324 // If estimates are explicitly disabled for this function, we're done.
17325 MachineFunction &MF = DAG.getMachineFunction();
17326 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17327 if (Enabled == TLI.ReciprocalEstimate::Disabled)
17328 return SDValue();
17329
17330 // Estimates may be explicitly enabled for this type with a custom number of
17331 // refinement steps.
17332 int Iterations = TLI.getDivRefinementSteps(VT, MF);
17333 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17334 AddToWorklist(Est.getNode());
17335
17336 if (Iterations) {
17337 EVT VT = Op.getValueType();
17338 SDLoc DL(Op);
17339 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17340
17341 // Newton iterations: Est = Est + Est (1 - Arg * Est)
17342 for (int i = 0; i < Iterations; ++i) {
17343 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17344 AddToWorklist(NewEst.getNode());
17345
17346 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17347 AddToWorklist(NewEst.getNode());
17348
17349 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17350 AddToWorklist(NewEst.getNode());
17351
17352 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17353 AddToWorklist(Est.getNode());
17354 }
17355 }
17356 return Est;
17357 }
17358
17359 return SDValue();
17360}
17361
17362/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17363/// For the reciprocal sqrt, we need to find the zero of the function:
17364/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17365/// =>
17366/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17367/// As a result, we precompute A/2 prior to the iteration loop.
17368SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17369 unsigned Iterations,
17370 SDNodeFlags Flags, bool Reciprocal) {
17371 EVT VT = Arg.getValueType();
17372 SDLoc DL(Arg);
17373 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17374
17375 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17376 // this entire sequence requires only one FP constant.
17377 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17378 AddToWorklist(HalfArg.getNode());
17379
17380 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17381 AddToWorklist(HalfArg.getNode());
17382
17383 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17384 for (unsigned i = 0; i < Iterations; ++i) {
17385 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17386 AddToWorklist(NewEst.getNode());
17387
17388 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17389 AddToWorklist(NewEst.getNode());
17390
17391 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17392 AddToWorklist(NewEst.getNode());
17393
17394 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17395 AddToWorklist(Est.getNode());
17396 }
17397
17398 // If non-reciprocal square root is requested, multiply the result by Arg.
17399 if (!Reciprocal) {
17400 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17401 AddToWorklist(Est.getNode());
17402 }
17403
17404 return Est;
17405}
17406
17407/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17408/// For the reciprocal sqrt, we need to find the zero of the function:
17409/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17410/// =>
17411/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17412SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17413 unsigned Iterations,
17414 SDNodeFlags Flags, bool Reciprocal) {
17415 EVT VT = Arg.getValueType();
17416 SDLoc DL(Arg);
17417 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17418 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17419
17420 // This routine must enter the loop below to work correctly
17421 // when (Reciprocal == false).
17422 assert(Iterations > 0)(static_cast <bool> (Iterations > 0) ? void (0) : __assert_fail
("Iterations > 0", "/build/llvm-toolchain-snapshot-7~svn325118/lib/CodeGen/SelectionDAG/DAGCombiner.cpp"
, 17422, __extension__ __PRETTY_FUNCTION__))
;
17423
17424 // Newton iterations for reciprocal square root:
17425 // E = (E * -0.5) * ((A * E) * E + -3.0)
17426 for (unsigned i = 0; i < Iterations; ++i) {
17427 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17428 AddToWorklist(AE.getNode());
17429
17430 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17431 AddToWorklist(AEE.getNode());
17432
17433 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17434 AddToWorklist(RHS.getNode());
17435
17436 // When calculating a square root at the last iteration build:
17437 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17438 // (notice a common subexpression)
17439 SDValue LHS;
17440 if (Reciprocal || (i + 1) < Iterations) {
17441 // RSQRT: LHS = (E * -0.5)
17442 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17443 } else {
17444 // SQRT: LHS = (A * E) * -0.5
17445 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17446 }
17447 AddToWorklist(LHS.getNode());
17448
17449 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17450 AddToWorklist(Est.getNode());
17451 }
17452
17453 return Est;
17454}
17455
17456/// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17457/// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17458/// Op can be zero.
17459SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17460 bool Reciprocal) {
17461 if (Level >= AfterLegalizeDAG)
17462 return SDValue();
17463
17464 // TODO: Handle half and/or extended types?
17465 EVT VT = Op.getValueType();
17466 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17467 return SDValue();
17468
17469 // If estimates are explicitly disabled for this function, we're done.
17470 MachineFunction &MF = DAG.getMachineFunction();
17471 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17472 if (Enabled == TLI.ReciprocalEstimate::Disabled)
17473 return SDValue();
17474
17475 // Estimates may be explicitly enabled for this type with a custom number of
17476 // refinement steps.
17477 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17478
17479 bool UseOneConstNR = false;
17480 if (SDValue Est =
17481 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17482 Reciprocal)) {
17483 AddToWorklist(Est.getNode());
17484
17485 if (Iterations) {
17486 Est = UseOneConstNR
17487 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17488 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17489
17490 if (!Reciprocal) {
17491 // The estimate is now completely wrong if the input was exactly 0.0 or
17492 // possibly a denormal. Force the answer to 0.0 for those cases.
17493 EVT VT = Op.getValueType();
17494 SDLoc DL(Op);
17495 EVT CCVT = getSetCCResultType(VT);
17496 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
17497 const Function &F = DAG.getMachineFunction().getFunction();
17498 Attribute Denorms = F.getFnAttribute("denormal-fp-math");
17499 if (Denorms.getValueAsString().equals("ieee")) {
17500 // fabs(X) < SmallestNormal ? 0.0 : Est
17501 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
17502 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
17503 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
17504 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17505 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
17506 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
17507 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
17508 AddToWorklist(Fabs.getNode());
17509 AddToWorklist(IsDenorm.getNode());
17510 AddToWorklist(Est.getNode());
17511 } else {
17512 // X == 0.0 ? 0.0 : Est
17513 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17514 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17515 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
17516 AddToWorklist(IsZero.getNode());
17517 AddToWorklist(Est.getNode());
17518 }
17519 }
17520 }
17521 return Est;
17522 }
17523
17524 return SDValue();
17525}
17526
17527SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17528 return buildSqrtEstimateImpl(Op, Flags, true);
17529}
17530
17531SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17532 return buildSqrtEstimateImpl(Op, Flags, false);
17533}
17534
17535/// Return true if there is any possibility that the two addresses overlap.
17536bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17537 // If they are the same then they must be aliases.
17538 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17539
17540 // If they are both volatile then they cannot be reordered.
17541 if (Op0->isVolatile() && Op1->isVolatile()) return true;
17542
17543 // If one operation reads from invariant memory, and the other may store, they
17544 // cannot alias. These should really be checking the equivalent of mayWrite,
17545 // but it only matters for memory nodes other than load /store.
17546 if (Op0->isInvariant() && Op1->writeMem())
17547 return false;
17548
17549 if (Op1->isInvariant() && Op0->writeMem())
17550 return false;
17551
17552 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17553 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17554
17555 // Check for BaseIndexOffset matching.
17556 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG);
17557 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG);
17558 int64_t PtrDiff;
17559 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) {
17560 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17561 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17562
17563 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17564 // able to calculate their relative offset if at least one arises
17565 // from an alloca. However, these allocas cannot overlap and we
17566 // can infer there is no alias.
17567 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17568 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17569 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17570 // If the base are the same frame index but the we couldn't find a
17571 // constant offset, (indices are different) be conservative.
17572 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17573 !MFI.isFixedObjectIndex(B->getIndex())))
17574 return false;
17575 }
17576
17577 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
17578 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
17579 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
17580 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
17581 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
17582 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
17583
17584 // If of mismatched base types or checkable indices we can check
17585 // they do not alias.
17586 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
17587 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
17588 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1))
17589 return false;
17590 }
17591
17592 // If we know required SrcValue1 and SrcValue2 have relatively large
17593 // alignment compared to the size and offset of the access, we may be able
17594 // to prove they do not alias. This check is conservative for now to catch
17595 // cases created by splitting vector types.
17596 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17597 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17598 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17599 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17600 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17601 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17602 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17603 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17604
17605 // There is no overlap between these relatively aligned accesses of
17606 // similar size. Return no alias.
17607 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17608 (OffAlign1 + NumBytes1) <= OffAlign0)
17609 return false;
17610 }
17611
17612 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17613 ? CombinerGlobalAA
17614 : DAG.getSubtarget().useAA();
17615#ifndef NDEBUG
17616 if (CombinerAAOnlyFunc.getNumOccurrences() &&
17617 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17618 UseAA = false;
17619#endif
17620
17621 if (UseAA && AA &&
17622 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17623 // Use alias analysis information.
17624 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17625 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17626 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17627 AliasResult AAResult =
17628 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17629 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17630 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17631 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17632 if (AAResult == NoAlias)
17633 return false;
17634 }
17635
17636 // Otherwise we have to assume they alias.
17637 return true;
17638}
17639
17640/// Walk up chain skipping non-aliasing memory nodes,
17641/// looking for aliasing nodes and adding them to the Aliases vector.
17642void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17643 SmallVectorImpl<SDValue> &Aliases) {
17644 SmallVector<SDValue, 8> Chains; // List of chains to visit.
17645 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
17646
17647 // Get alias information for node.
17648 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17649
17650 // Starting off.
17651 Chains.push_back(OriginalChain);
17652 unsigned Depth = 0;
17653
17654 // Look at each chain and determine if it is an alias. If so, add it to the
17655 // aliases list. If not, then continue up the chain looking for the next
17656 // candidate.
17657 while (!Chains.empty()) {
17658 SDValue Chain = Chains.pop_back_val();
17659
17660 // For TokenFactor nodes, look at each operand and only continue up the
17661 // chain until we reach the depth limit.
17662 //
17663 // FIXME: The depth check could be made to return the last non-aliasing
17664 // chain we found before we hit a tokenfactor rather than the original
17665 // chain.
17666 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17667 Aliases.clear();
17668 Aliases.push_back(OriginalChain);
17669 return;
17670 }
17671
17672 // Don't bother if we've been before.
17673 if (!Visited.insert(Chain.getNode()).second)
17674 continue;
17675
17676 switch (Chain.getOpcode()) {
17677 case ISD::EntryToken:
17678 // Entry token is ideal chain operand, but handled in FindBetterChain.
17679 break;
17680
17681 case ISD::LOAD:
17682 case ISD::STORE: {
17683 // Get alias information for Chain.
17684 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17685 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17686
17687 // If chain is alias then stop here.
17688 if (!(IsLoad && IsOpLoad) &&
17689 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17690 Aliases.push_back(Chain);
17691 } else {
17692 // Look further up the chain.
17693 Chains.push_back(Chain.getOperand(0));
17694 ++Depth;
17695 }
17696 break;
17697 }
17698
17699 case ISD::TokenFactor:
17700 // We have to check each of the operands of the token factor for "small"
17701 // token factors, so we queue them up. Adding the operands to the queue
17702 // (stack) in reverse order maintains the original order and increases the
17703 // likelihood that getNode will find a matching token factor (CSE.)
17704 if (Chain.getNumOperands() > 16) {
17705 Aliases.push_back(Chain);
17706 break;
17707 }
17708 for (unsigned n = Chain.getNumOperands(); n;)
17709 Chains.push_back(Chain.getOperand(--n));
17710 ++Depth;
17711 break;
17712
17713 case ISD::CopyFromReg:
17714 // Forward past CopyFromReg.
17715 Chains.push_back(Chain.getOperand(0));
17716 ++Depth;
17717 break;
17718
17719 default:
17720 // For all other instructions we will just have to take what we can get.
17721 Aliases.push_back(Chain);
17722 break;
17723 }
17724 }
17725}
17726
17727/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17728/// (aliasing node.)
17729SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17730 if (OptLevel == CodeGenOpt::None)
17731 return OldChain;
17732
17733 // Ops for replacing token factor.
17734 SmallVector<SDValue, 8> Aliases;
17735
17736 // Accumulate all the aliases to this node.
17737 GatherAllAliases(N, OldChain, Aliases);
17738
17739 // If no operands then chain to entry token.
17740 if (Aliases.size() == 0)
17741 return DAG.getEntryNode();
17742
17743 // If a single operand then chain to it. We don't need to revisit it.
17744 if (Aliases.size() == 1)
17745 return Aliases[0];
17746
17747 // Construct a custom tailored token factor.
17748 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17749}
17750
17751// This function tries to collect a bunch of potentially interesting
17752// nodes to improve the chains of, all at once. This might seem
17753// redundant, as this function gets called when visiting every store
17754// node, so why not let the work be done on each store as it's visited?
17755//
17756// I believe this is mainly important because MergeConsecutiveStores
17757// is unable to deal with merging stores of different sizes, so unless
17758// we improve the chains of all the potential candidates up-front
17759// before running MergeConsecutiveStores, it might only see some of
17760// the nodes that will eventually be candidates, and then not be able
17761// to go from a partially-merged state to the desired final
17762// fully-merged state.
17763bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17764 if (OptLevel == CodeGenOpt::None)
17765 return false;
17766
17767 // This holds the base pointer, index, and the offset in bytes from the base
17768 // pointer.
17769 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
17770
17771 // We must have a base and an offset.
17772 if (!BasePtr.getBase().getNode())
17773 return false;
17774
17775 // Do not handle stores to undef base pointers.
17776 if (BasePtr.getBase().isUndef())
17777 return false;
17778
17779 SmallVector<StoreSDNode *, 8> ChainedStores;
17780 ChainedStores.push_back(St);
17781
17782 // Walk up the chain and look for nodes with offsets from the same
17783 // base pointer. Stop when reaching an instruction with a different kind
17784 // or instruction which has a different base pointer.
17785 StoreSDNode *Index = St;
17786 while (Index) {
17787 // If the chain has more than one use, then we can't reorder the mem ops.
17788 if (Index != St && !SDValue(Index, 0)->hasOneUse())
17789 break;
17790
17791 if (Index->isVolatile() || Index->isIndexed())
17792 break;
17793
17794 // Find the base pointer and offset for this memory node.
17795 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG);
17796
17797 // Check that the base pointer is the same as the original one.
17798 if (!BasePtr.equalBaseIndex(Ptr, DAG))
17799 break;
17800
17801 // Walk up the chain to find the next store node, ignoring any
17802 // intermediate loads. Any other kind of node will halt the loop.
17803 SDNode *NextInChain = Index->getChain().getNode();
17804 while (true) {
17805 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17806 // We found a store node. Use it for the next iteration.
17807 if (STn->isVolatile() || STn->isIndexed()) {
17808 Index = nullptr;
17809 break;
17810 }
17811 ChainedStores.push_back(STn);
17812 Index = STn;
17813 break;
17814 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17815 NextInChain = Ldn->getChain().getNode();
17816 continue;
17817 } else {
17818 Index = nullptr;
17819 break;
17820 }
17821 } // end while
17822 }
17823
17824 // At this point, ChainedStores lists all of the Store nodes
17825 // reachable by iterating up through chain nodes matching the above
17826 // conditions. For each such store identified, try to find an
17827 // earlier chain to attach the store to which won't violate the
17828 // required ordering.
17829 bool MadeChangeToSt = false;
17830 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17831
17832 for (StoreSDNode *ChainedStore : ChainedStores) {
17833 SDValue Chain = ChainedStore->getChain();
17834 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17835
17836 if (Chain != BetterChain) {
17837 if (ChainedStore == St)
17838 MadeChangeToSt = true;
17839 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17840 }
17841 }
17842
17843 // Do all replacements after finding the replacements to make to avoid making
17844 // the chains more complicated by introducing new TokenFactors.
17845 for (auto Replacement : BetterChains)
17846 replaceStoreChain(Replacement.first, Replacement.second);
17847
17848 return MadeChangeToSt;
17849}
17850
17851/// This is the entry point for the file.
17852void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17853 CodeGenOpt::Level OptLevel) {
17854 /// This is the main entry point to this class.
17855 DAGCombiner(*this, AA, OptLevel).Run(Level);
17856}

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h

1//===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SmallBitVector class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_SMALLBITVECTOR_H
15#define LLVM_ADT_SMALLBITVECTOR_H
16
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/iterator_range.h"
19#include "llvm/Support/MathExtras.h"
20#include <algorithm>
21#include <cassert>
22#include <climits>
23#include <cstddef>
24#include <cstdint>
25#include <limits>
26#include <utility>
27
28namespace llvm {
29
30/// This is a 'bitvector' (really, a variable-sized bit array), optimized for
31/// the case when the array is small. It contains one pointer-sized field, which
32/// is directly used as a plain collection of bits when possible, or as a
33/// pointer to a larger heap-allocated array when necessary. This allows normal
34/// "small" cases to be fast without losing generality for large inputs.
35class SmallBitVector {
36 // TODO: In "large" mode, a pointer to a BitVector is used, leading to an
37 // unnecessary level of indirection. It would be more efficient to use a
38 // pointer to memory containing size, allocation size, and the array of bits.
39 uintptr_t X = 1;
40
41 enum {
42 // The number of bits in this class.
43 NumBaseBits = sizeof(uintptr_t) * CHAR_BIT8,
44
45 // One bit is used to discriminate between small and large mode. The
46 // remaining bits are used for the small-mode representation.
47 SmallNumRawBits = NumBaseBits - 1,
48
49 // A few more bits are used to store the size of the bit set in small mode.
50 // Theoretically this is a ceil-log2. These bits are encoded in the most
51 // significant bits of the raw bits.
52 SmallNumSizeBits = (NumBaseBits == 32 ? 5 :
53 NumBaseBits == 64 ? 6 :
54 SmallNumRawBits),
55
56 // The remaining bits are used to store the actual set in small mode.
57 SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits
58 };
59
60 static_assert(NumBaseBits == 64 || NumBaseBits == 32,
61 "Unsupported word size");
62
63public:
64 using size_type = unsigned;
65
66 // Encapsulation of a single bit.
67 class reference {
68 SmallBitVector &TheVector;
69 unsigned BitPos;
70
71 public:
72 reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {}
73
74 reference(const reference&) = default;
75
76 reference& operator=(reference t) {
77 *this = bool(t);
78 return *this;
79 }
80
81 reference& operator=(bool t) {
82 if (t)
83 TheVector.set(BitPos);
84 else
85 TheVector.reset(BitPos);
86 return *this;
87 }
88
89 operator bool() const {
90 return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos);
91 }
92 };
93
94private:
95 bool isSmall() const {
96 return X & uintptr_t(1);
97 }
98
99 BitVector *getPointer() const {
100 assert(!isSmall())(static_cast <bool> (!isSmall()) ? void (0) : __assert_fail
("!isSmall()", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 100, __extension__ __PRETTY_FUNCTION__))
;
101 return reinterpret_cast<BitVector *>(X);
102 }
103
104 void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) {
105 X = 1;
106 setSmallSize(NewSize);
107 setSmallBits(NewSmallBits);
108 }
109
110 void switchToLarge(BitVector *BV) {
111 X = reinterpret_cast<uintptr_t>(BV);
112 assert(!isSmall() && "Tried to use an unaligned pointer")(static_cast <bool> (!isSmall() && "Tried to use an unaligned pointer"
) ? void (0) : __assert_fail ("!isSmall() && \"Tried to use an unaligned pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 112, __extension__ __PRETTY_FUNCTION__))
;
113 }
114
115 // Return all the bits used for the "small" representation; this includes
116 // bits for the size as well as the element bits.
117 uintptr_t getSmallRawBits() const {
118 assert(isSmall())(static_cast <bool> (isSmall()) ? void (0) : __assert_fail
("isSmall()", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 118, __extension__ __PRETTY_FUNCTION__))
;
119 return X >> 1;
120 }
121
122 void setSmallRawBits(uintptr_t NewRawBits) {
123 assert(isSmall())(static_cast <bool> (isSmall()) ? void (0) : __assert_fail
("isSmall()", "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 123, __extension__ __PRETTY_FUNCTION__))
;
124 X = (NewRawBits << 1) | uintptr_t(1);
125 }
126
127 // Return the size.
128 size_t getSmallSize() const { return getSmallRawBits() >> SmallNumDataBits; }
129
130 void setSmallSize(size_t Size) {
131 setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits));
132 }
133
134 // Return the element bits.
135 uintptr_t getSmallBits() const {
136 return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize());
137 }
138
139 void setSmallBits(uintptr_t NewBits) {
140 setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) |
141 (getSmallSize() << SmallNumDataBits));
142 }
143
144public:
145 /// Creates an empty bitvector.
146 SmallBitVector() = default;
147
148 /// Creates a bitvector of specified number of bits. All bits are initialized
149 /// to the specified value.
150 explicit SmallBitVector(unsigned s, bool t = false) {
151 if (s <= SmallNumDataBits)
10
Assuming 's' is > SmallNumDataBits
11
Taking false branch
152 switchToSmall(t ? ~uintptr_t(0) : 0, s);
153 else
154 switchToLarge(new BitVector(s, t));
12
Memory is allocated
155 }
156
157 /// SmallBitVector copy ctor.
158 SmallBitVector(const SmallBitVector &RHS) {
159 if (RHS.isSmall())
160 X = RHS.X;
161 else
162 switchToLarge(new BitVector(*RHS.getPointer()));
163 }
164
165 SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) {
166 RHS.X = 1;
167 }
168
169 ~SmallBitVector() {
170 if (!isSmall())
171 delete getPointer();
172 }
173
174 using const_set_bits_iterator = const_set_bits_iterator_impl<SmallBitVector>;
175 using set_iterator = const_set_bits_iterator;
176
177 const_set_bits_iterator set_bits_begin() const {
178 return const_set_bits_iterator(*this);
179 }
180
181 const_set_bits_iterator set_bits_end() const {
182 return const_set_bits_iterator(*this, -1);
183 }
184
185 iterator_range<const_set_bits_iterator> set_bits() const {
186 return make_range(set_bits_begin(), set_bits_end());
187 }
188
189 /// Tests whether there are no bits in this bitvector.
190 bool empty() const {
191 return isSmall() ? getSmallSize() == 0 : getPointer()->empty();
192 }
193
194 /// Returns the number of bits in this bitvector.
195 size_t size() const {
196 return isSmall() ? getSmallSize() : getPointer()->size();
197 }
198
199 /// Returns the number of bits which are set.
200 size_type count() const {
201 if (isSmall()) {
202 uintptr_t Bits = getSmallBits();
203 return countPopulation(Bits);
204 }
205 return getPointer()->count();
206 }
207
208 /// Returns true if any bit is set.
209 bool any() const {
210 if (isSmall())
211 return getSmallBits() != 0;
212 return getPointer()->any();
213 }
214
215 /// Returns true if all bits are set.
216 bool all() const {
217 if (isSmall())
218 return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1;
219 return getPointer()->all();
220 }
221
222 /// Returns true if none of the bits are set.
223 bool none() const {
224 if (isSmall())
225 return getSmallBits() == 0;
226 return getPointer()->none();
227 }
228
229 /// Returns the index of the first set bit, -1 if none of the bits are set.
230 int find_first() const {
231 if (isSmall()) {
232 uintptr_t Bits = getSmallBits();
233 if (Bits == 0)
234 return -1;
235 return countTrailingZeros(Bits);
236 }
237 return getPointer()->find_first();
238 }
239
240 int find_last() const {
241 if (isSmall()) {
242 uintptr_t Bits = getSmallBits();
243 if (Bits == 0)
244 return -1;
245 return NumBaseBits - countLeadingZeros(Bits);
246 }
247 return getPointer()->find_last();
248 }
249
250 /// Returns the index of the first unset bit, -1 if all of the bits are set.
251 int find_first_unset() const {
252 if (isSmall()) {
253 if (count() == getSmallSize())
254 return -1;
255
256 uintptr_t Bits = getSmallBits();
257 return countTrailingOnes(Bits);
258 }
259 return getPointer()->find_first_unset();
260 }
261
262 int find_last_unset() const {
263 if (isSmall()) {
264 if (count() == getSmallSize())
265 return -1;
266
267 uintptr_t Bits = getSmallBits();
268 return NumBaseBits - countLeadingOnes(Bits);
269 }
270 return getPointer()->find_last_unset();
271 }
272
273 /// Returns the index of the next set bit following the "Prev" bit.
274 /// Returns -1 if the next set bit is not found.
275 int find_next(unsigned Prev) const {
276 if (isSmall()) {
277 uintptr_t Bits = getSmallBits();
278 // Mask off previous bits.
279 Bits &= ~uintptr_t(0) << (Prev + 1);
280 if (Bits == 0 || Prev + 1 >= getSmallSize())
281 return -1;
282 return countTrailingZeros(Bits);
283 }
284 return getPointer()->find_next(Prev);
285 }
286
287 /// Returns the index of the next unset bit following the "Prev" bit.
288 /// Returns -1 if the next unset bit is not found.
289 int find_next_unset(unsigned Prev) const {
290 if (isSmall()) {
291 ++Prev;
292 uintptr_t Bits = getSmallBits();
293 // Mask in previous bits.
294 uintptr_t Mask = (1 << Prev) - 1;
295 Bits |= Mask;
296
297 if (Bits == ~uintptr_t(0) || Prev + 1 >= getSmallSize())
298 return -1;
299 return countTrailingOnes(Bits);
300 }
301 return getPointer()->find_next_unset(Prev);
302 }
303
304 /// find_prev - Returns the index of the first set bit that precedes the
305 /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
306 int find_prev(unsigned PriorTo) const {
307 if (isSmall()) {
308 if (PriorTo == 0)
309 return -1;
310
311 --PriorTo;
312 uintptr_t Bits = getSmallBits();
313 Bits &= maskTrailingOnes<uintptr_t>(PriorTo + 1);
314 if (Bits == 0)
315 return -1;
316
317 return NumBaseBits - countLeadingZeros(Bits) - 1;
318 }
319 return getPointer()->find_prev(PriorTo);
320 }
321
322 /// Clear all bits.
323 void clear() {
324 if (!isSmall())
325 delete getPointer();
326 switchToSmall(0, 0);
327 }
328
329 /// Grow or shrink the bitvector.
330 void resize(unsigned N, bool t = false) {
331 if (!isSmall()) {
332 getPointer()->resize(N, t);
333 } else if (SmallNumDataBits >= N) {
334 uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0;
335 setSmallSize(N);
336 setSmallBits(NewBits | getSmallBits());
337 } else {
338 BitVector *BV = new BitVector(N, t);
339 uintptr_t OldBits = getSmallBits();
340 for (size_t i = 0, e = getSmallSize(); i != e; ++i)
341 (*BV)[i] = (OldBits >> i) & 1;
342 switchToLarge(BV);
343 }
344 }
345
346 void reserve(unsigned N) {
347 if (isSmall()) {
348 if (N > SmallNumDataBits) {
349 uintptr_t OldBits = getSmallRawBits();
350 size_t SmallSize = getSmallSize();
351 BitVector *BV = new BitVector(SmallSize);
352 for (size_t i = 0; i < SmallSize; ++i)
353 if ((OldBits >> i) & 1)
354 BV->set(i);
355 BV->reserve(N);
356 switchToLarge(BV);
357 }
358 } else {
359 getPointer()->reserve(N);
360 }
361 }
362
363 // Set, reset, flip
364 SmallBitVector &set() {
365 if (isSmall())
366 setSmallBits(~uintptr_t(0));
367 else
368 getPointer()->set();
369 return *this;
370 }
371
372 SmallBitVector &set(unsigned Idx) {
373 if (isSmall()) {
374 assert(Idx <= static_cast<unsigned>((static_cast <bool> (Idx <= static_cast<unsigned>
( std::numeric_limits<uintptr_t>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 376, __extension__ __PRETTY_FUNCTION__))
375 std::numeric_limits<uintptr_t>::digits) &&(static_cast <bool> (Idx <= static_cast<unsigned>
( std::numeric_limits<uintptr_t>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 376, __extension__ __PRETTY_FUNCTION__))
376 "undefined behavior")(static_cast <bool> (Idx <= static_cast<unsigned>
( std::numeric_limits<uintptr_t>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 376, __extension__ __PRETTY_FUNCTION__))
;
377 setSmallBits(getSmallBits() | (uintptr_t(1) << Idx));
378 }
379 else
380 getPointer()->set(Idx);
381 return *this;
382 }
383
384 /// Efficiently set a range of bits in [I, E)
385 SmallBitVector &set(unsigned I, unsigned E) {
386 assert(I <= E && "Attempted to set backwards range!")(static_cast <bool> (I <= E && "Attempted to set backwards range!"
) ? void (0) : __assert_fail ("I <= E && \"Attempted to set backwards range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 386, __extension__ __PRETTY_FUNCTION__))
;
387 assert(E <= size() && "Attempted to set out-of-bounds range!")(static_cast <bool> (E <= size() && "Attempted to set out-of-bounds range!"
) ? void (0) : __assert_fail ("E <= size() && \"Attempted to set out-of-bounds range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 387, __extension__ __PRETTY_FUNCTION__))
;
388 if (I == E) return *this;
389 if (isSmall()) {
390 uintptr_t EMask = ((uintptr_t)1) << E;
391 uintptr_t IMask = ((uintptr_t)1) << I;
392 uintptr_t Mask = EMask - IMask;
393 setSmallBits(getSmallBits() | Mask);
394 } else
395 getPointer()->set(I, E);
396 return *this;
397 }
398
399 SmallBitVector &reset() {
400 if (isSmall())
401 setSmallBits(0);
402 else
403 getPointer()->reset();
404 return *this;
405 }
406
407 SmallBitVector &reset(unsigned Idx) {
408 if (isSmall())
409 setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx));
410 else
411 getPointer()->reset(Idx);
412 return *this;
413 }
414
415 /// Efficiently reset a range of bits in [I, E)
416 SmallBitVector &reset(unsigned I, unsigned E) {
417 assert(I <= E && "Attempted to reset backwards range!")(static_cast <bool> (I <= E && "Attempted to reset backwards range!"
) ? void (0) : __assert_fail ("I <= E && \"Attempted to reset backwards range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 417, __extension__ __PRETTY_FUNCTION__))
;
418 assert(E <= size() && "Attempted to reset out-of-bounds range!")(static_cast <bool> (E <= size() && "Attempted to reset out-of-bounds range!"
) ? void (0) : __assert_fail ("E <= size() && \"Attempted to reset out-of-bounds range!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 418, __extension__ __PRETTY_FUNCTION__))
;
419 if (I == E) return *this;
420 if (isSmall()) {
421 uintptr_t EMask = ((uintptr_t)1) << E;
422 uintptr_t IMask = ((uintptr_t)1) << I;
423 uintptr_t Mask = EMask - IMask;
424 setSmallBits(getSmallBits() & ~Mask);
425 } else
426 getPointer()->reset(I, E);
427 return *this;
428 }
429
430 SmallBitVector &flip() {
431 if (isSmall())
432 setSmallBits(~getSmallBits());
433 else
434 getPointer()->flip();
435 return *this;
436 }
437
438 SmallBitVector &flip(unsigned Idx) {
439 if (isSmall())
440 setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx));
441 else
442 getPointer()->flip(Idx);
443 return *this;
444 }
445
446 // No argument flip.
447 SmallBitVector operator~() const {
448 return SmallBitVector(*this).flip();
449 }
450
451 // Indexing.
452 reference operator[](unsigned Idx) {
453 assert(Idx < size() && "Out-of-bounds Bit access.")(static_cast <bool> (Idx < size() && "Out-of-bounds Bit access."
) ? void (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 453, __extension__ __PRETTY_FUNCTION__))
;
454 return reference(*this, Idx);
455 }
456
457 bool operator[](unsigned Idx) const {
458 assert(Idx < size() && "Out-of-bounds Bit access.")(static_cast <bool> (Idx < size() && "Out-of-bounds Bit access."
) ? void (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 458, __extension__ __PRETTY_FUNCTION__))
;
459 if (isSmall())
460 return ((getSmallBits() >> Idx) & 1) != 0;
461 return getPointer()->operator[](Idx);
462 }
463
464 bool test(unsigned Idx) const {
465 return (*this)[Idx];
466 }
467
468 /// Test if any common bits are set.
469 bool anyCommon(const SmallBitVector &RHS) const {
470 if (isSmall() && RHS.isSmall())
471 return (getSmallBits() & RHS.getSmallBits()) != 0;
472 if (!isSmall() && !RHS.isSmall())
473 return getPointer()->anyCommon(*RHS.getPointer());
474
475 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
476 if (test(i) && RHS.test(i))
477 return true;
478 return false;
479 }
480
481 // Comparison operators.
482 bool operator==(const SmallBitVector &RHS) const {
483 if (size() != RHS.size())
484 return false;
485 if (isSmall())
486 return getSmallBits() == RHS.getSmallBits();
487 else
488 return *getPointer() == *RHS.getPointer();
489 }
490
491 bool operator!=(const SmallBitVector &RHS) const {
492 return !(*this == RHS);
493 }
494
495 // Intersection, union, disjoint union.
496 SmallBitVector &operator&=(const SmallBitVector &RHS) {
497 resize(std::max(size(), RHS.size()));
498 if (isSmall())
499 setSmallBits(getSmallBits() & RHS.getSmallBits());
500 else if (!RHS.isSmall())
501 getPointer()->operator&=(*RHS.getPointer());
502 else {
503 SmallBitVector Copy = RHS;
504 Copy.resize(size());
505 getPointer()->operator&=(*Copy.getPointer());
506 }
507 return *this;
508 }
509
510 /// Reset bits that are set in RHS. Same as *this &= ~RHS.
511 SmallBitVector &reset(const SmallBitVector &RHS) {
512 if (isSmall() && RHS.isSmall())
513 setSmallBits(getSmallBits() & ~RHS.getSmallBits());
514 else if (!isSmall() && !RHS.isSmall())
515 getPointer()->reset(*RHS.getPointer());
516 else
517 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
518 if (RHS.test(i))
519 reset(i);
520
521 return *this;
522 }
523
524 /// Check if (This - RHS) is zero. This is the same as reset(RHS) and any().
525 bool test(const SmallBitVector &RHS) const {
526 if (isSmall() && RHS.isSmall())
527 return (getSmallBits() & ~RHS.getSmallBits()) != 0;
528 if (!isSmall() && !RHS.isSmall())
529 return getPointer()->test(*RHS.getPointer());
530
531 unsigned i, e;
532 for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
533 if (test(i) && !RHS.test(i))
534 return true;
535
536 for (e = size(); i != e; ++i)
537 if (test(i))
538 return true;
539
540 return false;
541 }
542
543 SmallBitVector &operator|=(const SmallBitVector &RHS) {
544 resize(std::max(size(), RHS.size()));
545 if (isSmall())
546 setSmallBits(getSmallBits() | RHS.getSmallBits());
547 else if (!RHS.isSmall())
548 getPointer()->operator|=(*RHS.getPointer());
549 else {
550 SmallBitVector Copy = RHS;
551 Copy.resize(size());
552 getPointer()->operator|=(*Copy.getPointer());
553 }
554 return *this;
555 }
556
557 SmallBitVector &operator^=(const SmallBitVector &RHS) {
558 resize(std::max(size(), RHS.size()));
559 if (isSmall())
560 setSmallBits(getSmallBits() ^ RHS.getSmallBits());
561 else if (!RHS.isSmall())
562 getPointer()->operator^=(*RHS.getPointer());
563 else {
564 SmallBitVector Copy = RHS;
565 Copy.resize(size());
566 getPointer()->operator^=(*Copy.getPointer());
567 }
568 return *this;
569 }
570
571 SmallBitVector &operator<<=(unsigned N) {
572 if (isSmall())
573 setSmallBits(getSmallBits() << N);
574 else
575 getPointer()->operator<<=(N);
576 return *this;
577 }
578
579 SmallBitVector &operator>>=(unsigned N) {
580 if (isSmall())
581 setSmallBits(getSmallBits() >> N);
582 else
583 getPointer()->operator>>=(N);
584 return *this;
585 }
586
587 // Assignment operator.
588 const SmallBitVector &operator=(const SmallBitVector &RHS) {
589 if (isSmall()) {
590 if (RHS.isSmall())
591 X = RHS.X;
592 else
593 switchToLarge(new BitVector(*RHS.getPointer()));
594 } else {
595 if (!RHS.isSmall())
596 *getPointer() = *RHS.getPointer();
597 else {
598 delete getPointer();
599 X = RHS.X;
600 }
601 }
602 return *this;
603 }
604
605 const SmallBitVector &operator=(SmallBitVector &&RHS) {
606 if (this != &RHS) {
607 clear();
608 swap(RHS);
609 }
610 return *this;
611 }
612
613 void swap(SmallBitVector &RHS) {
614 std::swap(X, RHS.X);
615 }
616
617 /// Add '1' bits from Mask to this vector. Don't resize.
618 /// This computes "*this |= Mask".
619 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
620 if (isSmall())
621 applyMask<true, false>(Mask, MaskWords);
622 else
623 getPointer()->setBitsInMask(Mask, MaskWords);
624 }
625
626 /// Clear any bits in this vector that are set in Mask. Don't resize.
627 /// This computes "*this &= ~Mask".
628 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
629 if (isSmall())
630 applyMask<false, false>(Mask, MaskWords);
631 else
632 getPointer()->clearBitsInMask(Mask, MaskWords);
633 }
634
635 /// Add a bit to this vector for every '0' bit in Mask. Don't resize.
636 /// This computes "*this |= ~Mask".
637 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
638 if (isSmall())
639 applyMask<true, true>(Mask, MaskWords);
640 else
641 getPointer()->setBitsNotInMask(Mask, MaskWords);
642 }
643
644 /// Clear a bit in this vector for every '0' bit in Mask. Don't resize.
645 /// This computes "*this &= Mask".
646 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
647 if (isSmall())
648 applyMask<false, true>(Mask, MaskWords);
649 else
650 getPointer()->clearBitsNotInMask(Mask, MaskWords);
651 }
652
653private:
654 template <bool AddBits, bool InvertMask>
655 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
656 assert(MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!")(static_cast <bool> (MaskWords <= sizeof(uintptr_t) &&
"Mask is larger than base!") ? void (0) : __assert_fail ("MaskWords <= sizeof(uintptr_t) && \"Mask is larger than base!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/ADT/SmallBitVector.h"
, 656, __extension__ __PRETTY_FUNCTION__))
;
657 uintptr_t M = Mask[0];
658 if (NumBaseBits == 64)
659 M |= uint64_t(Mask[1]) << 32;
660 if (InvertMask)
661 M = ~M;
662 if (AddBits)
663 setSmallBits(getSmallBits() | M);
664 else
665 setSmallBits(getSmallBits() & ~M);
666 }
667};
668
669inline SmallBitVector
670operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) {
671 SmallBitVector Result(LHS);
672 Result &= RHS;
673 return Result;
674}
675
676inline SmallBitVector
677operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) {
678 SmallBitVector Result(LHS);
679 Result |= RHS;
680 return Result;
681}
682
683inline SmallBitVector
684operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) {
685 SmallBitVector Result(LHS);
686 Result ^= RHS;
687 return Result;
688}
689
690} // end namespace llvm
691
692namespace std {
693
694/// Implement std::swap in terms of BitVector swap.
695inline void
696swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) {
697 LHS.swap(RHS);
698}
699
700} // end namespace std
701
702#endif // LLVM_ADT_SMALLBITVECTOR_H