[LLVM][Alignment] Introduce Alignment In MachineFrameInfo
[llvm-complete.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
blob2672f2021018d16de2eccab270b031ecd02f4b07
1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
10 // both before and after the DAG is legalized.
12 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
13 // primarily intended to handle simplification opportunities that are implicit
14 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntervalMap.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/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/CodeGen/DAGCombine.h"
34 #include "llvm/CodeGen/ISDOpcodes.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CodeGen.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/KnownBits.h"
61 #include "llvm/Support/MachineValueType.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetOptions.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <functional>
70 #include <iterator>
71 #include <string>
72 #include <tuple>
73 #include <utility>
75 using namespace llvm;
77 #define DEBUG_TYPE "dagcombine"
79 STATISTIC(NodesCombined , "Number of dag nodes combined");
80 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
81 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
82 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
83 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
84 STATISTIC(SlicedLoads, "Number of load sliced");
85 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
87 static cl::opt<bool>
88 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
89 cl::desc("Enable DAG combiner's use of IR alias analysis"));
91 static cl::opt<bool>
92 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
93 cl::desc("Enable DAG combiner's use of TBAA"));
95 #ifndef NDEBUG
96 static cl::opt<std::string>
97 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
98 cl::desc("Only use DAG-combiner alias analysis in this"
99 " function"));
100 #endif
102 /// Hidden option to stress test load slicing, i.e., when this option
103 /// is enabled, load slicing bypasses most of its profitability guards.
104 static cl::opt<bool>
105 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
106 cl::desc("Bypass the profitability model of load slicing"),
107 cl::init(false));
109 static cl::opt<bool>
110 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
111 cl::desc("DAG combiner may split indexing from loads"));
113 static cl::opt<bool>
114 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
115 cl::desc("DAG combiner enable merging multiple stores "
116 "into a wider store"));
118 static cl::opt<unsigned> TokenFactorInlineLimit(
119 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
120 cl::desc("Limit the number of operands to inline for Token Factors"));
122 static cl::opt<unsigned> StoreMergeDependenceLimit(
123 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
124 cl::desc("Limit the number of times for the same StoreNode and RootNode "
125 "to bail out in store merging dependence check"));
127 namespace {
129 class DAGCombiner {
130 SelectionDAG &DAG;
131 const TargetLowering &TLI;
132 CombineLevel Level;
133 CodeGenOpt::Level OptLevel;
134 bool LegalOperations = false;
135 bool LegalTypes = false;
136 bool ForCodeSize;
138 /// Worklist of all of the nodes that need to be simplified.
140 /// This must behave as a stack -- new nodes to process are pushed onto the
141 /// back and when processing we pop off of the back.
143 /// The worklist will not contain duplicates but may contain null entries
144 /// due to nodes being deleted from the underlying DAG.
145 SmallVector<SDNode *, 64> Worklist;
147 /// Mapping from an SDNode to its position on the worklist.
149 /// This is used to find and remove nodes from the worklist (by nulling
150 /// them) when they are deleted from the underlying DAG. It relies on
151 /// stable indices of nodes within the worklist.
152 DenseMap<SDNode *, unsigned> WorklistMap;
153 /// This records all nodes attempted to add to the worklist since we
154 /// considered a new worklist entry. As we keep do not add duplicate nodes
155 /// in the worklist, this is different from the tail of the worklist.
156 SmallSetVector<SDNode *, 32> PruningList;
158 /// Set of nodes which have been combined (at least once).
160 /// This is used to allow us to reliably add any operands of a DAG node
161 /// which have not yet been combined to the worklist.
162 SmallPtrSet<SDNode *, 32> CombinedNodes;
164 /// Map from candidate StoreNode to the pair of RootNode and count.
165 /// The count is used to track how many times we have seen the StoreNode
166 /// with the same RootNode bail out in dependence check. If we have seen
167 /// the bail out for the same pair many times over a limit, we won't
168 /// consider the StoreNode with the same RootNode as store merging
169 /// candidate again.
170 DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap;
172 // AA - Used for DAG load/store alias analysis.
173 AliasAnalysis *AA;
175 /// When an instruction is simplified, add all users of the instruction to
176 /// the work lists because they might get more simplified now.
177 void AddUsersToWorklist(SDNode *N) {
178 for (SDNode *Node : N->uses())
179 AddToWorklist(Node);
182 // Prune potentially dangling nodes. This is called after
183 // any visit to a node, but should also be called during a visit after any
184 // failed combine which may have created a DAG node.
185 void clearAddedDanglingWorklistEntries() {
186 // Check any nodes added to the worklist to see if they are prunable.
187 while (!PruningList.empty()) {
188 auto *N = PruningList.pop_back_val();
189 if (N->use_empty())
190 recursivelyDeleteUnusedNodes(N);
194 SDNode *getNextWorklistEntry() {
195 // Before we do any work, remove nodes that are not in use.
196 clearAddedDanglingWorklistEntries();
197 SDNode *N = nullptr;
198 // The Worklist holds the SDNodes in order, but it may contain null
199 // entries.
200 while (!N && !Worklist.empty()) {
201 N = Worklist.pop_back_val();
204 if (N) {
205 bool GoodWorklistEntry = WorklistMap.erase(N);
206 (void)GoodWorklistEntry;
207 assert(GoodWorklistEntry &&
208 "Found a worklist entry without a corresponding map entry!");
210 return N;
213 /// Call the node-specific routine that folds each particular type of node.
214 SDValue visit(SDNode *N);
216 public:
217 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
218 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
219 OptLevel(OL), AA(AA) {
220 ForCodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
222 MaximumLegalStoreInBits = 0;
223 for (MVT VT : MVT::all_valuetypes())
224 if (EVT(VT).isSimple() && VT != MVT::Other &&
225 TLI.isTypeLegal(EVT(VT)) &&
226 VT.getSizeInBits() >= MaximumLegalStoreInBits)
227 MaximumLegalStoreInBits = VT.getSizeInBits();
230 void ConsiderForPruning(SDNode *N) {
231 // Mark this for potential pruning.
232 PruningList.insert(N);
235 /// Add to the worklist making sure its instance is at the back (next to be
236 /// processed.)
237 void AddToWorklist(SDNode *N) {
238 assert(N->getOpcode() != ISD::DELETED_NODE &&
239 "Deleted Node added to Worklist");
241 // Skip handle nodes as they can't usefully be combined and confuse the
242 // zero-use deletion strategy.
243 if (N->getOpcode() == ISD::HANDLENODE)
244 return;
246 ConsiderForPruning(N);
248 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
249 Worklist.push_back(N);
252 /// Remove all instances of N from the worklist.
253 void removeFromWorklist(SDNode *N) {
254 CombinedNodes.erase(N);
255 PruningList.remove(N);
256 StoreRootCountMap.erase(N);
258 auto It = WorklistMap.find(N);
259 if (It == WorklistMap.end())
260 return; // Not in the worklist.
262 // Null out the entry rather than erasing it to avoid a linear operation.
263 Worklist[It->second] = nullptr;
264 WorklistMap.erase(It);
267 void deleteAndRecombine(SDNode *N);
268 bool recursivelyDeleteUnusedNodes(SDNode *N);
270 /// Replaces all uses of the results of one DAG node with new values.
271 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
272 bool AddTo = true);
274 /// Replaces all uses of the results of one DAG node with new values.
275 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
276 return CombineTo(N, &Res, 1, AddTo);
279 /// Replaces all uses of the results of one DAG node with new values.
280 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
281 bool AddTo = true) {
282 SDValue To[] = { Res0, Res1 };
283 return CombineTo(N, To, 2, AddTo);
286 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
288 private:
289 unsigned MaximumLegalStoreInBits;
291 /// Check the specified integer node value to see if it can be simplified or
292 /// if things it uses can be simplified by bit propagation.
293 /// If so, return true.
294 bool SimplifyDemandedBits(SDValue Op) {
295 unsigned BitWidth = Op.getScalarValueSizeInBits();
296 APInt DemandedBits = APInt::getAllOnesValue(BitWidth);
297 return SimplifyDemandedBits(Op, DemandedBits);
300 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
301 EVT VT = Op.getValueType();
302 unsigned NumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
303 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
304 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts);
307 /// Check the specified vector node value to see if it can be simplified or
308 /// if things it uses can be simplified as it only uses some of the
309 /// elements. If so, return true.
310 bool SimplifyDemandedVectorElts(SDValue Op) {
311 unsigned NumElts = Op.getValueType().getVectorNumElements();
312 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
313 return SimplifyDemandedVectorElts(Op, DemandedElts);
316 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
317 const APInt &DemandedElts);
318 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
319 bool AssumeSingleUse = false);
321 bool CombineToPreIndexedLoadStore(SDNode *N);
322 bool CombineToPostIndexedLoadStore(SDNode *N);
323 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
324 bool SliceUpLoad(SDNode *N);
326 // Scalars have size 0 to distinguish from singleton vectors.
327 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
328 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
329 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
331 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
332 /// load.
334 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
335 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
336 /// \param EltNo index of the vector element to load.
337 /// \param OriginalLoad load that EVE came from to be replaced.
338 /// \returns EVE on success SDValue() on failure.
339 SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
340 SDValue EltNo,
341 LoadSDNode *OriginalLoad);
342 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
343 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
344 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
345 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
346 SDValue PromoteIntBinOp(SDValue Op);
347 SDValue PromoteIntShiftOp(SDValue Op);
348 SDValue PromoteExtend(SDValue Op);
349 bool PromoteLoad(SDValue Op);
351 /// Call the node-specific routine that knows how to fold each
352 /// particular type of node. If that doesn't do anything, try the
353 /// target-specific DAG combines.
354 SDValue combine(SDNode *N);
356 // Visitation implementation - Implement dag node combining for different
357 // node types. The semantics are as follows:
358 // Return Value:
359 // SDValue.getNode() == 0 - No change was made
360 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
361 // otherwise - N should be replaced by the returned Operand.
363 SDValue visitTokenFactor(SDNode *N);
364 SDValue visitMERGE_VALUES(SDNode *N);
365 SDValue visitADD(SDNode *N);
366 SDValue visitADDLike(SDNode *N);
367 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference);
368 SDValue visitSUB(SDNode *N);
369 SDValue visitADDSAT(SDNode *N);
370 SDValue visitSUBSAT(SDNode *N);
371 SDValue visitADDC(SDNode *N);
372 SDValue visitADDO(SDNode *N);
373 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
374 SDValue visitSUBC(SDNode *N);
375 SDValue visitSUBO(SDNode *N);
376 SDValue visitADDE(SDNode *N);
377 SDValue visitADDCARRY(SDNode *N);
378 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
379 SDValue visitSUBE(SDNode *N);
380 SDValue visitSUBCARRY(SDNode *N);
381 SDValue visitMUL(SDNode *N);
382 SDValue visitMULFIX(SDNode *N);
383 SDValue useDivRem(SDNode *N);
384 SDValue visitSDIV(SDNode *N);
385 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
386 SDValue visitUDIV(SDNode *N);
387 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
388 SDValue visitREM(SDNode *N);
389 SDValue visitMULHU(SDNode *N);
390 SDValue visitMULHS(SDNode *N);
391 SDValue visitSMUL_LOHI(SDNode *N);
392 SDValue visitUMUL_LOHI(SDNode *N);
393 SDValue visitMULO(SDNode *N);
394 SDValue visitIMINMAX(SDNode *N);
395 SDValue visitAND(SDNode *N);
396 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
397 SDValue visitOR(SDNode *N);
398 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
399 SDValue visitXOR(SDNode *N);
400 SDValue SimplifyVBinOp(SDNode *N);
401 SDValue visitSHL(SDNode *N);
402 SDValue visitSRA(SDNode *N);
403 SDValue visitSRL(SDNode *N);
404 SDValue visitFunnelShift(SDNode *N);
405 SDValue visitRotate(SDNode *N);
406 SDValue visitABS(SDNode *N);
407 SDValue visitBSWAP(SDNode *N);
408 SDValue visitBITREVERSE(SDNode *N);
409 SDValue visitCTLZ(SDNode *N);
410 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
411 SDValue visitCTTZ(SDNode *N);
412 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
413 SDValue visitCTPOP(SDNode *N);
414 SDValue visitSELECT(SDNode *N);
415 SDValue visitVSELECT(SDNode *N);
416 SDValue visitSELECT_CC(SDNode *N);
417 SDValue visitSETCC(SDNode *N);
418 SDValue visitSETCCCARRY(SDNode *N);
419 SDValue visitSIGN_EXTEND(SDNode *N);
420 SDValue visitZERO_EXTEND(SDNode *N);
421 SDValue visitANY_EXTEND(SDNode *N);
422 SDValue visitAssertExt(SDNode *N);
423 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
424 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
425 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
426 SDValue visitTRUNCATE(SDNode *N);
427 SDValue visitBITCAST(SDNode *N);
428 SDValue visitBUILD_PAIR(SDNode *N);
429 SDValue visitFADD(SDNode *N);
430 SDValue visitFSUB(SDNode *N);
431 SDValue visitFMUL(SDNode *N);
432 SDValue visitFMA(SDNode *N);
433 SDValue visitFDIV(SDNode *N);
434 SDValue visitFREM(SDNode *N);
435 SDValue visitFSQRT(SDNode *N);
436 SDValue visitFCOPYSIGN(SDNode *N);
437 SDValue visitFPOW(SDNode *N);
438 SDValue visitSINT_TO_FP(SDNode *N);
439 SDValue visitUINT_TO_FP(SDNode *N);
440 SDValue visitFP_TO_SINT(SDNode *N);
441 SDValue visitFP_TO_UINT(SDNode *N);
442 SDValue visitFP_ROUND(SDNode *N);
443 SDValue visitFP_ROUND_INREG(SDNode *N);
444 SDValue visitFP_EXTEND(SDNode *N);
445 SDValue visitFNEG(SDNode *N);
446 SDValue visitFABS(SDNode *N);
447 SDValue visitFCEIL(SDNode *N);
448 SDValue visitFTRUNC(SDNode *N);
449 SDValue visitFFLOOR(SDNode *N);
450 SDValue visitFMINNUM(SDNode *N);
451 SDValue visitFMAXNUM(SDNode *N);
452 SDValue visitFMINIMUM(SDNode *N);
453 SDValue visitFMAXIMUM(SDNode *N);
454 SDValue visitBRCOND(SDNode *N);
455 SDValue visitBR_CC(SDNode *N);
456 SDValue visitLOAD(SDNode *N);
458 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
459 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
461 SDValue visitSTORE(SDNode *N);
462 SDValue visitLIFETIME_END(SDNode *N);
463 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
464 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
465 SDValue visitBUILD_VECTOR(SDNode *N);
466 SDValue visitCONCAT_VECTORS(SDNode *N);
467 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
468 SDValue visitVECTOR_SHUFFLE(SDNode *N);
469 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
470 SDValue visitINSERT_SUBVECTOR(SDNode *N);
471 SDValue visitMLOAD(SDNode *N);
472 SDValue visitMSTORE(SDNode *N);
473 SDValue visitMGATHER(SDNode *N);
474 SDValue visitMSCATTER(SDNode *N);
475 SDValue visitFP_TO_FP16(SDNode *N);
476 SDValue visitFP16_TO_FP(SDNode *N);
477 SDValue visitVECREDUCE(SDNode *N);
479 SDValue visitFADDForFMACombine(SDNode *N);
480 SDValue visitFSUBForFMACombine(SDNode *N);
481 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
483 SDValue XformToShuffleWithZero(SDNode *N);
484 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
485 const SDLoc &DL, SDValue N0,
486 SDValue N1);
487 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
488 SDValue N1);
489 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
490 SDValue N1, SDNodeFlags Flags);
492 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
494 SDValue foldSelectOfConstants(SDNode *N);
495 SDValue foldVSelectOfConstants(SDNode *N);
496 SDValue foldBinOpIntoSelect(SDNode *BO);
497 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
498 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
499 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
500 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
501 SDValue N2, SDValue N3, ISD::CondCode CC,
502 bool NotExtCompare = false);
503 SDValue convertSelectOfFPConstantsToLoadOffset(
504 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
505 ISD::CondCode CC);
506 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
507 SDValue N2, SDValue N3, ISD::CondCode CC);
508 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
509 const SDLoc &DL);
510 SDValue unfoldMaskedMerge(SDNode *N);
511 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
512 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
513 const SDLoc &DL, bool foldBooleans);
514 SDValue rebuildSetCC(SDValue N);
516 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
517 SDValue &CC) const;
518 bool isOneUseSetCC(SDValue N) const;
520 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
521 unsigned HiOp);
522 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
523 SDValue CombineExtLoad(SDNode *N);
524 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
525 SDValue combineRepeatedFPDivisors(SDNode *N);
526 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
527 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
528 SDValue BuildSDIV(SDNode *N);
529 SDValue BuildSDIVPow2(SDNode *N);
530 SDValue BuildUDIV(SDNode *N);
531 SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
532 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
533 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
534 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
535 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
536 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
537 SDNodeFlags Flags, bool Reciprocal);
538 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
539 SDNodeFlags Flags, bool Reciprocal);
540 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
541 bool DemandHighBits = true);
542 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
543 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
544 SDValue InnerPos, SDValue InnerNeg,
545 unsigned PosOpcode, unsigned NegOpcode,
546 const SDLoc &DL);
547 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
548 SDValue MatchLoadCombine(SDNode *N);
549 SDValue MatchStoreCombine(StoreSDNode *N);
550 SDValue ReduceLoadWidth(SDNode *N);
551 SDValue ReduceLoadOpStoreWidth(SDNode *N);
552 SDValue splitMergedValStore(StoreSDNode *ST);
553 SDValue TransformFPLoadStorePair(SDNode *N);
554 SDValue convertBuildVecZextToZext(SDNode *N);
555 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
556 SDValue reduceBuildVecToShuffle(SDNode *N);
557 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
558 ArrayRef<int> VectorMask, SDValue VecIn1,
559 SDValue VecIn2, unsigned LeftIdx,
560 bool DidSplitVec);
561 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
563 /// Walk up chain skipping non-aliasing memory nodes,
564 /// looking for aliasing nodes and adding them to the Aliases vector.
565 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
566 SmallVectorImpl<SDValue> &Aliases);
568 /// Return true if there is any possibility that the two addresses overlap.
569 bool isAlias(SDNode *Op0, SDNode *Op1) const;
571 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
572 /// chain (aliasing node.)
573 SDValue FindBetterChain(SDNode *N, SDValue Chain);
575 /// Try to replace a store and any possibly adjacent stores on
576 /// consecutive chains with better chains. Return true only if St is
577 /// replaced.
579 /// Notice that other chains may still be replaced even if the function
580 /// returns false.
581 bool findBetterNeighborChains(StoreSDNode *St);
583 // Helper for findBetterNeighborChains. Walk up store chain add additional
584 // chained stores that do not overlap and can be parallelized.
585 bool parallelizeChainedStores(StoreSDNode *St);
587 /// Holds a pointer to an LSBaseSDNode as well as information on where it
588 /// is located in a sequence of memory operations connected by a chain.
589 struct MemOpLink {
590 // Ptr to the mem node.
591 LSBaseSDNode *MemNode;
593 // Offset from the base ptr.
594 int64_t OffsetFromBase;
596 MemOpLink(LSBaseSDNode *N, int64_t Offset)
597 : MemNode(N), OffsetFromBase(Offset) {}
600 /// This is a helper function for visitMUL to check the profitability
601 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
602 /// MulNode is the original multiply, AddNode is (add x, c1),
603 /// and ConstNode is c2.
604 bool isMulAddWithConstProfitable(SDNode *MulNode,
605 SDValue &AddNode,
606 SDValue &ConstNode);
608 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
609 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
610 /// the type of the loaded value to be extended.
611 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
612 EVT LoadResultTy, EVT &ExtVT);
614 /// Helper function to calculate whether the given Load/Store can have its
615 /// width reduced to ExtVT.
616 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
617 EVT &MemVT, unsigned ShAmt = 0);
619 /// Used by BackwardsPropagateMask to find suitable loads.
620 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
621 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
622 ConstantSDNode *Mask, SDNode *&NodeToMask);
623 /// Attempt to propagate a given AND node back to load leaves so that they
624 /// can be combined into narrow loads.
625 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
627 /// Helper function for MergeConsecutiveStores which merges the
628 /// component store chains.
629 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
630 unsigned NumStores);
632 /// This is a helper function for MergeConsecutiveStores. When the
633 /// source elements of the consecutive stores are all constants or
634 /// all extracted vector elements, try to merge them into one
635 /// larger store introducing bitcasts if necessary. \return True
636 /// if a merged store was created.
637 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
638 EVT MemVT, unsigned NumStores,
639 bool IsConstantSrc, bool UseVector,
640 bool UseTrunc);
642 /// This is a helper function for MergeConsecutiveStores. Stores
643 /// that potentially may be merged with St are placed in
644 /// StoreNodes. RootNode is a chain predecessor to all store
645 /// candidates.
646 void getStoreMergeCandidates(StoreSDNode *St,
647 SmallVectorImpl<MemOpLink> &StoreNodes,
648 SDNode *&Root);
650 /// Helper function for MergeConsecutiveStores. Checks if
651 /// candidate stores have indirect dependency through their
652 /// operands. RootNode is the predecessor to all stores calculated
653 /// by getStoreMergeCandidates and is used to prune the dependency check.
654 /// \return True if safe to merge.
655 bool checkMergeStoreCandidatesForDependencies(
656 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
657 SDNode *RootNode);
659 /// Merge consecutive store operations into a wide store.
660 /// This optimization uses wide integers or vectors when possible.
661 /// \return number of stores that were merged into a merged store (the
662 /// affected nodes are stored as a prefix in \p StoreNodes).
663 bool MergeConsecutiveStores(StoreSDNode *St);
665 /// Try to transform a truncation where C is a constant:
666 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
668 /// \p N needs to be a truncation and its first operand an AND. Other
669 /// requirements are checked by the function (e.g. that trunc is
670 /// single-use) and if missed an empty SDValue is returned.
671 SDValue distributeTruncateThroughAnd(SDNode *N);
673 /// Helper function to determine whether the target supports operation
674 /// given by \p Opcode for type \p VT, that is, whether the operation
675 /// is legal or custom before legalizing operations, and whether is
676 /// legal (but not custom) after legalization.
677 bool hasOperation(unsigned Opcode, EVT VT) {
678 if (LegalOperations)
679 return TLI.isOperationLegal(Opcode, VT);
680 return TLI.isOperationLegalOrCustom(Opcode, VT);
683 public:
684 /// Runs the dag combiner on all nodes in the work list
685 void Run(CombineLevel AtLevel);
687 SelectionDAG &getDAG() const { return DAG; }
689 /// Returns a type large enough to hold any valid shift amount - before type
690 /// legalization these can be huge.
691 EVT getShiftAmountTy(EVT LHSTy) {
692 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
693 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
696 /// This method returns true if we are running before type legalization or
697 /// if the specified VT is legal.
698 bool isTypeLegal(const EVT &VT) {
699 if (!LegalTypes) return true;
700 return TLI.isTypeLegal(VT);
703 /// Convenience wrapper around TargetLowering::getSetCCResultType
704 EVT getSetCCResultType(EVT VT) const {
705 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
708 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
709 SDValue OrigLoad, SDValue ExtLoad,
710 ISD::NodeType ExtType);
713 /// This class is a DAGUpdateListener that removes any deleted
714 /// nodes from the worklist.
715 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
716 DAGCombiner &DC;
718 public:
719 explicit WorklistRemover(DAGCombiner &dc)
720 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
722 void NodeDeleted(SDNode *N, SDNode *E) override {
723 DC.removeFromWorklist(N);
727 class WorklistInserter : public SelectionDAG::DAGUpdateListener {
728 DAGCombiner &DC;
730 public:
731 explicit WorklistInserter(DAGCombiner &dc)
732 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
734 // FIXME: Ideally we could add N to the worklist, but this causes exponential
735 // compile time costs in large DAGs, e.g. Halide.
736 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
739 } // end anonymous namespace
741 //===----------------------------------------------------------------------===//
742 // TargetLowering::DAGCombinerInfo implementation
743 //===----------------------------------------------------------------------===//
745 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
746 ((DAGCombiner*)DC)->AddToWorklist(N);
749 SDValue TargetLowering::DAGCombinerInfo::
750 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
751 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
754 SDValue TargetLowering::DAGCombinerInfo::
755 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
756 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
759 SDValue TargetLowering::DAGCombinerInfo::
760 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
761 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
764 void TargetLowering::DAGCombinerInfo::
765 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
766 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
769 //===----------------------------------------------------------------------===//
770 // Helper Functions
771 //===----------------------------------------------------------------------===//
773 void DAGCombiner::deleteAndRecombine(SDNode *N) {
774 removeFromWorklist(N);
776 // If the operands of this node are only used by the node, they will now be
777 // dead. Make sure to re-visit them and recursively delete dead nodes.
778 for (const SDValue &Op : N->ops())
779 // For an operand generating multiple values, one of the values may
780 // become dead allowing further simplification (e.g. split index
781 // arithmetic from an indexed load).
782 if (Op->hasOneUse() || Op->getNumValues() > 1)
783 AddToWorklist(Op.getNode());
785 DAG.DeleteNode(N);
788 /// Return 1 if we can compute the negated form of the specified expression for
789 /// the same cost as the expression itself, or 2 if we can compute the negated
790 /// form more cheaply than the expression itself.
791 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
792 const TargetLowering &TLI,
793 const TargetOptions *Options,
794 bool ForCodeSize,
795 unsigned Depth = 0) {
796 // fneg is removable even if it has multiple uses.
797 if (Op.getOpcode() == ISD::FNEG)
798 return 2;
800 // Don't allow anything with multiple uses unless we know it is free.
801 EVT VT = Op.getValueType();
802 const SDNodeFlags Flags = Op->getFlags();
803 if (!Op.hasOneUse() &&
804 !(Op.getOpcode() == ISD::FP_EXTEND &&
805 TLI.isFPExtFree(VT, Op.getOperand(0).getValueType())))
806 return 0;
808 // Don't recurse exponentially.
809 if (Depth > 6)
810 return 0;
812 switch (Op.getOpcode()) {
813 default: return false;
814 case ISD::ConstantFP: {
815 if (!LegalOperations)
816 return 1;
818 // Don't invert constant FP values after legalization unless the target says
819 // the negated constant is legal.
820 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
821 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
822 ForCodeSize);
824 case ISD::BUILD_VECTOR: {
825 // Only permit BUILD_VECTOR of constants.
826 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
827 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
829 return 0;
830 if (!LegalOperations)
831 return 1;
832 if (TLI.isOperationLegal(ISD::ConstantFP, VT) &&
833 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
834 return 1;
835 return llvm::all_of(Op->op_values(), [&](SDValue N) {
836 return N.isUndef() ||
837 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
838 ForCodeSize);
841 case ISD::FADD:
842 if (!Options->NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
843 return 0;
845 // After operation legalization, it might not be legal to create new FSUBs.
846 if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
847 return 0;
849 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
850 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
851 Options, ForCodeSize, Depth + 1))
852 return V;
853 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
854 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
855 ForCodeSize, Depth + 1);
856 case ISD::FSUB:
857 // We can't turn -(A-B) into B-A when we honor signed zeros.
858 if (!Options->NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
859 return 0;
861 // fold (fneg (fsub A, B)) -> (fsub B, A)
862 return 1;
864 case ISD::FMUL:
865 case ISD::FDIV:
866 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
867 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
868 Options, ForCodeSize, Depth + 1))
869 return V;
871 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
872 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
873 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
874 return 0;
876 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
877 ForCodeSize, Depth + 1);
879 case ISD::FP_EXTEND:
880 case ISD::FP_ROUND:
881 case ISD::FSIN:
882 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
883 ForCodeSize, Depth + 1);
887 /// If isNegatibleForFree returns true, return the newly negated expression.
888 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
889 bool LegalOperations, bool ForCodeSize,
890 unsigned Depth = 0) {
891 // fneg is removable even if it has multiple uses.
892 if (Op.getOpcode() == ISD::FNEG)
893 return Op.getOperand(0);
895 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
896 const TargetOptions &Options = DAG.getTarget().Options;
897 const SDNodeFlags Flags = Op->getFlags();
899 switch (Op.getOpcode()) {
900 default: llvm_unreachable("Unknown code");
901 case ISD::ConstantFP: {
902 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
903 V.changeSign();
904 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
906 case ISD::BUILD_VECTOR: {
907 SmallVector<SDValue, 4> Ops;
908 for (SDValue C : Op->op_values()) {
909 if (C.isUndef()) {
910 Ops.push_back(C);
911 continue;
913 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
914 V.changeSign();
915 Ops.push_back(DAG.getConstantFP(V, SDLoc(Op), C.getValueType()));
917 return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Ops);
919 case ISD::FADD:
920 assert(Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros());
922 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
923 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
924 DAG.getTargetLoweringInfo(), &Options, ForCodeSize,
925 Depth + 1))
926 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
927 GetNegatedExpression(Op.getOperand(0), DAG,
928 LegalOperations, ForCodeSize,
929 Depth + 1),
930 Op.getOperand(1), Flags);
931 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
932 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
933 GetNegatedExpression(Op.getOperand(1), DAG,
934 LegalOperations, ForCodeSize,
935 Depth + 1),
936 Op.getOperand(0), Flags);
937 case ISD::FSUB:
938 // fold (fneg (fsub 0, B)) -> B
939 if (ConstantFPSDNode *N0CFP =
940 isConstOrConstSplatFP(Op.getOperand(0), /*AllowUndefs*/ true))
941 if (N0CFP->isZero())
942 return Op.getOperand(1);
944 // fold (fneg (fsub A, B)) -> (fsub B, A)
945 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
946 Op.getOperand(1), Op.getOperand(0), Flags);
948 case ISD::FMUL:
949 case ISD::FDIV:
950 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
951 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
952 DAG.getTargetLoweringInfo(), &Options, ForCodeSize,
953 Depth + 1))
954 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
955 GetNegatedExpression(Op.getOperand(0), DAG,
956 LegalOperations, ForCodeSize,
957 Depth + 1),
958 Op.getOperand(1), Flags);
960 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
961 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
962 Op.getOperand(0),
963 GetNegatedExpression(Op.getOperand(1), DAG,
964 LegalOperations, ForCodeSize,
965 Depth + 1), Flags);
967 case ISD::FP_EXTEND:
968 case ISD::FSIN:
969 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
970 GetNegatedExpression(Op.getOperand(0), DAG,
971 LegalOperations, ForCodeSize,
972 Depth + 1));
973 case ISD::FP_ROUND:
974 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
975 GetNegatedExpression(Op.getOperand(0), DAG,
976 LegalOperations, ForCodeSize,
977 Depth + 1),
978 Op.getOperand(1));
982 // APInts must be the same size for most operations, this helper
983 // function zero extends the shorter of the pair so that they match.
984 // We provide an Offset so that we can create bitwidths that won't overflow.
985 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
986 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
987 LHS = LHS.zextOrSelf(Bits);
988 RHS = RHS.zextOrSelf(Bits);
991 // Return true if this node is a setcc, or is a select_cc
992 // that selects between the target values used for true and false, making it
993 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
994 // the appropriate nodes based on the type of node we are checking. This
995 // simplifies life a bit for the callers.
996 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
997 SDValue &CC) const {
998 if (N.getOpcode() == ISD::SETCC) {
999 LHS = N.getOperand(0);
1000 RHS = N.getOperand(1);
1001 CC = N.getOperand(2);
1002 return true;
1005 if (N.getOpcode() != ISD::SELECT_CC ||
1006 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
1007 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
1008 return false;
1010 if (TLI.getBooleanContents(N.getValueType()) ==
1011 TargetLowering::UndefinedBooleanContent)
1012 return false;
1014 LHS = N.getOperand(0);
1015 RHS = N.getOperand(1);
1016 CC = N.getOperand(4);
1017 return true;
1020 /// Return true if this is a SetCC-equivalent operation with only one use.
1021 /// If this is true, it allows the users to invert the operation for free when
1022 /// it is profitable to do so.
1023 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
1024 SDValue N0, N1, N2;
1025 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
1026 return true;
1027 return false;
1030 // Returns the SDNode if it is a constant float BuildVector
1031 // or constant float.
1032 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
1033 if (isa<ConstantFPSDNode>(N))
1034 return N.getNode();
1035 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
1036 return N.getNode();
1037 return nullptr;
1040 // Determines if it is a constant integer or a build vector of constant
1041 // integers (and undefs).
1042 // Do not permit build vector implicit truncation.
1043 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
1044 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
1045 return !(Const->isOpaque() && NoOpaques);
1046 if (N.getOpcode() != ISD::BUILD_VECTOR)
1047 return false;
1048 unsigned BitWidth = N.getScalarValueSizeInBits();
1049 for (const SDValue &Op : N->op_values()) {
1050 if (Op.isUndef())
1051 continue;
1052 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
1053 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
1054 (Const->isOpaque() && NoOpaques))
1055 return false;
1057 return true;
1060 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1061 // undef's.
1062 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
1063 if (V.getOpcode() != ISD::BUILD_VECTOR)
1064 return false;
1065 return isConstantOrConstantVector(V, NoOpaques) ||
1066 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
1069 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
1070 const SDLoc &DL,
1071 SDValue N0,
1072 SDValue N1) {
1073 // Currently this only tries to ensure we don't undo the GEP splits done by
1074 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1075 // we check if the following transformation would be problematic:
1076 // (load/store (add, (add, x, offset1), offset2)) ->
1077 // (load/store (add, x, offset1+offset2)).
1079 if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
1080 return false;
1082 if (N0.hasOneUse())
1083 return false;
1085 auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1086 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1087 if (!C1 || !C2)
1088 return false;
1090 const APInt &C1APIntVal = C1->getAPIntValue();
1091 const APInt &C2APIntVal = C2->getAPIntValue();
1092 if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64)
1093 return false;
1095 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1096 if (CombinedValueIntVal.getBitWidth() > 64)
1097 return false;
1098 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1100 for (SDNode *Node : N0->uses()) {
1101 auto LoadStore = dyn_cast<MemSDNode>(Node);
1102 if (LoadStore) {
1103 // Is x[offset2] already not a legal addressing mode? If so then
1104 // reassociating the constants breaks nothing (we test offset2 because
1105 // that's the one we hope to fold into the load or store).
1106 TargetLoweringBase::AddrMode AM;
1107 AM.HasBaseReg = true;
1108 AM.BaseOffs = C2APIntVal.getSExtValue();
1109 EVT VT = LoadStore->getMemoryVT();
1110 unsigned AS = LoadStore->getAddressSpace();
1111 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1112 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1113 continue;
1115 // Would x[offset1+offset2] still be a legal addressing mode?
1116 AM.BaseOffs = CombinedValue;
1117 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1118 return true;
1122 return false;
1125 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
1126 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
1127 SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1128 SDValue N0, SDValue N1) {
1129 EVT VT = N0.getValueType();
1131 if (N0.getOpcode() != Opc)
1132 return SDValue();
1134 // Don't reassociate reductions.
1135 if (N0->getFlags().hasVectorReduction())
1136 return SDValue();
1138 if (SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
1139 if (SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1140 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1141 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, C1, C2))
1142 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
1143 return SDValue();
1145 if (N0.hasOneUse()) {
1146 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1147 // iff (op x, c1) has one use
1148 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
1149 if (!OpNode.getNode())
1150 return SDValue();
1151 AddToWorklist(OpNode.getNode());
1152 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
1155 return SDValue();
1158 // Try to reassociate commutative binops.
1159 SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
1160 SDValue N1, SDNodeFlags Flags) {
1161 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
1162 // Don't reassociate reductions.
1163 if (Flags.hasVectorReduction())
1164 return SDValue();
1166 // Floating-point reassociation is not allowed without loose FP math.
1167 if (N0.getValueType().isFloatingPoint() ||
1168 N1.getValueType().isFloatingPoint())
1169 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1170 return SDValue();
1172 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
1173 return Combined;
1174 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
1175 return Combined;
1176 return SDValue();
1179 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1180 bool AddTo) {
1181 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1182 ++NodesCombined;
1183 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1184 To[0].getNode()->dump(&DAG);
1185 dbgs() << " and " << NumTo - 1 << " other values\n");
1186 for (unsigned i = 0, e = NumTo; i != e; ++i)
1187 assert((!To[i].getNode() ||
1188 N->getValueType(i) == To[i].getValueType()) &&
1189 "Cannot combine value to value of different type!");
1191 WorklistRemover DeadNodes(*this);
1192 DAG.ReplaceAllUsesWith(N, To);
1193 if (AddTo) {
1194 // Push the new nodes and any users onto the worklist
1195 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1196 if (To[i].getNode()) {
1197 AddToWorklist(To[i].getNode());
1198 AddUsersToWorklist(To[i].getNode());
1203 // Finally, if the node is now dead, remove it from the graph. The node
1204 // may not be dead if the replacement process recursively simplified to
1205 // something else needing this node.
1206 if (N->use_empty())
1207 deleteAndRecombine(N);
1208 return SDValue(N, 0);
1211 void DAGCombiner::
1212 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1213 // Replace all uses. If any nodes become isomorphic to other nodes and
1214 // are deleted, make sure to remove them from our worklist.
1215 WorklistRemover DeadNodes(*this);
1216 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1218 // Push the new node and any (possibly new) users onto the worklist.
1219 AddToWorklist(TLO.New.getNode());
1220 AddUsersToWorklist(TLO.New.getNode());
1222 // Finally, if the node is now dead, remove it from the graph. The node
1223 // may not be dead if the replacement process recursively simplified to
1224 // something else needing this node.
1225 if (TLO.Old.getNode()->use_empty())
1226 deleteAndRecombine(TLO.Old.getNode());
1229 /// Check the specified integer node value to see if it can be simplified or if
1230 /// things it uses can be simplified by bit propagation. If so, return true.
1231 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1232 const APInt &DemandedElts) {
1233 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1234 KnownBits Known;
1235 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO))
1236 return false;
1238 // Revisit the node.
1239 AddToWorklist(Op.getNode());
1241 // Replace the old value with the new one.
1242 ++NodesCombined;
1243 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1244 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1245 dbgs() << '\n');
1247 CommitTargetLoweringOpt(TLO);
1248 return true;
1251 /// Check the specified vector node value to see if it can be simplified or
1252 /// if things it uses can be simplified as it only uses some of the elements.
1253 /// If so, return true.
1254 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1255 const APInt &DemandedElts,
1256 bool AssumeSingleUse) {
1257 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1258 APInt KnownUndef, KnownZero;
1259 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1260 TLO, 0, AssumeSingleUse))
1261 return false;
1263 // Revisit the node.
1264 AddToWorklist(Op.getNode());
1266 // Replace the old value with the new one.
1267 ++NodesCombined;
1268 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1269 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1270 dbgs() << '\n');
1272 CommitTargetLoweringOpt(TLO);
1273 return true;
1276 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1277 SDLoc DL(Load);
1278 EVT VT = Load->getValueType(0);
1279 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1281 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1282 Trunc.getNode()->dump(&DAG); dbgs() << '\n');
1283 WorklistRemover DeadNodes(*this);
1284 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1285 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1286 deleteAndRecombine(Load);
1287 AddToWorklist(Trunc.getNode());
1290 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1291 Replace = false;
1292 SDLoc DL(Op);
1293 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1294 LoadSDNode *LD = cast<LoadSDNode>(Op);
1295 EVT MemVT = LD->getMemoryVT();
1296 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1297 : LD->getExtensionType();
1298 Replace = true;
1299 return DAG.getExtLoad(ExtType, DL, PVT,
1300 LD->getChain(), LD->getBasePtr(),
1301 MemVT, LD->getMemOperand());
1304 unsigned Opc = Op.getOpcode();
1305 switch (Opc) {
1306 default: break;
1307 case ISD::AssertSext:
1308 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1309 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1310 break;
1311 case ISD::AssertZext:
1312 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1313 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1314 break;
1315 case ISD::Constant: {
1316 unsigned ExtOpc =
1317 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1318 return DAG.getNode(ExtOpc, DL, PVT, Op);
1322 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1323 return SDValue();
1324 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1327 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1328 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1329 return SDValue();
1330 EVT OldVT = Op.getValueType();
1331 SDLoc DL(Op);
1332 bool Replace = false;
1333 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1334 if (!NewOp.getNode())
1335 return SDValue();
1336 AddToWorklist(NewOp.getNode());
1338 if (Replace)
1339 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1340 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1341 DAG.getValueType(OldVT));
1344 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1345 EVT OldVT = Op.getValueType();
1346 SDLoc DL(Op);
1347 bool Replace = false;
1348 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1349 if (!NewOp.getNode())
1350 return SDValue();
1351 AddToWorklist(NewOp.getNode());
1353 if (Replace)
1354 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1355 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1358 /// Promote the specified integer binary operation if the target indicates it is
1359 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1360 /// i32 since i16 instructions are longer.
1361 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1362 if (!LegalOperations)
1363 return SDValue();
1365 EVT VT = Op.getValueType();
1366 if (VT.isVector() || !VT.isInteger())
1367 return SDValue();
1369 // If operation type is 'undesirable', e.g. i16 on x86, consider
1370 // promoting it.
1371 unsigned Opc = Op.getOpcode();
1372 if (TLI.isTypeDesirableForOp(Opc, VT))
1373 return SDValue();
1375 EVT PVT = VT;
1376 // Consult target whether it is a good idea to promote this operation and
1377 // what's the right type to promote it to.
1378 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1379 assert(PVT != VT && "Don't know what type to promote to!");
1381 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1383 bool Replace0 = false;
1384 SDValue N0 = Op.getOperand(0);
1385 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1387 bool Replace1 = false;
1388 SDValue N1 = Op.getOperand(1);
1389 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1390 SDLoc DL(Op);
1392 SDValue RV =
1393 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1395 // We are always replacing N0/N1's use in N and only need
1396 // additional replacements if there are additional uses.
1397 Replace0 &= !N0->hasOneUse();
1398 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1400 // Combine Op here so it is preserved past replacements.
1401 CombineTo(Op.getNode(), RV);
1403 // If operands have a use ordering, make sure we deal with
1404 // predecessor first.
1405 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1406 std::swap(N0, N1);
1407 std::swap(NN0, NN1);
1410 if (Replace0) {
1411 AddToWorklist(NN0.getNode());
1412 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1414 if (Replace1) {
1415 AddToWorklist(NN1.getNode());
1416 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1418 return Op;
1420 return SDValue();
1423 /// Promote the specified integer shift operation if the target indicates it is
1424 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1425 /// i32 since i16 instructions are longer.
1426 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1427 if (!LegalOperations)
1428 return SDValue();
1430 EVT VT = Op.getValueType();
1431 if (VT.isVector() || !VT.isInteger())
1432 return SDValue();
1434 // If operation type is 'undesirable', e.g. i16 on x86, consider
1435 // promoting it.
1436 unsigned Opc = Op.getOpcode();
1437 if (TLI.isTypeDesirableForOp(Opc, VT))
1438 return SDValue();
1440 EVT PVT = VT;
1441 // Consult target whether it is a good idea to promote this operation and
1442 // what's the right type to promote it to.
1443 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1444 assert(PVT != VT && "Don't know what type to promote to!");
1446 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1448 bool Replace = false;
1449 SDValue N0 = Op.getOperand(0);
1450 SDValue N1 = Op.getOperand(1);
1451 if (Opc == ISD::SRA)
1452 N0 = SExtPromoteOperand(N0, PVT);
1453 else if (Opc == ISD::SRL)
1454 N0 = ZExtPromoteOperand(N0, PVT);
1455 else
1456 N0 = PromoteOperand(N0, PVT, Replace);
1458 if (!N0.getNode())
1459 return SDValue();
1461 SDLoc DL(Op);
1462 SDValue RV =
1463 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1465 AddToWorklist(N0.getNode());
1466 if (Replace)
1467 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1469 // Deal with Op being deleted.
1470 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1471 return RV;
1473 return SDValue();
1476 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1477 if (!LegalOperations)
1478 return SDValue();
1480 EVT VT = Op.getValueType();
1481 if (VT.isVector() || !VT.isInteger())
1482 return SDValue();
1484 // If operation type is 'undesirable', e.g. i16 on x86, consider
1485 // promoting it.
1486 unsigned Opc = Op.getOpcode();
1487 if (TLI.isTypeDesirableForOp(Opc, VT))
1488 return SDValue();
1490 EVT PVT = VT;
1491 // Consult target whether it is a good idea to promote this operation and
1492 // what's the right type to promote it to.
1493 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1494 assert(PVT != VT && "Don't know what type to promote to!");
1495 // fold (aext (aext x)) -> (aext x)
1496 // fold (aext (zext x)) -> (zext x)
1497 // fold (aext (sext x)) -> (sext x)
1498 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1499 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1501 return SDValue();
1504 bool DAGCombiner::PromoteLoad(SDValue Op) {
1505 if (!LegalOperations)
1506 return false;
1508 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1509 return false;
1511 EVT VT = Op.getValueType();
1512 if (VT.isVector() || !VT.isInteger())
1513 return false;
1515 // If operation type is 'undesirable', e.g. i16 on x86, consider
1516 // promoting it.
1517 unsigned Opc = Op.getOpcode();
1518 if (TLI.isTypeDesirableForOp(Opc, VT))
1519 return false;
1521 EVT PVT = VT;
1522 // Consult target whether it is a good idea to promote this operation and
1523 // what's the right type to promote it to.
1524 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1525 assert(PVT != VT && "Don't know what type to promote to!");
1527 SDLoc DL(Op);
1528 SDNode *N = Op.getNode();
1529 LoadSDNode *LD = cast<LoadSDNode>(N);
1530 EVT MemVT = LD->getMemoryVT();
1531 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1532 : LD->getExtensionType();
1533 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1534 LD->getChain(), LD->getBasePtr(),
1535 MemVT, LD->getMemOperand());
1536 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1538 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1539 Result.getNode()->dump(&DAG); dbgs() << '\n');
1540 WorklistRemover DeadNodes(*this);
1541 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1542 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1543 deleteAndRecombine(N);
1544 AddToWorklist(Result.getNode());
1545 return true;
1547 return false;
1550 /// Recursively delete a node which has no uses and any operands for
1551 /// which it is the only use.
1553 /// Note that this both deletes the nodes and removes them from the worklist.
1554 /// It also adds any nodes who have had a user deleted to the worklist as they
1555 /// may now have only one use and subject to other combines.
1556 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1557 if (!N->use_empty())
1558 return false;
1560 SmallSetVector<SDNode *, 16> Nodes;
1561 Nodes.insert(N);
1562 do {
1563 N = Nodes.pop_back_val();
1564 if (!N)
1565 continue;
1567 if (N->use_empty()) {
1568 for (const SDValue &ChildN : N->op_values())
1569 Nodes.insert(ChildN.getNode());
1571 removeFromWorklist(N);
1572 DAG.DeleteNode(N);
1573 } else {
1574 AddToWorklist(N);
1576 } while (!Nodes.empty());
1577 return true;
1580 //===----------------------------------------------------------------------===//
1581 // Main DAG Combiner implementation
1582 //===----------------------------------------------------------------------===//
1584 void DAGCombiner::Run(CombineLevel AtLevel) {
1585 // set the instance variables, so that the various visit routines may use it.
1586 Level = AtLevel;
1587 LegalOperations = Level >= AfterLegalizeVectorOps;
1588 LegalTypes = Level >= AfterLegalizeTypes;
1590 WorklistInserter AddNodes(*this);
1592 // Add all the dag nodes to the worklist.
1593 for (SDNode &Node : DAG.allnodes())
1594 AddToWorklist(&Node);
1596 // Create a dummy node (which is not added to allnodes), that adds a reference
1597 // to the root node, preventing it from being deleted, and tracking any
1598 // changes of the root.
1599 HandleSDNode Dummy(DAG.getRoot());
1601 // While we have a valid worklist entry node, try to combine it.
1602 while (SDNode *N = getNextWorklistEntry()) {
1603 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1604 // N is deleted from the DAG, since they too may now be dead or may have a
1605 // reduced number of uses, allowing other xforms.
1606 if (recursivelyDeleteUnusedNodes(N))
1607 continue;
1609 WorklistRemover DeadNodes(*this);
1611 // If this combine is running after legalizing the DAG, re-legalize any
1612 // nodes pulled off the worklist.
1613 if (Level == AfterLegalizeDAG) {
1614 SmallSetVector<SDNode *, 16> UpdatedNodes;
1615 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1617 for (SDNode *LN : UpdatedNodes) {
1618 AddToWorklist(LN);
1619 AddUsersToWorklist(LN);
1621 if (!NIsValid)
1622 continue;
1625 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1627 // Add any operands of the new node which have not yet been combined to the
1628 // worklist as well. Because the worklist uniques things already, this
1629 // won't repeatedly process the same operand.
1630 CombinedNodes.insert(N);
1631 for (const SDValue &ChildN : N->op_values())
1632 if (!CombinedNodes.count(ChildN.getNode()))
1633 AddToWorklist(ChildN.getNode());
1635 SDValue RV = combine(N);
1637 if (!RV.getNode())
1638 continue;
1640 ++NodesCombined;
1642 // If we get back the same node we passed in, rather than a new node or
1643 // zero, we know that the node must have defined multiple values and
1644 // CombineTo was used. Since CombineTo takes care of the worklist
1645 // mechanics for us, we have no work to do in this case.
1646 if (RV.getNode() == N)
1647 continue;
1649 assert(N->getOpcode() != ISD::DELETED_NODE &&
1650 RV.getOpcode() != ISD::DELETED_NODE &&
1651 "Node was deleted but visit returned new node!");
1653 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
1655 if (N->getNumValues() == RV.getNode()->getNumValues())
1656 DAG.ReplaceAllUsesWith(N, RV.getNode());
1657 else {
1658 assert(N->getValueType(0) == RV.getValueType() &&
1659 N->getNumValues() == 1 && "Type mismatch");
1660 DAG.ReplaceAllUsesWith(N, &RV);
1663 // Push the new node and any users onto the worklist
1664 AddToWorklist(RV.getNode());
1665 AddUsersToWorklist(RV.getNode());
1667 // Finally, if the node is now dead, remove it from the graph. The node
1668 // may not be dead if the replacement process recursively simplified to
1669 // something else needing this node. This will also take care of adding any
1670 // operands which have lost a user to the worklist.
1671 recursivelyDeleteUnusedNodes(N);
1674 // If the root changed (e.g. it was a dead load, update the root).
1675 DAG.setRoot(Dummy.getValue());
1676 DAG.RemoveDeadNodes();
1679 SDValue DAGCombiner::visit(SDNode *N) {
1680 switch (N->getOpcode()) {
1681 default: break;
1682 case ISD::TokenFactor: return visitTokenFactor(N);
1683 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1684 case ISD::ADD: return visitADD(N);
1685 case ISD::SUB: return visitSUB(N);
1686 case ISD::SADDSAT:
1687 case ISD::UADDSAT: return visitADDSAT(N);
1688 case ISD::SSUBSAT:
1689 case ISD::USUBSAT: return visitSUBSAT(N);
1690 case ISD::ADDC: return visitADDC(N);
1691 case ISD::SADDO:
1692 case ISD::UADDO: return visitADDO(N);
1693 case ISD::SUBC: return visitSUBC(N);
1694 case ISD::SSUBO:
1695 case ISD::USUBO: return visitSUBO(N);
1696 case ISD::ADDE: return visitADDE(N);
1697 case ISD::ADDCARRY: return visitADDCARRY(N);
1698 case ISD::SUBE: return visitSUBE(N);
1699 case ISD::SUBCARRY: return visitSUBCARRY(N);
1700 case ISD::SMULFIX:
1701 case ISD::SMULFIXSAT:
1702 case ISD::UMULFIX: return visitMULFIX(N);
1703 case ISD::MUL: return visitMUL(N);
1704 case ISD::SDIV: return visitSDIV(N);
1705 case ISD::UDIV: return visitUDIV(N);
1706 case ISD::SREM:
1707 case ISD::UREM: return visitREM(N);
1708 case ISD::MULHU: return visitMULHU(N);
1709 case ISD::MULHS: return visitMULHS(N);
1710 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1711 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1712 case ISD::SMULO:
1713 case ISD::UMULO: return visitMULO(N);
1714 case ISD::SMIN:
1715 case ISD::SMAX:
1716 case ISD::UMIN:
1717 case ISD::UMAX: return visitIMINMAX(N);
1718 case ISD::AND: return visitAND(N);
1719 case ISD::OR: return visitOR(N);
1720 case ISD::XOR: return visitXOR(N);
1721 case ISD::SHL: return visitSHL(N);
1722 case ISD::SRA: return visitSRA(N);
1723 case ISD::SRL: return visitSRL(N);
1724 case ISD::ROTR:
1725 case ISD::ROTL: return visitRotate(N);
1726 case ISD::FSHL:
1727 case ISD::FSHR: return visitFunnelShift(N);
1728 case ISD::ABS: return visitABS(N);
1729 case ISD::BSWAP: return visitBSWAP(N);
1730 case ISD::BITREVERSE: return visitBITREVERSE(N);
1731 case ISD::CTLZ: return visitCTLZ(N);
1732 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1733 case ISD::CTTZ: return visitCTTZ(N);
1734 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1735 case ISD::CTPOP: return visitCTPOP(N);
1736 case ISD::SELECT: return visitSELECT(N);
1737 case ISD::VSELECT: return visitVSELECT(N);
1738 case ISD::SELECT_CC: return visitSELECT_CC(N);
1739 case ISD::SETCC: return visitSETCC(N);
1740 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1741 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1742 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1743 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1744 case ISD::AssertSext:
1745 case ISD::AssertZext: return visitAssertExt(N);
1746 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1747 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1748 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1749 case ISD::TRUNCATE: return visitTRUNCATE(N);
1750 case ISD::BITCAST: return visitBITCAST(N);
1751 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1752 case ISD::FADD: return visitFADD(N);
1753 case ISD::FSUB: return visitFSUB(N);
1754 case ISD::FMUL: return visitFMUL(N);
1755 case ISD::FMA: return visitFMA(N);
1756 case ISD::FDIV: return visitFDIV(N);
1757 case ISD::FREM: return visitFREM(N);
1758 case ISD::FSQRT: return visitFSQRT(N);
1759 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1760 case ISD::FPOW: return visitFPOW(N);
1761 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1762 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1763 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1764 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1765 case ISD::FP_ROUND: return visitFP_ROUND(N);
1766 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1767 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1768 case ISD::FNEG: return visitFNEG(N);
1769 case ISD::FABS: return visitFABS(N);
1770 case ISD::FFLOOR: return visitFFLOOR(N);
1771 case ISD::FMINNUM: return visitFMINNUM(N);
1772 case ISD::FMAXNUM: return visitFMAXNUM(N);
1773 case ISD::FMINIMUM: return visitFMINIMUM(N);
1774 case ISD::FMAXIMUM: return visitFMAXIMUM(N);
1775 case ISD::FCEIL: return visitFCEIL(N);
1776 case ISD::FTRUNC: return visitFTRUNC(N);
1777 case ISD::BRCOND: return visitBRCOND(N);
1778 case ISD::BR_CC: return visitBR_CC(N);
1779 case ISD::LOAD: return visitLOAD(N);
1780 case ISD::STORE: return visitSTORE(N);
1781 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1782 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1783 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1784 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1785 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1786 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1787 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1788 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1789 case ISD::MGATHER: return visitMGATHER(N);
1790 case ISD::MLOAD: return visitMLOAD(N);
1791 case ISD::MSCATTER: return visitMSCATTER(N);
1792 case ISD::MSTORE: return visitMSTORE(N);
1793 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
1794 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1795 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1796 case ISD::VECREDUCE_FADD:
1797 case ISD::VECREDUCE_FMUL:
1798 case ISD::VECREDUCE_ADD:
1799 case ISD::VECREDUCE_MUL:
1800 case ISD::VECREDUCE_AND:
1801 case ISD::VECREDUCE_OR:
1802 case ISD::VECREDUCE_XOR:
1803 case ISD::VECREDUCE_SMAX:
1804 case ISD::VECREDUCE_SMIN:
1805 case ISD::VECREDUCE_UMAX:
1806 case ISD::VECREDUCE_UMIN:
1807 case ISD::VECREDUCE_FMAX:
1808 case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N);
1810 return SDValue();
1813 SDValue DAGCombiner::combine(SDNode *N) {
1814 SDValue RV = visit(N);
1816 // If nothing happened, try a target-specific DAG combine.
1817 if (!RV.getNode()) {
1818 assert(N->getOpcode() != ISD::DELETED_NODE &&
1819 "Node was deleted but visit returned NULL!");
1821 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1822 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1824 // Expose the DAG combiner to the target combiner impls.
1825 TargetLowering::DAGCombinerInfo
1826 DagCombineInfo(DAG, Level, false, this);
1828 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1832 // If nothing happened still, try promoting the operation.
1833 if (!RV.getNode()) {
1834 switch (N->getOpcode()) {
1835 default: break;
1836 case ISD::ADD:
1837 case ISD::SUB:
1838 case ISD::MUL:
1839 case ISD::AND:
1840 case ISD::OR:
1841 case ISD::XOR:
1842 RV = PromoteIntBinOp(SDValue(N, 0));
1843 break;
1844 case ISD::SHL:
1845 case ISD::SRA:
1846 case ISD::SRL:
1847 RV = PromoteIntShiftOp(SDValue(N, 0));
1848 break;
1849 case ISD::SIGN_EXTEND:
1850 case ISD::ZERO_EXTEND:
1851 case ISD::ANY_EXTEND:
1852 RV = PromoteExtend(SDValue(N, 0));
1853 break;
1854 case ISD::LOAD:
1855 if (PromoteLoad(SDValue(N, 0)))
1856 RV = SDValue(N, 0);
1857 break;
1861 // If N is a commutative binary node, try to eliminate it if the commuted
1862 // version is already present in the DAG.
1863 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1864 N->getNumValues() == 1) {
1865 SDValue N0 = N->getOperand(0);
1866 SDValue N1 = N->getOperand(1);
1868 // Constant operands are canonicalized to RHS.
1869 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1870 SDValue Ops[] = {N1, N0};
1871 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1872 N->getFlags());
1873 if (CSENode)
1874 return SDValue(CSENode, 0);
1878 return RV;
1881 /// Given a node, return its input chain if it has one, otherwise return a null
1882 /// sd operand.
1883 static SDValue getInputChainForNode(SDNode *N) {
1884 if (unsigned NumOps = N->getNumOperands()) {
1885 if (N->getOperand(0).getValueType() == MVT::Other)
1886 return N->getOperand(0);
1887 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1888 return N->getOperand(NumOps-1);
1889 for (unsigned i = 1; i < NumOps-1; ++i)
1890 if (N->getOperand(i).getValueType() == MVT::Other)
1891 return N->getOperand(i);
1893 return SDValue();
1896 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1897 // If N has two operands, where one has an input chain equal to the other,
1898 // the 'other' chain is redundant.
1899 if (N->getNumOperands() == 2) {
1900 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1901 return N->getOperand(0);
1902 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1903 return N->getOperand(1);
1906 // Don't simplify token factors if optnone.
1907 if (OptLevel == CodeGenOpt::None)
1908 return SDValue();
1910 // If the sole user is a token factor, we should make sure we have a
1911 // chance to merge them together. This prevents TF chains from inhibiting
1912 // optimizations.
1913 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
1914 AddToWorklist(*(N->use_begin()));
1916 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1917 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1918 SmallPtrSet<SDNode*, 16> SeenOps;
1919 bool Changed = false; // If we should replace this token factor.
1921 // Start out with this token factor.
1922 TFs.push_back(N);
1924 // Iterate through token factors. The TFs grows when new token factors are
1925 // encountered.
1926 for (unsigned i = 0; i < TFs.size(); ++i) {
1927 // Limit number of nodes to inline, to avoid quadratic compile times.
1928 // We have to add the outstanding Token Factors to Ops, otherwise we might
1929 // drop Ops from the resulting Token Factors.
1930 if (Ops.size() > TokenFactorInlineLimit) {
1931 for (unsigned j = i; j < TFs.size(); j++)
1932 Ops.emplace_back(TFs[j], 0);
1933 // Drop unprocessed Token Factors from TFs, so we do not add them to the
1934 // combiner worklist later.
1935 TFs.resize(i);
1936 break;
1939 SDNode *TF = TFs[i];
1940 // Check each of the operands.
1941 for (const SDValue &Op : TF->op_values()) {
1942 switch (Op.getOpcode()) {
1943 case ISD::EntryToken:
1944 // Entry tokens don't need to be added to the list. They are
1945 // redundant.
1946 Changed = true;
1947 break;
1949 case ISD::TokenFactor:
1950 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1951 // Queue up for processing.
1952 TFs.push_back(Op.getNode());
1953 Changed = true;
1954 break;
1956 LLVM_FALLTHROUGH;
1958 default:
1959 // Only add if it isn't already in the list.
1960 if (SeenOps.insert(Op.getNode()).second)
1961 Ops.push_back(Op);
1962 else
1963 Changed = true;
1964 break;
1969 // Re-visit inlined Token Factors, to clean them up in case they have been
1970 // removed. Skip the first Token Factor, as this is the current node.
1971 for (unsigned i = 1, e = TFs.size(); i < e; i++)
1972 AddToWorklist(TFs[i]);
1974 // Remove Nodes that are chained to another node in the list. Do so
1975 // by walking up chains breath-first stopping when we've seen
1976 // another operand. In general we must climb to the EntryNode, but we can exit
1977 // early if we find all remaining work is associated with just one operand as
1978 // no further pruning is possible.
1980 // List of nodes to search through and original Ops from which they originate.
1981 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1982 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1983 SmallPtrSet<SDNode *, 16> SeenChains;
1984 bool DidPruneOps = false;
1986 unsigned NumLeftToConsider = 0;
1987 for (const SDValue &Op : Ops) {
1988 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1989 OpWorkCount.push_back(1);
1992 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1993 // If this is an Op, we can remove the op from the list. Remark any
1994 // search associated with it as from the current OpNumber.
1995 if (SeenOps.count(Op) != 0) {
1996 Changed = true;
1997 DidPruneOps = true;
1998 unsigned OrigOpNumber = 0;
1999 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
2000 OrigOpNumber++;
2001 assert((OrigOpNumber != Ops.size()) &&
2002 "expected to find TokenFactor Operand");
2003 // Re-mark worklist from OrigOpNumber to OpNumber
2004 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
2005 if (Worklist[i].second == OrigOpNumber) {
2006 Worklist[i].second = OpNumber;
2009 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
2010 OpWorkCount[OrigOpNumber] = 0;
2011 NumLeftToConsider--;
2013 // Add if it's a new chain
2014 if (SeenChains.insert(Op).second) {
2015 OpWorkCount[OpNumber]++;
2016 Worklist.push_back(std::make_pair(Op, OpNumber));
2020 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
2021 // We need at least be consider at least 2 Ops to prune.
2022 if (NumLeftToConsider <= 1)
2023 break;
2024 auto CurNode = Worklist[i].first;
2025 auto CurOpNumber = Worklist[i].second;
2026 assert((OpWorkCount[CurOpNumber] > 0) &&
2027 "Node should not appear in worklist");
2028 switch (CurNode->getOpcode()) {
2029 case ISD::EntryToken:
2030 // Hitting EntryToken is the only way for the search to terminate without
2031 // hitting
2032 // another operand's search. Prevent us from marking this operand
2033 // considered.
2034 NumLeftToConsider++;
2035 break;
2036 case ISD::TokenFactor:
2037 for (const SDValue &Op : CurNode->op_values())
2038 AddToWorklist(i, Op.getNode(), CurOpNumber);
2039 break;
2040 case ISD::LIFETIME_START:
2041 case ISD::LIFETIME_END:
2042 case ISD::CopyFromReg:
2043 case ISD::CopyToReg:
2044 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
2045 break;
2046 default:
2047 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
2048 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
2049 break;
2051 OpWorkCount[CurOpNumber]--;
2052 if (OpWorkCount[CurOpNumber] == 0)
2053 NumLeftToConsider--;
2056 // If we've changed things around then replace token factor.
2057 if (Changed) {
2058 SDValue Result;
2059 if (Ops.empty()) {
2060 // The entry token is the only possible outcome.
2061 Result = DAG.getEntryNode();
2062 } else {
2063 if (DidPruneOps) {
2064 SmallVector<SDValue, 8> PrunedOps;
2066 for (const SDValue &Op : Ops) {
2067 if (SeenChains.count(Op.getNode()) == 0)
2068 PrunedOps.push_back(Op);
2070 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2071 } else {
2072 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2075 return Result;
2077 return SDValue();
2080 /// MERGE_VALUES can always be eliminated.
2081 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2082 WorklistRemover DeadNodes(*this);
2083 // Replacing results may cause a different MERGE_VALUES to suddenly
2084 // be CSE'd with N, and carry its uses with it. Iterate until no
2085 // uses remain, to ensure that the node can be safely deleted.
2086 // First add the users of this node to the work list so that they
2087 // can be tried again once they have new operands.
2088 AddUsersToWorklist(N);
2089 do {
2090 // Do as a single replacement to avoid rewalking use lists.
2091 SmallVector<SDValue, 8> Ops;
2092 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2093 Ops.push_back(N->getOperand(i));
2094 DAG.ReplaceAllUsesWith(N, Ops.data());
2095 } while (!N->use_empty());
2096 deleteAndRecombine(N);
2097 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2100 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2101 /// ConstantSDNode pointer else nullptr.
2102 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
2103 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
2104 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2107 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2108 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
2109 "Unexpected binary operator");
2111 // Don't do this unless the old select is going away. We want to eliminate the
2112 // binary operator, not replace a binop with a select.
2113 // TODO: Handle ISD::SELECT_CC.
2114 unsigned SelOpNo = 0;
2115 SDValue Sel = BO->getOperand(0);
2116 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2117 SelOpNo = 1;
2118 Sel = BO->getOperand(1);
2121 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2122 return SDValue();
2124 SDValue CT = Sel.getOperand(1);
2125 if (!isConstantOrConstantVector(CT, true) &&
2126 !isConstantFPBuildVectorOrConstantFP(CT))
2127 return SDValue();
2129 SDValue CF = Sel.getOperand(2);
2130 if (!isConstantOrConstantVector(CF, true) &&
2131 !isConstantFPBuildVectorOrConstantFP(CF))
2132 return SDValue();
2134 // Bail out if any constants are opaque because we can't constant fold those.
2135 // The exception is "and" and "or" with either 0 or -1 in which case we can
2136 // propagate non constant operands into select. I.e.:
2137 // and (select Cond, 0, -1), X --> select Cond, 0, X
2138 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2139 auto BinOpcode = BO->getOpcode();
2140 bool CanFoldNonConst =
2141 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2142 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) &&
2143 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF));
2145 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2146 if (!CanFoldNonConst &&
2147 !isConstantOrConstantVector(CBO, true) &&
2148 !isConstantFPBuildVectorOrConstantFP(CBO))
2149 return SDValue();
2151 EVT VT = Sel.getValueType();
2153 // In case of shift value and shift amount may have different VT. For instance
2154 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
2155 // swapped operands and value types do not match. NB: x86 is fine if operands
2156 // are not swapped with shift amount VT being not bigger than shifted value.
2157 // TODO: that is possible to check for a shift operation, correct VTs and
2158 // still perform optimization on x86 if needed.
2159 if (SelOpNo && VT != CBO.getValueType())
2160 return SDValue();
2162 // We have a select-of-constants followed by a binary operator with a
2163 // constant. Eliminate the binop by pulling the constant math into the select.
2164 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2165 SDLoc DL(Sel);
2166 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
2167 : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
2168 if (!CanFoldNonConst && !NewCT.isUndef() &&
2169 !isConstantOrConstantVector(NewCT, true) &&
2170 !isConstantFPBuildVectorOrConstantFP(NewCT))
2171 return SDValue();
2173 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
2174 : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
2175 if (!CanFoldNonConst && !NewCF.isUndef() &&
2176 !isConstantOrConstantVector(NewCF, true) &&
2177 !isConstantFPBuildVectorOrConstantFP(NewCF))
2178 return SDValue();
2180 SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
2181 SelectOp->setFlags(BO->getFlags());
2182 return SelectOp;
2185 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
2186 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2187 "Expecting add or sub");
2189 // Match a constant operand and a zext operand for the math instruction:
2190 // add Z, C
2191 // sub C, Z
2192 bool IsAdd = N->getOpcode() == ISD::ADD;
2193 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2194 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2195 auto *CN = dyn_cast<ConstantSDNode>(C);
2196 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2197 return SDValue();
2199 // Match the zext operand as a setcc of a boolean.
2200 if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
2201 Z.getOperand(0).getValueType() != MVT::i1)
2202 return SDValue();
2204 // Match the compare as: setcc (X & 1), 0, eq.
2205 SDValue SetCC = Z.getOperand(0);
2206 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
2207 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
2208 SetCC.getOperand(0).getOpcode() != ISD::AND ||
2209 !isOneConstant(SetCC.getOperand(0).getOperand(1)))
2210 return SDValue();
2212 // We are adding/subtracting a constant and an inverted low bit. Turn that
2213 // into a subtract/add of the low bit with incremented/decremented constant:
2214 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2215 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2216 EVT VT = C.getValueType();
2217 SDLoc DL(N);
2218 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
2219 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
2220 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2221 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2224 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2225 /// a shift and add with a different constant.
2226 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
2227 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2228 "Expecting add or sub");
2230 // We need a constant operand for the add/sub, and the other operand is a
2231 // logical shift right: add (srl), C or sub C, (srl).
2232 // TODO - support non-uniform vector amounts.
2233 bool IsAdd = N->getOpcode() == ISD::ADD;
2234 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2235 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2236 ConstantSDNode *C = isConstOrConstSplat(ConstantOp);
2237 if (!C || ShiftOp.getOpcode() != ISD::SRL)
2238 return SDValue();
2240 // The shift must be of a 'not' value.
2241 SDValue Not = ShiftOp.getOperand(0);
2242 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2243 return SDValue();
2245 // The shift must be moving the sign bit to the least-significant-bit.
2246 EVT VT = ShiftOp.getValueType();
2247 SDValue ShAmt = ShiftOp.getOperand(1);
2248 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2249 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2250 return SDValue();
2252 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2253 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2254 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2255 SDLoc DL(N);
2256 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
2257 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
2258 APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1;
2259 return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT));
2262 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2263 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2264 /// are no common bits set in the operands).
2265 SDValue DAGCombiner::visitADDLike(SDNode *N) {
2266 SDValue N0 = N->getOperand(0);
2267 SDValue N1 = N->getOperand(1);
2268 EVT VT = N0.getValueType();
2269 SDLoc DL(N);
2271 // fold vector ops
2272 if (VT.isVector()) {
2273 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2274 return FoldedVOp;
2276 // fold (add x, 0) -> x, vector edition
2277 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2278 return N0;
2279 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2280 return N1;
2283 // fold (add x, undef) -> undef
2284 if (N0.isUndef())
2285 return N0;
2287 if (N1.isUndef())
2288 return N1;
2290 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2291 // canonicalize constant to RHS
2292 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2293 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2294 // fold (add c1, c2) -> c1+c2
2295 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
2296 N1.getNode());
2299 // fold (add x, 0) -> x
2300 if (isNullConstant(N1))
2301 return N0;
2303 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2304 // fold ((A-c1)+c2) -> (A+(c2-c1))
2305 if (N0.getOpcode() == ISD::SUB &&
2306 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
2307 SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N1.getNode(),
2308 N0.getOperand(1).getNode());
2309 assert(Sub && "Constant folding failed");
2310 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2313 // fold ((c1-A)+c2) -> (c1+c2)-A
2314 if (N0.getOpcode() == ISD::SUB &&
2315 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2316 SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N1.getNode(),
2317 N0.getOperand(0).getNode());
2318 assert(Add && "Constant folding failed");
2319 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2322 // add (sext i1 X), 1 -> zext (not i1 X)
2323 // We don't transform this pattern:
2324 // add (zext i1 X), -1 -> sext (not i1 X)
2325 // because most (?) targets generate better code for the zext form.
2326 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2327 isOneOrOneSplat(N1)) {
2328 SDValue X = N0.getOperand(0);
2329 if ((!LegalOperations ||
2330 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2331 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2332 X.getScalarValueSizeInBits() == 1) {
2333 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2334 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2338 // Undo the add -> or combine to merge constant offsets from a frame index.
2339 if (N0.getOpcode() == ISD::OR &&
2340 isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2341 isa<ConstantSDNode>(N0.getOperand(1)) &&
2342 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2343 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2344 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2348 if (SDValue NewSel = foldBinOpIntoSelect(N))
2349 return NewSel;
2351 // reassociate add
2352 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) {
2353 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2354 return RADD;
2356 // fold ((0-A) + B) -> B-A
2357 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
2358 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2360 // fold (A + (0-B)) -> A-B
2361 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2362 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2364 // fold (A+(B-A)) -> B
2365 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2366 return N1.getOperand(0);
2368 // fold ((B-A)+A) -> B
2369 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2370 return N0.getOperand(0);
2372 // fold ((A-B)+(C-A)) -> (C-B)
2373 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2374 N0.getOperand(0) == N1.getOperand(1))
2375 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2376 N0.getOperand(1));
2378 // fold ((A-B)+(B-C)) -> (A-C)
2379 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2380 N0.getOperand(1) == N1.getOperand(0))
2381 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2382 N1.getOperand(1));
2384 // fold (A+(B-(A+C))) to (B-C)
2385 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2386 N0 == N1.getOperand(1).getOperand(0))
2387 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2388 N1.getOperand(1).getOperand(1));
2390 // fold (A+(B-(C+A))) to (B-C)
2391 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2392 N0 == N1.getOperand(1).getOperand(1))
2393 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2394 N1.getOperand(1).getOperand(0));
2396 // fold (A+((B-A)+or-C)) to (B+or-C)
2397 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2398 N1.getOperand(0).getOpcode() == ISD::SUB &&
2399 N0 == N1.getOperand(0).getOperand(1))
2400 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2401 N1.getOperand(1));
2403 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2404 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2405 SDValue N00 = N0.getOperand(0);
2406 SDValue N01 = N0.getOperand(1);
2407 SDValue N10 = N1.getOperand(0);
2408 SDValue N11 = N1.getOperand(1);
2410 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2411 return DAG.getNode(ISD::SUB, DL, VT,
2412 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2413 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2416 // fold (add (umax X, C), -C) --> (usubsat X, C)
2417 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
2418 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
2419 return (!Max && !Op) ||
2420 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
2422 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
2423 /*AllowUndefs*/ true))
2424 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
2425 N0.getOperand(1));
2428 if (SimplifyDemandedBits(SDValue(N, 0)))
2429 return SDValue(N, 0);
2431 if (isOneOrOneSplat(N1)) {
2432 // fold (add (xor a, -1), 1) -> (sub 0, a)
2433 if (isBitwiseNot(N0))
2434 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2435 N0.getOperand(0));
2437 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2438 if (N0.getOpcode() == ISD::ADD ||
2439 N0.getOpcode() == ISD::UADDO ||
2440 N0.getOpcode() == ISD::SADDO) {
2441 SDValue A, Xor;
2443 if (isBitwiseNot(N0.getOperand(0))) {
2444 A = N0.getOperand(1);
2445 Xor = N0.getOperand(0);
2446 } else if (isBitwiseNot(N0.getOperand(1))) {
2447 A = N0.getOperand(0);
2448 Xor = N0.getOperand(1);
2451 if (Xor)
2452 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
2455 // Look for:
2456 // add (add x, y), 1
2457 // And if the target does not like this form then turn into:
2458 // sub y, (xor x, -1)
2459 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2460 N0.getOpcode() == ISD::ADD) {
2461 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2462 DAG.getAllOnesConstant(DL, VT));
2463 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
2467 // (x - y) + -1 -> add (xor y, -1), x
2468 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2469 isAllOnesOrAllOnesSplat(N1)) {
2470 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
2471 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
2474 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
2475 return Combined;
2477 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
2478 return Combined;
2480 return SDValue();
2483 SDValue DAGCombiner::visitADD(SDNode *N) {
2484 SDValue N0 = N->getOperand(0);
2485 SDValue N1 = N->getOperand(1);
2486 EVT VT = N0.getValueType();
2487 SDLoc DL(N);
2489 if (SDValue Combined = visitADDLike(N))
2490 return Combined;
2492 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2493 return V;
2495 if (SDValue V = foldAddSubOfSignBit(N, DAG))
2496 return V;
2498 // fold (a+b) -> (a|b) iff a and b share no bits.
2499 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2500 DAG.haveNoCommonBitsSet(N0, N1))
2501 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2503 return SDValue();
2506 SDValue DAGCombiner::visitADDSAT(SDNode *N) {
2507 unsigned Opcode = N->getOpcode();
2508 SDValue N0 = N->getOperand(0);
2509 SDValue N1 = N->getOperand(1);
2510 EVT VT = N0.getValueType();
2511 SDLoc DL(N);
2513 // fold vector ops
2514 if (VT.isVector()) {
2515 // TODO SimplifyVBinOp
2517 // fold (add_sat x, 0) -> x, vector edition
2518 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2519 return N0;
2520 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2521 return N1;
2524 // fold (add_sat x, undef) -> -1
2525 if (N0.isUndef() || N1.isUndef())
2526 return DAG.getAllOnesConstant(DL, VT);
2528 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2529 // canonicalize constant to RHS
2530 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2531 return DAG.getNode(Opcode, DL, VT, N1, N0);
2532 // fold (add_sat c1, c2) -> c3
2533 return DAG.FoldConstantArithmetic(Opcode, DL, VT, N0.getNode(),
2534 N1.getNode());
2537 // fold (add_sat x, 0) -> x
2538 if (isNullConstant(N1))
2539 return N0;
2541 // If it cannot overflow, transform into an add.
2542 if (Opcode == ISD::UADDSAT)
2543 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2544 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
2546 return SDValue();
2549 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2550 bool Masked = false;
2552 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2553 while (true) {
2554 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2555 V = V.getOperand(0);
2556 continue;
2559 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2560 Masked = true;
2561 V = V.getOperand(0);
2562 continue;
2565 break;
2568 // If this is not a carry, return.
2569 if (V.getResNo() != 1)
2570 return SDValue();
2572 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2573 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2574 return SDValue();
2576 EVT VT = V.getNode()->getValueType(0);
2577 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
2578 return SDValue();
2580 // If the result is masked, then no matter what kind of bool it is we can
2581 // return. If it isn't, then we need to make sure the bool type is either 0 or
2582 // 1 and not other values.
2583 if (Masked ||
2584 TLI.getBooleanContents(V.getValueType()) ==
2585 TargetLoweringBase::ZeroOrOneBooleanContent)
2586 return V;
2588 return SDValue();
2591 /// Given the operands of an add/sub operation, see if the 2nd operand is a
2592 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2593 /// the opcode and bypass the mask operation.
2594 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
2595 SelectionDAG &DAG, const SDLoc &DL) {
2596 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
2597 return SDValue();
2599 EVT VT = N0.getValueType();
2600 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
2601 return SDValue();
2603 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2604 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2605 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
2608 /// Helper for doing combines based on N0 and N1 being added to each other.
2609 SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
2610 SDNode *LocReference) {
2611 EVT VT = N0.getValueType();
2612 SDLoc DL(LocReference);
2614 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2615 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2616 isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
2617 return DAG.getNode(ISD::SUB, DL, VT, N0,
2618 DAG.getNode(ISD::SHL, DL, VT,
2619 N1.getOperand(0).getOperand(1),
2620 N1.getOperand(1)));
2622 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
2623 return V;
2625 // Look for:
2626 // add (add x, 1), y
2627 // And if the target does not like this form then turn into:
2628 // sub y, (xor x, -1)
2629 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2630 N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) {
2631 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2632 DAG.getAllOnesConstant(DL, VT));
2633 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
2636 // Hoist one-use subtraction by non-opaque constant:
2637 // (x - C) + y -> (x + y) - C
2638 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2639 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2640 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
2641 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
2642 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2644 // Hoist one-use subtraction from non-opaque constant:
2645 // (C - x) + y -> (y - x) + C
2646 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2647 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
2648 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2649 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
2652 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2653 // rather than 'add 0/-1' (the zext should get folded).
2654 // add (sext i1 Y), X --> sub X, (zext i1 Y)
2655 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2656 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
2657 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
2658 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2659 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2662 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2663 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2664 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2665 if (TN->getVT() == MVT::i1) {
2666 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2667 DAG.getConstant(1, DL, VT));
2668 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2672 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2673 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2674 N1.getResNo() == 0)
2675 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2676 N0, N1.getOperand(0), N1.getOperand(2));
2678 // (add X, Carry) -> (addcarry X, 0, Carry)
2679 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2680 if (SDValue Carry = getAsCarry(TLI, N1))
2681 return DAG.getNode(ISD::ADDCARRY, DL,
2682 DAG.getVTList(VT, Carry.getValueType()), N0,
2683 DAG.getConstant(0, DL, VT), Carry);
2685 return SDValue();
2688 SDValue DAGCombiner::visitADDC(SDNode *N) {
2689 SDValue N0 = N->getOperand(0);
2690 SDValue N1 = N->getOperand(1);
2691 EVT VT = N0.getValueType();
2692 SDLoc DL(N);
2694 // If the flag result is dead, turn this into an ADD.
2695 if (!N->hasAnyUseOfValue(1))
2696 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2697 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2699 // canonicalize constant to RHS.
2700 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2701 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2702 if (N0C && !N1C)
2703 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2705 // fold (addc x, 0) -> x + no carry out
2706 if (isNullConstant(N1))
2707 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2708 DL, MVT::Glue));
2710 // If it cannot overflow, transform into an add.
2711 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2712 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2713 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2715 return SDValue();
2718 static SDValue flipBoolean(SDValue V, const SDLoc &DL,
2719 SelectionDAG &DAG, const TargetLowering &TLI) {
2720 EVT VT = V.getValueType();
2722 SDValue Cst;
2723 switch (TLI.getBooleanContents(VT)) {
2724 case TargetLowering::ZeroOrOneBooleanContent:
2725 case TargetLowering::UndefinedBooleanContent:
2726 Cst = DAG.getConstant(1, DL, VT);
2727 break;
2728 case TargetLowering::ZeroOrNegativeOneBooleanContent:
2729 Cst = DAG.getAllOnesConstant(DL, VT);
2730 break;
2733 return DAG.getNode(ISD::XOR, DL, VT, V, Cst);
2737 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2738 * then the flip also occurs if computing the inverse is the same cost.
2739 * This function returns an empty SDValue in case it cannot flip the boolean
2740 * without increasing the cost of the computation. If you want to flip a boolean
2741 * no matter what, use flipBoolean.
2743 static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
2744 const TargetLowering &TLI,
2745 bool Force) {
2746 if (Force && isa<ConstantSDNode>(V))
2747 return flipBoolean(V, SDLoc(V), DAG, TLI);
2749 if (V.getOpcode() != ISD::XOR)
2750 return SDValue();
2752 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
2753 if (!Const)
2754 return SDValue();
2756 EVT VT = V.getValueType();
2758 bool IsFlip = false;
2759 switch(TLI.getBooleanContents(VT)) {
2760 case TargetLowering::ZeroOrOneBooleanContent:
2761 IsFlip = Const->isOne();
2762 break;
2763 case TargetLowering::ZeroOrNegativeOneBooleanContent:
2764 IsFlip = Const->isAllOnesValue();
2765 break;
2766 case TargetLowering::UndefinedBooleanContent:
2767 IsFlip = (Const->getAPIntValue() & 0x01) == 1;
2768 break;
2771 if (IsFlip)
2772 return V.getOperand(0);
2773 if (Force)
2774 return flipBoolean(V, SDLoc(V), DAG, TLI);
2775 return SDValue();
2778 SDValue DAGCombiner::visitADDO(SDNode *N) {
2779 SDValue N0 = N->getOperand(0);
2780 SDValue N1 = N->getOperand(1);
2781 EVT VT = N0.getValueType();
2782 bool IsSigned = (ISD::SADDO == N->getOpcode());
2784 EVT CarryVT = N->getValueType(1);
2785 SDLoc DL(N);
2787 // If the flag result is dead, turn this into an ADD.
2788 if (!N->hasAnyUseOfValue(1))
2789 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2790 DAG.getUNDEF(CarryVT));
2792 // canonicalize constant to RHS.
2793 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2794 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2795 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
2797 // fold (addo x, 0) -> x + no carry out
2798 if (isNullOrNullSplat(N1))
2799 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2801 if (!IsSigned) {
2802 // If it cannot overflow, transform into an add.
2803 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2804 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2805 DAG.getConstant(0, DL, CarryVT));
2807 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2808 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
2809 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2810 DAG.getConstant(0, DL, VT), N0.getOperand(0));
2811 return CombineTo(N, Sub,
2812 flipBoolean(Sub.getValue(1), DL, DAG, TLI));
2815 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2816 return Combined;
2818 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2819 return Combined;
2822 return SDValue();
2825 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2826 EVT VT = N0.getValueType();
2827 if (VT.isVector())
2828 return SDValue();
2830 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2831 // If Y + 1 cannot overflow.
2832 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2833 SDValue Y = N1.getOperand(0);
2834 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2835 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2836 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2837 N1.getOperand(2));
2840 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2841 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2842 if (SDValue Carry = getAsCarry(TLI, N1))
2843 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2844 DAG.getConstant(0, SDLoc(N), VT), Carry);
2846 return SDValue();
2849 SDValue DAGCombiner::visitADDE(SDNode *N) {
2850 SDValue N0 = N->getOperand(0);
2851 SDValue N1 = N->getOperand(1);
2852 SDValue CarryIn = N->getOperand(2);
2854 // canonicalize constant to RHS
2855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2857 if (N0C && !N1C)
2858 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2859 N1, N0, CarryIn);
2861 // fold (adde x, y, false) -> (addc x, y)
2862 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2863 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2865 return SDValue();
2868 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2869 SDValue N0 = N->getOperand(0);
2870 SDValue N1 = N->getOperand(1);
2871 SDValue CarryIn = N->getOperand(2);
2872 SDLoc DL(N);
2874 // canonicalize constant to RHS
2875 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2876 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2877 if (N0C && !N1C)
2878 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2880 // fold (addcarry x, y, false) -> (uaddo x, y)
2881 if (isNullConstant(CarryIn)) {
2882 if (!LegalOperations ||
2883 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
2884 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2887 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2888 if (isNullConstant(N0) && isNullConstant(N1)) {
2889 EVT VT = N0.getValueType();
2890 EVT CarryVT = CarryIn.getValueType();
2891 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2892 AddToWorklist(CarryExt.getNode());
2893 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2894 DAG.getConstant(1, DL, VT)),
2895 DAG.getConstant(0, DL, CarryVT));
2898 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2899 return Combined;
2901 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2902 return Combined;
2904 return SDValue();
2908 * If we are facing some sort of diamond carry propapagtion pattern try to
2909 * break it up to generate something like:
2910 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2912 * The end result is usually an increase in operation required, but because the
2913 * carry is now linearized, other tranforms can kick in and optimize the DAG.
2915 * Patterns typically look something like
2916 * (uaddo A, B)
2917 * / \
2918 * Carry Sum
2919 * | \
2920 * | (addcarry *, 0, Z)
2921 * | /
2922 * \ Carry
2923 * | /
2924 * (addcarry X, *, *)
2926 * But numerous variation exist. Our goal is to identify A, B, X and Z and
2927 * produce a combine with a single path for carry propagation.
2929 static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
2930 SDValue X, SDValue Carry0, SDValue Carry1,
2931 SDNode *N) {
2932 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
2933 return SDValue();
2934 if (Carry1.getOpcode() != ISD::UADDO)
2935 return SDValue();
2937 SDValue Z;
2940 * First look for a suitable Z. It will present itself in the form of
2941 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2943 if (Carry0.getOpcode() == ISD::ADDCARRY &&
2944 isNullConstant(Carry0.getOperand(1))) {
2945 Z = Carry0.getOperand(2);
2946 } else if (Carry0.getOpcode() == ISD::UADDO &&
2947 isOneConstant(Carry0.getOperand(1))) {
2948 EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
2949 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
2950 } else {
2951 // We couldn't find a suitable Z.
2952 return SDValue();
2956 auto cancelDiamond = [&](SDValue A,SDValue B) {
2957 SDLoc DL(N);
2958 SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
2959 Combiner.AddToWorklist(NewY.getNode());
2960 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
2961 DAG.getConstant(0, DL, X.getValueType()),
2962 NewY.getValue(1));
2966 * (uaddo A, B)
2968 * Sum
2970 * (addcarry *, 0, Z)
2972 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
2973 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
2977 * (addcarry A, 0, Z)
2979 * Sum
2981 * (uaddo *, B)
2983 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
2984 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
2987 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
2988 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
2991 return SDValue();
2994 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2995 SDNode *N) {
2996 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
2997 if (isBitwiseNot(N0))
2998 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
2999 SDLoc DL(N);
3000 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
3001 N0.getOperand(0), NotC);
3002 return CombineTo(N, Sub,
3003 flipBoolean(Sub.getValue(1), DL, DAG, TLI));
3006 // Iff the flag result is dead:
3007 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
3008 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3009 // or the dependency between the instructions.
3010 if ((N0.getOpcode() == ISD::ADD ||
3011 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3012 N0.getValue(1) != CarryIn)) &&
3013 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3014 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
3015 N0.getOperand(0), N0.getOperand(1), CarryIn);
3018 * When one of the addcarry argument is itself a carry, we may be facing
3019 * a diamond carry propagation. In which case we try to transform the DAG
3020 * to ensure linear carry propagation if that is possible.
3022 if (auto Y = getAsCarry(TLI, N1)) {
3023 // Because both are carries, Y and Z can be swapped.
3024 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
3025 return R;
3026 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
3027 return R;
3030 return SDValue();
3033 // Since it may not be valid to emit a fold to zero for vector initializers
3034 // check if we can before folding.
3035 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
3036 SelectionDAG &DAG, bool LegalOperations) {
3037 if (!VT.isVector())
3038 return DAG.getConstant(0, DL, VT);
3039 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
3040 return DAG.getConstant(0, DL, VT);
3041 return SDValue();
3044 SDValue DAGCombiner::visitSUB(SDNode *N) {
3045 SDValue N0 = N->getOperand(0);
3046 SDValue N1 = N->getOperand(1);
3047 EVT VT = N0.getValueType();
3048 SDLoc DL(N);
3050 // fold vector ops
3051 if (VT.isVector()) {
3052 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3053 return FoldedVOp;
3055 // fold (sub x, 0) -> x, vector edition
3056 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3057 return N0;
3060 // fold (sub x, x) -> 0
3061 // FIXME: Refactor this and xor and other similar operations together.
3062 if (N0 == N1)
3063 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
3064 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3065 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
3066 // fold (sub c1, c2) -> c1-c2
3067 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
3068 N1.getNode());
3071 if (SDValue NewSel = foldBinOpIntoSelect(N))
3072 return NewSel;
3074 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3076 // fold (sub x, c) -> (add x, -c)
3077 if (N1C) {
3078 return DAG.getNode(ISD::ADD, DL, VT, N0,
3079 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3082 if (isNullOrNullSplat(N0)) {
3083 unsigned BitWidth = VT.getScalarSizeInBits();
3084 // Right-shifting everything out but the sign bit followed by negation is
3085 // the same as flipping arithmetic/logical shift type without the negation:
3086 // -(X >>u 31) -> (X >>s 31)
3087 // -(X >>s 31) -> (X >>u 31)
3088 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
3089 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
3090 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
3091 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
3092 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
3093 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
3097 // 0 - X --> 0 if the sub is NUW.
3098 if (N->getFlags().hasNoUnsignedWrap())
3099 return N0;
3101 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
3102 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3103 // N1 must be 0 because negating the minimum signed value is undefined.
3104 if (N->getFlags().hasNoSignedWrap())
3105 return N0;
3107 // 0 - X --> X if X is 0 or the minimum signed value.
3108 return N1;
3112 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3113 if (isAllOnesOrAllOnesSplat(N0))
3114 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
3116 // fold (A - (0-B)) -> A+B
3117 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
3118 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
3120 // fold A-(A-B) -> B
3121 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
3122 return N1.getOperand(1);
3124 // fold (A+B)-A -> B
3125 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
3126 return N0.getOperand(1);
3128 // fold (A+B)-B -> A
3129 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
3130 return N0.getOperand(0);
3132 // fold (A+C1)-C2 -> A+(C1-C2)
3133 if (N0.getOpcode() == ISD::ADD &&
3134 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3135 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3136 SDValue NewC = DAG.FoldConstantArithmetic(
3137 ISD::SUB, DL, VT, N0.getOperand(1).getNode(), N1.getNode());
3138 assert(NewC && "Constant folding failed");
3139 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
3142 // fold C2-(A+C1) -> (C2-C1)-A
3143 if (N1.getOpcode() == ISD::ADD) {
3144 SDValue N11 = N1.getOperand(1);
3145 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
3146 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
3147 SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
3148 N11.getNode());
3149 assert(NewC && "Constant folding failed");
3150 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
3154 // fold (A-C1)-C2 -> A-(C1+C2)
3155 if (N0.getOpcode() == ISD::SUB &&
3156 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3157 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3158 SDValue NewC = DAG.FoldConstantArithmetic(
3159 ISD::ADD, DL, VT, N0.getOperand(1).getNode(), N1.getNode());
3160 assert(NewC && "Constant folding failed");
3161 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
3164 // fold (c1-A)-c2 -> (c1-c2)-A
3165 if (N0.getOpcode() == ISD::SUB &&
3166 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3167 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) {
3168 SDValue NewC = DAG.FoldConstantArithmetic(
3169 ISD::SUB, DL, VT, N0.getOperand(0).getNode(), N1.getNode());
3170 assert(NewC && "Constant folding failed");
3171 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
3174 // fold ((A+(B+or-C))-B) -> A+or-C
3175 if (N0.getOpcode() == ISD::ADD &&
3176 (N0.getOperand(1).getOpcode() == ISD::SUB ||
3177 N0.getOperand(1).getOpcode() == ISD::ADD) &&
3178 N0.getOperand(1).getOperand(0) == N1)
3179 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
3180 N0.getOperand(1).getOperand(1));
3182 // fold ((A+(C+B))-B) -> A+C
3183 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
3184 N0.getOperand(1).getOperand(1) == N1)
3185 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
3186 N0.getOperand(1).getOperand(0));
3188 // fold ((A-(B-C))-C) -> A-B
3189 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
3190 N0.getOperand(1).getOperand(1) == N1)
3191 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
3192 N0.getOperand(1).getOperand(0));
3194 // fold (A-(B-C)) -> A+(C-B)
3195 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
3196 return DAG.getNode(ISD::ADD, DL, VT, N0,
3197 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
3198 N1.getOperand(0)));
3200 // fold (X - (-Y * Z)) -> (X + (Y * Z))
3201 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
3202 if (N1.getOperand(0).getOpcode() == ISD::SUB &&
3203 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
3204 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3205 N1.getOperand(0).getOperand(1),
3206 N1.getOperand(1));
3207 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3209 if (N1.getOperand(1).getOpcode() == ISD::SUB &&
3210 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
3211 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3212 N1.getOperand(0),
3213 N1.getOperand(1).getOperand(1));
3214 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3218 // If either operand of a sub is undef, the result is undef
3219 if (N0.isUndef())
3220 return N0;
3221 if (N1.isUndef())
3222 return N1;
3224 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
3225 return V;
3227 if (SDValue V = foldAddSubOfSignBit(N, DAG))
3228 return V;
3230 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
3231 return V;
3233 // (x - y) - 1 -> add (xor y, -1), x
3234 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) {
3235 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
3236 DAG.getAllOnesConstant(DL, VT));
3237 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
3240 // Look for:
3241 // sub y, (xor x, -1)
3242 // And if the target does not like this form then turn into:
3243 // add (add x, y), 1
3244 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
3245 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
3246 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
3249 // Hoist one-use addition by non-opaque constant:
3250 // (x + C) - y -> (x - y) + C
3251 if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
3252 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3253 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3254 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
3256 // y - (x + C) -> (y - x) - C
3257 if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD &&
3258 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
3259 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
3260 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
3262 // (x - C) - y -> (x - y) - C
3263 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3264 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3265 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3266 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3267 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
3269 // (C - x) - y -> C - (x + y)
3270 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3271 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3272 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
3273 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
3276 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3277 // rather than 'sub 0/1' (the sext should get folded).
3278 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3279 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
3280 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
3281 TLI.getBooleanContents(VT) ==
3282 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3283 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
3284 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
3287 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3288 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
3289 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
3290 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
3291 SDValue S0 = N1.getOperand(0);
3292 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) {
3293 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3294 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
3295 if (C->getAPIntValue() == (OpSizeInBits - 1))
3296 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
3301 // If the relocation model supports it, consider symbol offsets.
3302 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
3303 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
3304 // fold (sub Sym, c) -> Sym-c
3305 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
3306 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
3307 GA->getOffset() -
3308 (uint64_t)N1C->getSExtValue());
3309 // fold (sub Sym+c1, Sym+c2) -> c1-c2
3310 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
3311 if (GA->getGlobal() == GB->getGlobal())
3312 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
3313 DL, VT);
3316 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3317 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3318 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3319 if (TN->getVT() == MVT::i1) {
3320 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3321 DAG.getConstant(1, DL, VT));
3322 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
3326 // Prefer an add for more folding potential and possibly better codegen:
3327 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3328 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
3329 SDValue ShAmt = N1.getOperand(1);
3330 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
3331 if (ShAmtC &&
3332 ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
3333 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
3334 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
3338 return SDValue();
3341 SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
3342 SDValue N0 = N->getOperand(0);
3343 SDValue N1 = N->getOperand(1);
3344 EVT VT = N0.getValueType();
3345 SDLoc DL(N);
3347 // fold vector ops
3348 if (VT.isVector()) {
3349 // TODO SimplifyVBinOp
3351 // fold (sub_sat x, 0) -> x, vector edition
3352 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3353 return N0;
3356 // fold (sub_sat x, undef) -> 0
3357 if (N0.isUndef() || N1.isUndef())
3358 return DAG.getConstant(0, DL, VT);
3360 // fold (sub_sat x, x) -> 0
3361 if (N0 == N1)
3362 return DAG.getConstant(0, DL, VT);
3364 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3365 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
3366 // fold (sub_sat c1, c2) -> c3
3367 return DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, N0.getNode(),
3368 N1.getNode());
3371 // fold (sub_sat x, 0) -> x
3372 if (isNullConstant(N1))
3373 return N0;
3375 return SDValue();
3378 SDValue DAGCombiner::visitSUBC(SDNode *N) {
3379 SDValue N0 = N->getOperand(0);
3380 SDValue N1 = N->getOperand(1);
3381 EVT VT = N0.getValueType();
3382 SDLoc DL(N);
3384 // If the flag result is dead, turn this into an SUB.
3385 if (!N->hasAnyUseOfValue(1))
3386 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3387 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3389 // fold (subc x, x) -> 0 + no borrow
3390 if (N0 == N1)
3391 return CombineTo(N, DAG.getConstant(0, DL, VT),
3392 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3394 // fold (subc x, 0) -> x + no borrow
3395 if (isNullConstant(N1))
3396 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3398 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3399 if (isAllOnesConstant(N0))
3400 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3401 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3403 return SDValue();
3406 SDValue DAGCombiner::visitSUBO(SDNode *N) {
3407 SDValue N0 = N->getOperand(0);
3408 SDValue N1 = N->getOperand(1);
3409 EVT VT = N0.getValueType();
3410 bool IsSigned = (ISD::SSUBO == N->getOpcode());
3412 EVT CarryVT = N->getValueType(1);
3413 SDLoc DL(N);
3415 // If the flag result is dead, turn this into an SUB.
3416 if (!N->hasAnyUseOfValue(1))
3417 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3418 DAG.getUNDEF(CarryVT));
3420 // fold (subo x, x) -> 0 + no borrow
3421 if (N0 == N1)
3422 return CombineTo(N, DAG.getConstant(0, DL, VT),
3423 DAG.getConstant(0, DL, CarryVT));
3425 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3427 // fold (subox, c) -> (addo x, -c)
3428 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
3429 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
3430 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3433 // fold (subo x, 0) -> x + no borrow
3434 if (isNullOrNullSplat(N1))
3435 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3437 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3438 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
3439 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3440 DAG.getConstant(0, DL, CarryVT));
3442 return SDValue();
3445 SDValue DAGCombiner::visitSUBE(SDNode *N) {
3446 SDValue N0 = N->getOperand(0);
3447 SDValue N1 = N->getOperand(1);
3448 SDValue CarryIn = N->getOperand(2);
3450 // fold (sube x, y, false) -> (subc x, y)
3451 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3452 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
3454 return SDValue();
3457 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
3458 SDValue N0 = N->getOperand(0);
3459 SDValue N1 = N->getOperand(1);
3460 SDValue CarryIn = N->getOperand(2);
3462 // fold (subcarry x, y, false) -> (usubo x, y)
3463 if (isNullConstant(CarryIn)) {
3464 if (!LegalOperations ||
3465 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
3466 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
3469 return SDValue();
3472 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT and UMULFIX here.
3473 SDValue DAGCombiner::visitMULFIX(SDNode *N) {
3474 SDValue N0 = N->getOperand(0);
3475 SDValue N1 = N->getOperand(1);
3476 SDValue Scale = N->getOperand(2);
3477 EVT VT = N0.getValueType();
3479 // fold (mulfix x, undef, scale) -> 0
3480 if (N0.isUndef() || N1.isUndef())
3481 return DAG.getConstant(0, SDLoc(N), VT);
3483 // Canonicalize constant to RHS (vector doesn't have to splat)
3484 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3485 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3486 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
3488 // fold (mulfix x, 0, scale) -> 0
3489 if (isNullConstant(N1))
3490 return DAG.getConstant(0, SDLoc(N), VT);
3492 return SDValue();
3495 SDValue DAGCombiner::visitMUL(SDNode *N) {
3496 SDValue N0 = N->getOperand(0);
3497 SDValue N1 = N->getOperand(1);
3498 EVT VT = N0.getValueType();
3500 // fold (mul x, undef) -> 0
3501 if (N0.isUndef() || N1.isUndef())
3502 return DAG.getConstant(0, SDLoc(N), VT);
3504 bool N0IsConst = false;
3505 bool N1IsConst = false;
3506 bool N1IsOpaqueConst = false;
3507 bool N0IsOpaqueConst = false;
3508 APInt ConstValue0, ConstValue1;
3509 // fold vector ops
3510 if (VT.isVector()) {
3511 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3512 return FoldedVOp;
3514 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
3515 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
3516 assert((!N0IsConst ||
3517 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
3518 "Splat APInt should be element width");
3519 assert((!N1IsConst ||
3520 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
3521 "Splat APInt should be element width");
3522 } else {
3523 N0IsConst = isa<ConstantSDNode>(N0);
3524 if (N0IsConst) {
3525 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
3526 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
3528 N1IsConst = isa<ConstantSDNode>(N1);
3529 if (N1IsConst) {
3530 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3531 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3535 // fold (mul c1, c2) -> c1*c2
3536 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
3537 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
3538 N0.getNode(), N1.getNode());
3540 // canonicalize constant to RHS (vector doesn't have to splat)
3541 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3542 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3543 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
3544 // fold (mul x, 0) -> 0
3545 if (N1IsConst && ConstValue1.isNullValue())
3546 return N1;
3547 // fold (mul x, 1) -> x
3548 if (N1IsConst && ConstValue1.isOneValue())
3549 return N0;
3551 if (SDValue NewSel = foldBinOpIntoSelect(N))
3552 return NewSel;
3554 // fold (mul x, -1) -> 0-x
3555 if (N1IsConst && ConstValue1.isAllOnesValue()) {
3556 SDLoc DL(N);
3557 return DAG.getNode(ISD::SUB, DL, VT,
3558 DAG.getConstant(0, DL, VT), N0);
3560 // fold (mul x, (1 << c)) -> x << c
3561 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3562 DAG.isKnownToBeAPowerOfTwo(N1) &&
3563 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
3564 SDLoc DL(N);
3565 SDValue LogBase2 = BuildLogBase2(N1, DL);
3566 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3567 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3568 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
3570 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3571 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
3572 unsigned Log2Val = (-ConstValue1).logBase2();
3573 SDLoc DL(N);
3574 // FIXME: If the input is something that is easily negated (e.g. a
3575 // single-use add), we should put the negate there.
3576 return DAG.getNode(ISD::SUB, DL, VT,
3577 DAG.getConstant(0, DL, VT),
3578 DAG.getNode(ISD::SHL, DL, VT, N0,
3579 DAG.getConstant(Log2Val, DL,
3580 getShiftAmountTy(N0.getValueType()))));
3583 // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3584 // mul x, (2^N + 1) --> add (shl x, N), x
3585 // mul x, (2^N - 1) --> sub (shl x, N), x
3586 // Examples: x * 33 --> (x << 5) + x
3587 // x * 15 --> (x << 4) - x
3588 // x * -33 --> -((x << 5) + x)
3589 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3590 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
3591 // TODO: We could handle more general decomposition of any constant by
3592 // having the target set a limit on number of ops and making a
3593 // callback to determine that sequence (similar to sqrt expansion).
3594 unsigned MathOp = ISD::DELETED_NODE;
3595 APInt MulC = ConstValue1.abs();
3596 if ((MulC - 1).isPowerOf2())
3597 MathOp = ISD::ADD;
3598 else if ((MulC + 1).isPowerOf2())
3599 MathOp = ISD::SUB;
3601 if (MathOp != ISD::DELETED_NODE) {
3602 unsigned ShAmt =
3603 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
3604 assert(ShAmt < VT.getScalarSizeInBits() &&
3605 "multiply-by-constant generated out of bounds shift");
3606 SDLoc DL(N);
3607 SDValue Shl =
3608 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
3609 SDValue R = DAG.getNode(MathOp, DL, VT, Shl, N0);
3610 if (ConstValue1.isNegative())
3611 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
3612 return R;
3616 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3617 if (N0.getOpcode() == ISD::SHL &&
3618 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3619 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3620 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
3621 if (isConstantOrConstantVector(C3))
3622 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
3625 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3626 // use.
3628 SDValue Sh(nullptr, 0), Y(nullptr, 0);
3630 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3631 if (N0.getOpcode() == ISD::SHL &&
3632 isConstantOrConstantVector(N0.getOperand(1)) &&
3633 N0.getNode()->hasOneUse()) {
3634 Sh = N0; Y = N1;
3635 } else if (N1.getOpcode() == ISD::SHL &&
3636 isConstantOrConstantVector(N1.getOperand(1)) &&
3637 N1.getNode()->hasOneUse()) {
3638 Sh = N1; Y = N0;
3641 if (Sh.getNode()) {
3642 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
3643 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
3647 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3648 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
3649 N0.getOpcode() == ISD::ADD &&
3650 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
3651 isMulAddWithConstProfitable(N, N0, N1))
3652 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
3653 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
3654 N0.getOperand(0), N1),
3655 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
3656 N0.getOperand(1), N1));
3658 // reassociate mul
3659 if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
3660 return RMUL;
3662 return SDValue();
3665 /// Return true if divmod libcall is available.
3666 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
3667 const TargetLowering &TLI) {
3668 RTLIB::Libcall LC;
3669 EVT NodeType = Node->getValueType(0);
3670 if (!NodeType.isSimple())
3671 return false;
3672 switch (NodeType.getSimpleVT().SimpleTy) {
3673 default: return false; // No libcall for vector types.
3674 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
3675 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
3676 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
3677 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
3678 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
3681 return TLI.getLibcallName(LC) != nullptr;
3684 /// Issue divrem if both quotient and remainder are needed.
3685 SDValue DAGCombiner::useDivRem(SDNode *Node) {
3686 if (Node->use_empty())
3687 return SDValue(); // This is a dead node, leave it alone.
3689 unsigned Opcode = Node->getOpcode();
3690 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
3691 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3693 // DivMod lib calls can still work on non-legal types if using lib-calls.
3694 EVT VT = Node->getValueType(0);
3695 if (VT.isVector() || !VT.isInteger())
3696 return SDValue();
3698 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
3699 return SDValue();
3701 // If DIVREM is going to get expanded into a libcall,
3702 // but there is no libcall available, then don't combine.
3703 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
3704 !isDivRemLibcallAvailable(Node, isSigned, TLI))
3705 return SDValue();
3707 // If div is legal, it's better to do the normal expansion
3708 unsigned OtherOpcode = 0;
3709 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
3710 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
3711 if (TLI.isOperationLegalOrCustom(Opcode, VT))
3712 return SDValue();
3713 } else {
3714 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3715 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
3716 return SDValue();
3719 SDValue Op0 = Node->getOperand(0);
3720 SDValue Op1 = Node->getOperand(1);
3721 SDValue combined;
3722 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
3723 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
3724 SDNode *User = *UI;
3725 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
3726 User->use_empty())
3727 continue;
3728 // Convert the other matching node(s), too;
3729 // otherwise, the DIVREM may get target-legalized into something
3730 // target-specific that we won't be able to recognize.
3731 unsigned UserOpc = User->getOpcode();
3732 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
3733 User->getOperand(0) == Op0 &&
3734 User->getOperand(1) == Op1) {
3735 if (!combined) {
3736 if (UserOpc == OtherOpcode) {
3737 SDVTList VTs = DAG.getVTList(VT, VT);
3738 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
3739 } else if (UserOpc == DivRemOpc) {
3740 combined = SDValue(User, 0);
3741 } else {
3742 assert(UserOpc == Opcode);
3743 continue;
3746 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
3747 CombineTo(User, combined);
3748 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
3749 CombineTo(User, combined.getValue(1));
3752 return combined;
3755 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
3756 SDValue N0 = N->getOperand(0);
3757 SDValue N1 = N->getOperand(1);
3758 EVT VT = N->getValueType(0);
3759 SDLoc DL(N);
3761 unsigned Opc = N->getOpcode();
3762 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
3763 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3765 // X / undef -> undef
3766 // X % undef -> undef
3767 // X / 0 -> undef
3768 // X % 0 -> undef
3769 // NOTE: This includes vectors where any divisor element is zero/undef.
3770 if (DAG.isUndef(Opc, {N0, N1}))
3771 return DAG.getUNDEF(VT);
3773 // undef / X -> 0
3774 // undef % X -> 0
3775 if (N0.isUndef())
3776 return DAG.getConstant(0, DL, VT);
3778 // 0 / X -> 0
3779 // 0 % X -> 0
3780 ConstantSDNode *N0C = isConstOrConstSplat(N0);
3781 if (N0C && N0C->isNullValue())
3782 return N0;
3784 // X / X -> 1
3785 // X % X -> 0
3786 if (N0 == N1)
3787 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
3789 // X / 1 -> X
3790 // X % 1 -> 0
3791 // If this is a boolean op (single-bit element type), we can't have
3792 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
3793 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
3794 // it's a 1.
3795 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
3796 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
3798 return SDValue();
3801 SDValue DAGCombiner::visitSDIV(SDNode *N) {
3802 SDValue N0 = N->getOperand(0);
3803 SDValue N1 = N->getOperand(1);
3804 EVT VT = N->getValueType(0);
3805 EVT CCVT = getSetCCResultType(VT);
3807 // fold vector ops
3808 if (VT.isVector())
3809 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3810 return FoldedVOp;
3812 SDLoc DL(N);
3814 // fold (sdiv c1, c2) -> c1/c2
3815 ConstantSDNode *N0C = isConstOrConstSplat(N0);
3816 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3817 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
3818 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
3819 // fold (sdiv X, -1) -> 0-X
3820 if (N1C && N1C->isAllOnesValue())
3821 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
3822 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3823 if (N1C && N1C->getAPIntValue().isMinSignedValue())
3824 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3825 DAG.getConstant(1, DL, VT),
3826 DAG.getConstant(0, DL, VT));
3828 if (SDValue V = simplifyDivRem(N, DAG))
3829 return V;
3831 if (SDValue NewSel = foldBinOpIntoSelect(N))
3832 return NewSel;
3834 // If we know the sign bits of both operands are zero, strength reduce to a
3835 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
3836 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3837 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
3839 if (SDValue V = visitSDIVLike(N0, N1, N)) {
3840 // If the corresponding remainder node exists, update its users with
3841 // (Dividend - (Quotient * Divisor).
3842 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
3843 { N0, N1 })) {
3844 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3845 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3846 AddToWorklist(Mul.getNode());
3847 AddToWorklist(Sub.getNode());
3848 CombineTo(RemNode, Sub);
3850 return V;
3853 // sdiv, srem -> sdivrem
3854 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3855 // true. Otherwise, we break the simplification logic in visitREM().
3856 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3857 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3858 if (SDValue DivRem = useDivRem(N))
3859 return DivRem;
3861 return SDValue();
3864 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3865 SDLoc DL(N);
3866 EVT VT = N->getValueType(0);
3867 EVT CCVT = getSetCCResultType(VT);
3868 unsigned BitWidth = VT.getScalarSizeInBits();
3870 // Helper for determining whether a value is a power-2 constant scalar or a
3871 // vector of such elements.
3872 auto IsPowerOfTwo = [](ConstantSDNode *C) {
3873 if (C->isNullValue() || C->isOpaque())
3874 return false;
3875 if (C->getAPIntValue().isPowerOf2())
3876 return true;
3877 if ((-C->getAPIntValue()).isPowerOf2())
3878 return true;
3879 return false;
3882 // fold (sdiv X, pow2) -> simple ops after legalize
3883 // FIXME: We check for the exact bit here because the generic lowering gives
3884 // better results in that case. The target-specific lowering should learn how
3885 // to handle exact sdivs efficiently.
3886 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
3887 // Target-specific implementation of sdiv x, pow2.
3888 if (SDValue Res = BuildSDIVPow2(N))
3889 return Res;
3891 // Create constants that are functions of the shift amount value.
3892 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
3893 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
3894 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
3895 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
3896 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
3897 if (!isConstantOrConstantVector(Inexact))
3898 return SDValue();
3900 // Splat the sign bit into the register
3901 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
3902 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
3903 AddToWorklist(Sign.getNode());
3905 // Add (N0 < 0) ? abs2 - 1 : 0;
3906 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
3907 AddToWorklist(Srl.getNode());
3908 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
3909 AddToWorklist(Add.getNode());
3910 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
3911 AddToWorklist(Sra.getNode());
3913 // Special case: (sdiv X, 1) -> X
3914 // Special Case: (sdiv X, -1) -> 0-X
3915 SDValue One = DAG.getConstant(1, DL, VT);
3916 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
3917 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
3918 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
3919 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
3920 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
3922 // If dividing by a positive value, we're done. Otherwise, the result must
3923 // be negated.
3924 SDValue Zero = DAG.getConstant(0, DL, VT);
3925 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
3927 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3928 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
3929 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
3930 return Res;
3933 // If integer divide is expensive and we satisfy the requirements, emit an
3934 // alternate sequence. Targets may check function attributes for size/speed
3935 // trade-offs.
3936 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3937 if (isConstantOrConstantVector(N1) &&
3938 !TLI.isIntDivCheap(N->getValueType(0), Attr))
3939 if (SDValue Op = BuildSDIV(N))
3940 return Op;
3942 return SDValue();
3945 SDValue DAGCombiner::visitUDIV(SDNode *N) {
3946 SDValue N0 = N->getOperand(0);
3947 SDValue N1 = N->getOperand(1);
3948 EVT VT = N->getValueType(0);
3949 EVT CCVT = getSetCCResultType(VT);
3951 // fold vector ops
3952 if (VT.isVector())
3953 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3954 return FoldedVOp;
3956 SDLoc DL(N);
3958 // fold (udiv c1, c2) -> c1/c2
3959 ConstantSDNode *N0C = isConstOrConstSplat(N0);
3960 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3961 if (N0C && N1C)
3962 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
3963 N0C, N1C))
3964 return Folded;
3965 // fold (udiv X, -1) -> select(X == -1, 1, 0)
3966 if (N1C && N1C->getAPIntValue().isAllOnesValue())
3967 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3968 DAG.getConstant(1, DL, VT),
3969 DAG.getConstant(0, DL, VT));
3971 if (SDValue V = simplifyDivRem(N, DAG))
3972 return V;
3974 if (SDValue NewSel = foldBinOpIntoSelect(N))
3975 return NewSel;
3977 if (SDValue V = visitUDIVLike(N0, N1, N)) {
3978 // If the corresponding remainder node exists, update its users with
3979 // (Dividend - (Quotient * Divisor).
3980 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
3981 { N0, N1 })) {
3982 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3983 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3984 AddToWorklist(Mul.getNode());
3985 AddToWorklist(Sub.getNode());
3986 CombineTo(RemNode, Sub);
3988 return V;
3991 // sdiv, srem -> sdivrem
3992 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3993 // true. Otherwise, we break the simplification logic in visitREM().
3994 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3995 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3996 if (SDValue DivRem = useDivRem(N))
3997 return DivRem;
3999 return SDValue();
4002 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
4003 SDLoc DL(N);
4004 EVT VT = N->getValueType(0);
4006 // fold (udiv x, (1 << c)) -> x >>u c
4007 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4008 DAG.isKnownToBeAPowerOfTwo(N1)) {
4009 SDValue LogBase2 = BuildLogBase2(N1, DL);
4010 AddToWorklist(LogBase2.getNode());
4012 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4013 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4014 AddToWorklist(Trunc.getNode());
4015 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4018 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
4019 if (N1.getOpcode() == ISD::SHL) {
4020 SDValue N10 = N1.getOperand(0);
4021 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
4022 DAG.isKnownToBeAPowerOfTwo(N10)) {
4023 SDValue LogBase2 = BuildLogBase2(N10, DL);
4024 AddToWorklist(LogBase2.getNode());
4026 EVT ADDVT = N1.getOperand(1).getValueType();
4027 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
4028 AddToWorklist(Trunc.getNode());
4029 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
4030 AddToWorklist(Add.getNode());
4031 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
4035 // fold (udiv x, c) -> alternate
4036 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4037 if (isConstantOrConstantVector(N1) &&
4038 !TLI.isIntDivCheap(N->getValueType(0), Attr))
4039 if (SDValue Op = BuildUDIV(N))
4040 return Op;
4042 return SDValue();
4045 // handles ISD::SREM and ISD::UREM
4046 SDValue DAGCombiner::visitREM(SDNode *N) {
4047 unsigned Opcode = N->getOpcode();
4048 SDValue N0 = N->getOperand(0);
4049 SDValue N1 = N->getOperand(1);
4050 EVT VT = N->getValueType(0);
4051 EVT CCVT = getSetCCResultType(VT);
4053 bool isSigned = (Opcode == ISD::SREM);
4054 SDLoc DL(N);
4056 // fold (rem c1, c2) -> c1%c2
4057 ConstantSDNode *N0C = isConstOrConstSplat(N0);
4058 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4059 if (N0C && N1C)
4060 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
4061 return Folded;
4062 // fold (urem X, -1) -> select(X == -1, 0, x)
4063 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue())
4064 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4065 DAG.getConstant(0, DL, VT), N0);
4067 if (SDValue V = simplifyDivRem(N, DAG))
4068 return V;
4070 if (SDValue NewSel = foldBinOpIntoSelect(N))
4071 return NewSel;
4073 if (isSigned) {
4074 // If we know the sign bits of both operands are zero, strength reduce to a
4075 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4076 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4077 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
4078 } else {
4079 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4080 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
4081 // fold (urem x, pow2) -> (and x, pow2-1)
4082 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4083 AddToWorklist(Add.getNode());
4084 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4086 if (N1.getOpcode() == ISD::SHL &&
4087 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
4088 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4089 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4090 AddToWorklist(Add.getNode());
4091 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4095 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4097 // If X/C can be simplified by the division-by-constant logic, lower
4098 // X%C to the equivalent of X-X/C*C.
4099 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4100 // speculative DIV must not cause a DIVREM conversion. We guard against this
4101 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
4102 // combine will not return a DIVREM. Regardless, checking cheapness here
4103 // makes sense since the simplification results in fatter code.
4104 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
4105 SDValue OptimizedDiv =
4106 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
4107 if (OptimizedDiv.getNode()) {
4108 // If the equivalent Div node also exists, update its users.
4109 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4110 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
4111 { N0, N1 }))
4112 CombineTo(DivNode, OptimizedDiv);
4113 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
4114 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4115 AddToWorklist(OptimizedDiv.getNode());
4116 AddToWorklist(Mul.getNode());
4117 return Sub;
4121 // sdiv, srem -> sdivrem
4122 if (SDValue DivRem = useDivRem(N))
4123 return DivRem.getValue(1);
4125 return SDValue();
4128 SDValue DAGCombiner::visitMULHS(SDNode *N) {
4129 SDValue N0 = N->getOperand(0);
4130 SDValue N1 = N->getOperand(1);
4131 EVT VT = N->getValueType(0);
4132 SDLoc DL(N);
4134 if (VT.isVector()) {
4135 // fold (mulhs x, 0) -> 0
4136 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4137 return N1;
4138 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4139 return N0;
4142 // fold (mulhs x, 0) -> 0
4143 if (isNullConstant(N1))
4144 return N1;
4145 // fold (mulhs x, 1) -> (sra x, size(x)-1)
4146 if (isOneConstant(N1))
4147 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
4148 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
4149 getShiftAmountTy(N0.getValueType())));
4151 // fold (mulhs x, undef) -> 0
4152 if (N0.isUndef() || N1.isUndef())
4153 return DAG.getConstant(0, DL, VT);
4155 // If the type twice as wide is legal, transform the mulhs to a wider multiply
4156 // plus a shift.
4157 if (VT.isSimple() && !VT.isVector()) {
4158 MVT Simple = VT.getSimpleVT();
4159 unsigned SimpleSize = Simple.getSizeInBits();
4160 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4161 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4162 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
4163 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
4164 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4165 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4166 DAG.getConstant(SimpleSize, DL,
4167 getShiftAmountTy(N1.getValueType())));
4168 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4172 return SDValue();
4175 SDValue DAGCombiner::visitMULHU(SDNode *N) {
4176 SDValue N0 = N->getOperand(0);
4177 SDValue N1 = N->getOperand(1);
4178 EVT VT = N->getValueType(0);
4179 SDLoc DL(N);
4181 if (VT.isVector()) {
4182 // fold (mulhu x, 0) -> 0
4183 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4184 return N1;
4185 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4186 return N0;
4189 // fold (mulhu x, 0) -> 0
4190 if (isNullConstant(N1))
4191 return N1;
4192 // fold (mulhu x, 1) -> 0
4193 if (isOneConstant(N1))
4194 return DAG.getConstant(0, DL, N0.getValueType());
4195 // fold (mulhu x, undef) -> 0
4196 if (N0.isUndef() || N1.isUndef())
4197 return DAG.getConstant(0, DL, VT);
4199 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4200 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4201 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
4202 unsigned NumEltBits = VT.getScalarSizeInBits();
4203 SDValue LogBase2 = BuildLogBase2(N1, DL);
4204 SDValue SRLAmt = DAG.getNode(
4205 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
4206 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4207 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
4208 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4211 // If the type twice as wide is legal, transform the mulhu to a wider multiply
4212 // plus a shift.
4213 if (VT.isSimple() && !VT.isVector()) {
4214 MVT Simple = VT.getSimpleVT();
4215 unsigned SimpleSize = Simple.getSizeInBits();
4216 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4217 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4218 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
4219 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
4220 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4221 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4222 DAG.getConstant(SimpleSize, DL,
4223 getShiftAmountTy(N1.getValueType())));
4224 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4228 return SDValue();
4231 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4232 /// give the opcodes for the two computations that are being performed. Return
4233 /// true if a simplification was made.
4234 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
4235 unsigned HiOp) {
4236 // If the high half is not needed, just compute the low half.
4237 bool HiExists = N->hasAnyUseOfValue(1);
4238 if (!HiExists && (!LegalOperations ||
4239 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
4240 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4241 return CombineTo(N, Res, Res);
4244 // If the low half is not needed, just compute the high half.
4245 bool LoExists = N->hasAnyUseOfValue(0);
4246 if (!LoExists && (!LegalOperations ||
4247 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
4248 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4249 return CombineTo(N, Res, Res);
4252 // If both halves are used, return as it is.
4253 if (LoExists && HiExists)
4254 return SDValue();
4256 // If the two computed results can be simplified separately, separate them.
4257 if (LoExists) {
4258 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4259 AddToWorklist(Lo.getNode());
4260 SDValue LoOpt = combine(Lo.getNode());
4261 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
4262 (!LegalOperations ||
4263 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
4264 return CombineTo(N, LoOpt, LoOpt);
4267 if (HiExists) {
4268 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4269 AddToWorklist(Hi.getNode());
4270 SDValue HiOpt = combine(Hi.getNode());
4271 if (HiOpt.getNode() && HiOpt != Hi &&
4272 (!LegalOperations ||
4273 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
4274 return CombineTo(N, HiOpt, HiOpt);
4277 return SDValue();
4280 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
4281 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
4282 return Res;
4284 EVT VT = N->getValueType(0);
4285 SDLoc DL(N);
4287 // If the type is twice as wide is legal, transform the mulhu to a wider
4288 // multiply plus a shift.
4289 if (VT.isSimple() && !VT.isVector()) {
4290 MVT Simple = VT.getSimpleVT();
4291 unsigned SimpleSize = Simple.getSizeInBits();
4292 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4293 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4294 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
4295 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
4296 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4297 // Compute the high part as N1.
4298 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4299 DAG.getConstant(SimpleSize, DL,
4300 getShiftAmountTy(Lo.getValueType())));
4301 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4302 // Compute the low part as N0.
4303 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4304 return CombineTo(N, Lo, Hi);
4308 return SDValue();
4311 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
4312 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
4313 return Res;
4315 EVT VT = N->getValueType(0);
4316 SDLoc DL(N);
4318 // If the type is twice as wide is legal, transform the mulhu to a wider
4319 // multiply plus a shift.
4320 if (VT.isSimple() && !VT.isVector()) {
4321 MVT Simple = VT.getSimpleVT();
4322 unsigned SimpleSize = Simple.getSizeInBits();
4323 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4324 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4325 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
4326 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
4327 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4328 // Compute the high part as N1.
4329 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4330 DAG.getConstant(SimpleSize, DL,
4331 getShiftAmountTy(Lo.getValueType())));
4332 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4333 // Compute the low part as N0.
4334 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4335 return CombineTo(N, Lo, Hi);
4339 return SDValue();
4342 SDValue DAGCombiner::visitMULO(SDNode *N) {
4343 bool IsSigned = (ISD::SMULO == N->getOpcode());
4345 // (mulo x, 2) -> (addo x, x)
4346 if (ConstantSDNode *C2 = isConstOrConstSplat(N->getOperand(1)))
4347 if (C2->getAPIntValue() == 2)
4348 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, SDLoc(N),
4349 N->getVTList(), N->getOperand(0), N->getOperand(0));
4351 return SDValue();
4354 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
4355 SDValue N0 = N->getOperand(0);
4356 SDValue N1 = N->getOperand(1);
4357 EVT VT = N0.getValueType();
4359 // fold vector ops
4360 if (VT.isVector())
4361 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4362 return FoldedVOp;
4364 // fold operation with constant operands.
4365 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4366 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4367 if (N0C && N1C)
4368 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
4370 // canonicalize constant to RHS
4371 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4372 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4373 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
4375 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4376 // Only do this if the current op isn't legal and the flipped is.
4377 unsigned Opcode = N->getOpcode();
4378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4379 if (!TLI.isOperationLegal(Opcode, VT) &&
4380 (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
4381 (N1.isUndef() || DAG.SignBitIsZero(N1))) {
4382 unsigned AltOpcode;
4383 switch (Opcode) {
4384 case ISD::SMIN: AltOpcode = ISD::UMIN; break;
4385 case ISD::SMAX: AltOpcode = ISD::UMAX; break;
4386 case ISD::UMIN: AltOpcode = ISD::SMIN; break;
4387 case ISD::UMAX: AltOpcode = ISD::SMAX; break;
4388 default: llvm_unreachable("Unknown MINMAX opcode");
4390 if (TLI.isOperationLegal(AltOpcode, VT))
4391 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
4394 return SDValue();
4397 /// If this is a bitwise logic instruction and both operands have the same
4398 /// opcode, try to sink the other opcode after the logic instruction.
4399 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
4400 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
4401 EVT VT = N0.getValueType();
4402 unsigned LogicOpcode = N->getOpcode();
4403 unsigned HandOpcode = N0.getOpcode();
4404 assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
4405 LogicOpcode == ISD::XOR) && "Expected logic opcode");
4406 assert(HandOpcode == N1.getOpcode() && "Bad input!");
4408 // Bail early if none of these transforms apply.
4409 if (N0.getNumOperands() == 0)
4410 return SDValue();
4412 // FIXME: We should check number of uses of the operands to not increase
4413 // the instruction count for all transforms.
4415 // Handle size-changing casts.
4416 SDValue X = N0.getOperand(0);
4417 SDValue Y = N1.getOperand(0);
4418 EVT XVT = X.getValueType();
4419 SDLoc DL(N);
4420 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
4421 HandOpcode == ISD::SIGN_EXTEND) {
4422 // If both operands have other uses, this transform would create extra
4423 // instructions without eliminating anything.
4424 if (!N0.hasOneUse() && !N1.hasOneUse())
4425 return SDValue();
4426 // We need matching integer source types.
4427 if (XVT != Y.getValueType())
4428 return SDValue();
4429 // Don't create an illegal op during or after legalization. Don't ever
4430 // create an unsupported vector op.
4431 if ((VT.isVector() || LegalOperations) &&
4432 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
4433 return SDValue();
4434 // Avoid infinite looping with PromoteIntBinOp.
4435 // TODO: Should we apply desirable/legal constraints to all opcodes?
4436 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
4437 !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
4438 return SDValue();
4439 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
4440 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4441 return DAG.getNode(HandOpcode, DL, VT, Logic);
4444 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
4445 if (HandOpcode == ISD::TRUNCATE) {
4446 // If both operands have other uses, this transform would create extra
4447 // instructions without eliminating anything.
4448 if (!N0.hasOneUse() && !N1.hasOneUse())
4449 return SDValue();
4450 // We need matching source types.
4451 if (XVT != Y.getValueType())
4452 return SDValue();
4453 // Don't create an illegal op during or after legalization.
4454 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
4455 return SDValue();
4456 // Be extra careful sinking truncate. If it's free, there's no benefit in
4457 // widening a binop. Also, don't create a logic op on an illegal type.
4458 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
4459 return SDValue();
4460 if (!TLI.isTypeLegal(XVT))
4461 return SDValue();
4462 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4463 return DAG.getNode(HandOpcode, DL, VT, Logic);
4466 // For binops SHL/SRL/SRA/AND:
4467 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
4468 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
4469 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
4470 N0.getOperand(1) == N1.getOperand(1)) {
4471 // If either operand has other uses, this transform is not an improvement.
4472 if (!N0.hasOneUse() || !N1.hasOneUse())
4473 return SDValue();
4474 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4475 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
4478 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
4479 if (HandOpcode == ISD::BSWAP) {
4480 // If either operand has other uses, this transform is not an improvement.
4481 if (!N0.hasOneUse() || !N1.hasOneUse())
4482 return SDValue();
4483 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4484 return DAG.getNode(HandOpcode, DL, VT, Logic);
4487 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4488 // Only perform this optimization up until type legalization, before
4489 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4490 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4491 // we don't want to undo this promotion.
4492 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4493 // on scalars.
4494 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
4495 Level <= AfterLegalizeTypes) {
4496 // Input types must be integer and the same.
4497 if (XVT.isInteger() && XVT == Y.getValueType()) {
4498 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4499 return DAG.getNode(HandOpcode, DL, VT, Logic);
4503 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4504 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4505 // If both shuffles use the same mask, and both shuffle within a single
4506 // vector, then it is worthwhile to move the swizzle after the operation.
4507 // The type-legalizer generates this pattern when loading illegal
4508 // vector types from memory. In many cases this allows additional shuffle
4509 // optimizations.
4510 // There are other cases where moving the shuffle after the xor/and/or
4511 // is profitable even if shuffles don't perform a swizzle.
4512 // If both shuffles use the same mask, and both shuffles have the same first
4513 // or second operand, then it might still be profitable to move the shuffle
4514 // after the xor/and/or operation.
4515 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
4516 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
4517 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
4518 assert(X.getValueType() == Y.getValueType() &&
4519 "Inputs to shuffles are not the same type");
4521 // Check that both shuffles use the same mask. The masks are known to be of
4522 // the same length because the result vector type is the same.
4523 // Check also that shuffles have only one use to avoid introducing extra
4524 // instructions.
4525 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
4526 !SVN0->getMask().equals(SVN1->getMask()))
4527 return SDValue();
4529 // Don't try to fold this node if it requires introducing a
4530 // build vector of all zeros that might be illegal at this stage.
4531 SDValue ShOp = N0.getOperand(1);
4532 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4533 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4535 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4536 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
4537 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
4538 N0.getOperand(0), N1.getOperand(0));
4539 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
4542 // Don't try to fold this node if it requires introducing a
4543 // build vector of all zeros that might be illegal at this stage.
4544 ShOp = N0.getOperand(0);
4545 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4546 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4548 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4549 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
4550 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
4551 N1.getOperand(1));
4552 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
4556 return SDValue();
4559 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4560 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
4561 const SDLoc &DL) {
4562 SDValue LL, LR, RL, RR, N0CC, N1CC;
4563 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
4564 !isSetCCEquivalent(N1, RL, RR, N1CC))
4565 return SDValue();
4567 assert(N0.getValueType() == N1.getValueType() &&
4568 "Unexpected operand types for bitwise logic op");
4569 assert(LL.getValueType() == LR.getValueType() &&
4570 RL.getValueType() == RR.getValueType() &&
4571 "Unexpected operand types for setcc");
4573 // If we're here post-legalization or the logic op type is not i1, the logic
4574 // op type must match a setcc result type. Also, all folds require new
4575 // operations on the left and right operands, so those types must match.
4576 EVT VT = N0.getValueType();
4577 EVT OpVT = LL.getValueType();
4578 if (LegalOperations || VT.getScalarType() != MVT::i1)
4579 if (VT != getSetCCResultType(OpVT))
4580 return SDValue();
4581 if (OpVT != RL.getValueType())
4582 return SDValue();
4584 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
4585 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
4586 bool IsInteger = OpVT.isInteger();
4587 if (LR == RR && CC0 == CC1 && IsInteger) {
4588 bool IsZero = isNullOrNullSplat(LR);
4589 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
4591 // All bits clear?
4592 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
4593 // All sign bits clear?
4594 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
4595 // Any bits set?
4596 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
4597 // Any sign bits set?
4598 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
4600 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
4601 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4602 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
4603 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
4604 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
4605 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
4606 AddToWorklist(Or.getNode());
4607 return DAG.getSetCC(DL, VT, Or, LR, CC1);
4610 // All bits set?
4611 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
4612 // All sign bits set?
4613 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
4614 // Any bits clear?
4615 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
4616 // Any sign bits clear?
4617 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
4619 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
4620 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
4621 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
4622 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
4623 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
4624 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
4625 AddToWorklist(And.getNode());
4626 return DAG.getSetCC(DL, VT, And, LR, CC1);
4630 // TODO: What is the 'or' equivalent of this fold?
4631 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
4632 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
4633 IsInteger && CC0 == ISD::SETNE &&
4634 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
4635 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
4636 SDValue One = DAG.getConstant(1, DL, OpVT);
4637 SDValue Two = DAG.getConstant(2, DL, OpVT);
4638 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
4639 AddToWorklist(Add.getNode());
4640 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
4643 // Try more general transforms if the predicates match and the only user of
4644 // the compares is the 'and' or 'or'.
4645 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
4646 N0.hasOneUse() && N1.hasOneUse()) {
4647 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
4648 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
4649 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
4650 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
4651 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
4652 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
4653 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4654 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
4657 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
4658 // TODO - support non-uniform vector amounts.
4659 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
4660 // Match a shared variable operand and 2 non-opaque constant operands.
4661 ConstantSDNode *C0 = isConstOrConstSplat(LR);
4662 ConstantSDNode *C1 = isConstOrConstSplat(RR);
4663 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
4664 // Canonicalize larger constant as C0.
4665 if (C1->getAPIntValue().ugt(C0->getAPIntValue()))
4666 std::swap(C0, C1);
4668 // The difference of the constants must be a single bit.
4669 const APInt &C0Val = C0->getAPIntValue();
4670 const APInt &C1Val = C1->getAPIntValue();
4671 if ((C0Val - C1Val).isPowerOf2()) {
4672 // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) -->
4673 // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq
4674 SDValue OffsetC = DAG.getConstant(-C1Val, DL, OpVT);
4675 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LL, OffsetC);
4676 SDValue MaskC = DAG.getConstant(~(C0Val - C1Val), DL, OpVT);
4677 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Add, MaskC);
4678 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4679 return DAG.getSetCC(DL, VT, And, Zero, CC0);
4685 // Canonicalize equivalent operands to LL == RL.
4686 if (LL == RR && LR == RL) {
4687 CC1 = ISD::getSetCCSwappedOperands(CC1);
4688 std::swap(RL, RR);
4691 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4692 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4693 if (LL == RL && LR == RR) {
4694 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
4695 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
4696 if (NewCC != ISD::SETCC_INVALID &&
4697 (!LegalOperations ||
4698 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
4699 TLI.isOperationLegal(ISD::SETCC, OpVT))))
4700 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
4703 return SDValue();
4706 /// This contains all DAGCombine rules which reduce two values combined by
4707 /// an And operation to a single value. This makes them reusable in the context
4708 /// of visitSELECT(). Rules involving constants are not included as
4709 /// visitSELECT() already handles those cases.
4710 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
4711 EVT VT = N1.getValueType();
4712 SDLoc DL(N);
4714 // fold (and x, undef) -> 0
4715 if (N0.isUndef() || N1.isUndef())
4716 return DAG.getConstant(0, DL, VT);
4718 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
4719 return V;
4721 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
4722 VT.getSizeInBits() <= 64) {
4723 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4724 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
4725 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
4726 // immediate for an add, but it is legal if its top c2 bits are set,
4727 // transform the ADD so the immediate doesn't need to be materialized
4728 // in a register.
4729 APInt ADDC = ADDI->getAPIntValue();
4730 APInt SRLC = SRLI->getAPIntValue();
4731 if (ADDC.getMinSignedBits() <= 64 &&
4732 SRLC.ult(VT.getSizeInBits()) &&
4733 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4734 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
4735 SRLC.getZExtValue());
4736 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
4737 ADDC |= Mask;
4738 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4739 SDLoc DL0(N0);
4740 SDValue NewAdd =
4741 DAG.getNode(ISD::ADD, DL0, VT,
4742 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
4743 CombineTo(N0.getNode(), NewAdd);
4744 // Return N so it doesn't get rechecked!
4745 return SDValue(N, 0);
4753 // Reduce bit extract of low half of an integer to the narrower type.
4754 // (and (srl i64:x, K), KMask) ->
4755 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
4756 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4757 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
4758 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4759 unsigned Size = VT.getSizeInBits();
4760 const APInt &AndMask = CAnd->getAPIntValue();
4761 unsigned ShiftBits = CShift->getZExtValue();
4763 // Bail out, this node will probably disappear anyway.
4764 if (ShiftBits == 0)
4765 return SDValue();
4767 unsigned MaskBits = AndMask.countTrailingOnes();
4768 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
4770 if (AndMask.isMask() &&
4771 // Required bits must not span the two halves of the integer and
4772 // must fit in the half size type.
4773 (ShiftBits + MaskBits <= Size / 2) &&
4774 TLI.isNarrowingProfitable(VT, HalfVT) &&
4775 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
4776 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
4777 TLI.isTruncateFree(VT, HalfVT) &&
4778 TLI.isZExtFree(HalfVT, VT)) {
4779 // The isNarrowingProfitable is to avoid regressions on PPC and
4780 // AArch64 which match a few 64-bit bit insert / bit extract patterns
4781 // on downstream users of this. Those patterns could probably be
4782 // extended to handle extensions mixed in.
4784 SDValue SL(N0);
4785 assert(MaskBits <= Size);
4787 // Extracting the highest bit of the low half.
4788 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
4789 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
4790 N0.getOperand(0));
4792 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
4793 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
4794 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
4795 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
4796 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
4802 return SDValue();
4805 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
4806 EVT LoadResultTy, EVT &ExtVT) {
4807 if (!AndC->getAPIntValue().isMask())
4808 return false;
4810 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
4812 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4813 EVT LoadedVT = LoadN->getMemoryVT();
4815 if (ExtVT == LoadedVT &&
4816 (!LegalOperations ||
4817 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
4818 // ZEXTLOAD will match without needing to change the size of the value being
4819 // loaded.
4820 return true;
4823 // Do not change the width of a volatile load.
4824 if (LoadN->isVolatile())
4825 return false;
4827 // Do not generate loads of non-round integer types since these can
4828 // be expensive (and would be wrong if the type is not byte sized).
4829 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
4830 return false;
4832 if (LegalOperations &&
4833 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
4834 return false;
4836 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
4837 return false;
4839 return true;
4842 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
4843 ISD::LoadExtType ExtType, EVT &MemVT,
4844 unsigned ShAmt) {
4845 if (!LDST)
4846 return false;
4847 // Only allow byte offsets.
4848 if (ShAmt % 8)
4849 return false;
4851 // Do not generate loads of non-round integer types since these can
4852 // be expensive (and would be wrong if the type is not byte sized).
4853 if (!MemVT.isRound())
4854 return false;
4856 // Don't change the width of a volatile load.
4857 if (LDST->isVolatile())
4858 return false;
4860 // Verify that we are actually reducing a load width here.
4861 if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits())
4862 return false;
4864 // Ensure that this isn't going to produce an unsupported unaligned access.
4865 if (ShAmt &&
4866 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4867 LDST->getAddressSpace(), ShAmt / 8,
4868 LDST->getMemOperand()->getFlags()))
4869 return false;
4871 // It's not possible to generate a constant of extended or untyped type.
4872 EVT PtrType = LDST->getBasePtr().getValueType();
4873 if (PtrType == MVT::Untyped || PtrType.isExtended())
4874 return false;
4876 if (isa<LoadSDNode>(LDST)) {
4877 LoadSDNode *Load = cast<LoadSDNode>(LDST);
4878 // Don't transform one with multiple uses, this would require adding a new
4879 // load.
4880 if (!SDValue(Load, 0).hasOneUse())
4881 return false;
4883 if (LegalOperations &&
4884 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
4885 return false;
4887 // For the transform to be legal, the load must produce only two values
4888 // (the value loaded and the chain). Don't transform a pre-increment
4889 // load, for example, which produces an extra value. Otherwise the
4890 // transformation is not equivalent, and the downstream logic to replace
4891 // uses gets things wrong.
4892 if (Load->getNumValues() > 2)
4893 return false;
4895 // If the load that we're shrinking is an extload and we're not just
4896 // discarding the extension we can't simply shrink the load. Bail.
4897 // TODO: It would be possible to merge the extensions in some cases.
4898 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
4899 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4900 return false;
4902 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
4903 return false;
4904 } else {
4905 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
4906 StoreSDNode *Store = cast<StoreSDNode>(LDST);
4907 // Can't write outside the original store
4908 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4909 return false;
4911 if (LegalOperations &&
4912 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
4913 return false;
4915 return true;
4918 bool DAGCombiner::SearchForAndLoads(SDNode *N,
4919 SmallVectorImpl<LoadSDNode*> &Loads,
4920 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
4921 ConstantSDNode *Mask,
4922 SDNode *&NodeToMask) {
4923 // Recursively search for the operands, looking for loads which can be
4924 // narrowed.
4925 for (SDValue Op : N->op_values()) {
4926 if (Op.getValueType().isVector())
4927 return false;
4929 // Some constants may need fixing up later if they are too large.
4930 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4931 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
4932 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
4933 NodesWithConsts.insert(N);
4934 continue;
4937 if (!Op.hasOneUse())
4938 return false;
4940 switch(Op.getOpcode()) {
4941 case ISD::LOAD: {
4942 auto *Load = cast<LoadSDNode>(Op);
4943 EVT ExtVT;
4944 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
4945 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
4947 // ZEXTLOAD is already small enough.
4948 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
4949 ExtVT.bitsGE(Load->getMemoryVT()))
4950 continue;
4952 // Use LE to convert equal sized loads to zext.
4953 if (ExtVT.bitsLE(Load->getMemoryVT()))
4954 Loads.push_back(Load);
4956 continue;
4958 return false;
4960 case ISD::ZERO_EXTEND:
4961 case ISD::AssertZext: {
4962 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
4963 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4964 EVT VT = Op.getOpcode() == ISD::AssertZext ?
4965 cast<VTSDNode>(Op.getOperand(1))->getVT() :
4966 Op.getOperand(0).getValueType();
4968 // We can accept extending nodes if the mask is wider or an equal
4969 // width to the original type.
4970 if (ExtVT.bitsGE(VT))
4971 continue;
4972 break;
4974 case ISD::OR:
4975 case ISD::XOR:
4976 case ISD::AND:
4977 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
4978 NodeToMask))
4979 return false;
4980 continue;
4983 // Allow one node which will masked along with any loads found.
4984 if (NodeToMask)
4985 return false;
4987 // Also ensure that the node to be masked only produces one data result.
4988 NodeToMask = Op.getNode();
4989 if (NodeToMask->getNumValues() > 1) {
4990 bool HasValue = false;
4991 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
4992 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
4993 if (VT != MVT::Glue && VT != MVT::Other) {
4994 if (HasValue) {
4995 NodeToMask = nullptr;
4996 return false;
4998 HasValue = true;
5001 assert(HasValue && "Node to be masked has no data result?");
5004 return true;
5007 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
5008 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
5009 if (!Mask)
5010 return false;
5012 if (!Mask->getAPIntValue().isMask())
5013 return false;
5015 // No need to do anything if the and directly uses a load.
5016 if (isa<LoadSDNode>(N->getOperand(0)))
5017 return false;
5019 SmallVector<LoadSDNode*, 8> Loads;
5020 SmallPtrSet<SDNode*, 2> NodesWithConsts;
5021 SDNode *FixupNode = nullptr;
5022 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
5023 if (Loads.size() == 0)
5024 return false;
5026 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
5027 SDValue MaskOp = N->getOperand(1);
5029 // If it exists, fixup the single node we allow in the tree that needs
5030 // masking.
5031 if (FixupNode) {
5032 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
5033 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
5034 FixupNode->getValueType(0),
5035 SDValue(FixupNode, 0), MaskOp);
5036 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
5037 if (And.getOpcode() == ISD ::AND)
5038 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
5041 // Narrow any constants that need it.
5042 for (auto *LogicN : NodesWithConsts) {
5043 SDValue Op0 = LogicN->getOperand(0);
5044 SDValue Op1 = LogicN->getOperand(1);
5046 if (isa<ConstantSDNode>(Op0))
5047 std::swap(Op0, Op1);
5049 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
5050 Op1, MaskOp);
5052 DAG.UpdateNodeOperands(LogicN, Op0, And);
5055 // Create narrow loads.
5056 for (auto *Load : Loads) {
5057 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
5058 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
5059 SDValue(Load, 0), MaskOp);
5060 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
5061 if (And.getOpcode() == ISD ::AND)
5062 And = SDValue(
5063 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
5064 SDValue NewLoad = ReduceLoadWidth(And.getNode());
5065 assert(NewLoad &&
5066 "Shouldn't be masking the load if it can't be narrowed");
5067 CombineTo(Load, NewLoad, NewLoad.getValue(1));
5069 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
5070 return true;
5072 return false;
5075 // Unfold
5076 // x & (-1 'logical shift' y)
5077 // To
5078 // (x 'opposite logical shift' y) 'logical shift' y
5079 // if it is better for performance.
5080 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
5081 assert(N->getOpcode() == ISD::AND);
5083 SDValue N0 = N->getOperand(0);
5084 SDValue N1 = N->getOperand(1);
5086 // Do we actually prefer shifts over mask?
5087 if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
5088 return SDValue();
5090 // Try to match (-1 '[outer] logical shift' y)
5091 unsigned OuterShift;
5092 unsigned InnerShift; // The opposite direction to the OuterShift.
5093 SDValue Y; // Shift amount.
5094 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
5095 if (!M.hasOneUse())
5096 return false;
5097 OuterShift = M->getOpcode();
5098 if (OuterShift == ISD::SHL)
5099 InnerShift = ISD::SRL;
5100 else if (OuterShift == ISD::SRL)
5101 InnerShift = ISD::SHL;
5102 else
5103 return false;
5104 if (!isAllOnesConstant(M->getOperand(0)))
5105 return false;
5106 Y = M->getOperand(1);
5107 return true;
5110 SDValue X;
5111 if (matchMask(N1))
5112 X = N0;
5113 else if (matchMask(N0))
5114 X = N1;
5115 else
5116 return SDValue();
5118 SDLoc DL(N);
5119 EVT VT = N->getValueType(0);
5121 // tmp = x 'opposite logical shift' y
5122 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
5123 // ret = tmp 'logical shift' y
5124 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
5126 return T1;
5129 SDValue DAGCombiner::visitAND(SDNode *N) {
5130 SDValue N0 = N->getOperand(0);
5131 SDValue N1 = N->getOperand(1);
5132 EVT VT = N1.getValueType();
5134 // x & x --> x
5135 if (N0 == N1)
5136 return N0;
5138 // fold vector ops
5139 if (VT.isVector()) {
5140 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5141 return FoldedVOp;
5143 // fold (and x, 0) -> 0, vector edition
5144 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5145 // do not return N0, because undef node may exist in N0
5146 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
5147 SDLoc(N), N0.getValueType());
5148 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5149 // do not return N1, because undef node may exist in N1
5150 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
5151 SDLoc(N), N1.getValueType());
5153 // fold (and x, -1) -> x, vector edition
5154 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5155 return N1;
5156 if (ISD::isBuildVectorAllOnes(N1.getNode()))
5157 return N0;
5160 // fold (and c1, c2) -> c1&c2
5161 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5162 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5163 if (N0C && N1C && !N1C->isOpaque())
5164 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
5165 // canonicalize constant to RHS
5166 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5167 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5168 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
5169 // fold (and x, -1) -> x
5170 if (isAllOnesConstant(N1))
5171 return N0;
5172 // if (and x, c) is known to be zero, return 0
5173 unsigned BitWidth = VT.getScalarSizeInBits();
5174 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5175 APInt::getAllOnesValue(BitWidth)))
5176 return DAG.getConstant(0, SDLoc(N), VT);
5178 if (SDValue NewSel = foldBinOpIntoSelect(N))
5179 return NewSel;
5181 // reassociate and
5182 if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
5183 return RAND;
5185 // Try to convert a constant mask AND into a shuffle clear mask.
5186 if (VT.isVector())
5187 if (SDValue Shuffle = XformToShuffleWithZero(N))
5188 return Shuffle;
5190 // fold (and (or x, C), D) -> D if (C & D) == D
5191 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
5192 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
5194 if (N0.getOpcode() == ISD::OR &&
5195 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
5196 return N1;
5197 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5198 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5199 SDValue N0Op0 = N0.getOperand(0);
5200 APInt Mask = ~N1C->getAPIntValue();
5201 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
5202 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
5203 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
5204 N0.getValueType(), N0Op0);
5206 // Replace uses of the AND with uses of the Zero extend node.
5207 CombineTo(N, Zext);
5209 // We actually want to replace all uses of the any_extend with the
5210 // zero_extend, to avoid duplicating things. This will later cause this
5211 // AND to be folded.
5212 CombineTo(N0.getNode(), Zext);
5213 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5216 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5217 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5218 // already be zero by virtue of the width of the base type of the load.
5220 // the 'X' node here can either be nothing or an extract_vector_elt to catch
5221 // more cases.
5222 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5223 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
5224 N0.getOperand(0).getOpcode() == ISD::LOAD &&
5225 N0.getOperand(0).getResNo() == 0) ||
5226 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
5227 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
5228 N0 : N0.getOperand(0) );
5230 // Get the constant (if applicable) the zero'th operand is being ANDed with.
5231 // This can be a pure constant or a vector splat, in which case we treat the
5232 // vector as a scalar and use the splat value.
5233 APInt Constant = APInt::getNullValue(1);
5234 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
5235 Constant = C->getAPIntValue();
5236 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
5237 APInt SplatValue, SplatUndef;
5238 unsigned SplatBitSize;
5239 bool HasAnyUndefs;
5240 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
5241 SplatBitSize, HasAnyUndefs);
5242 if (IsSplat) {
5243 // Undef bits can contribute to a possible optimisation if set, so
5244 // set them.
5245 SplatValue |= SplatUndef;
5247 // The splat value may be something like "0x00FFFFFF", which means 0 for
5248 // the first vector value and FF for the rest, repeating. We need a mask
5249 // that will apply equally to all members of the vector, so AND all the
5250 // lanes of the constant together.
5251 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
5253 // If the splat value has been compressed to a bitlength lower
5254 // than the size of the vector lane, we need to re-expand it to
5255 // the lane size.
5256 if (EltBitWidth > SplatBitSize)
5257 for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
5258 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
5259 SplatValue |= SplatValue.shl(SplatBitSize);
5261 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5262 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5263 if ((SplatBitSize % EltBitWidth) == 0) {
5264 Constant = APInt::getAllOnesValue(EltBitWidth);
5265 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
5266 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
5271 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
5272 // actually legal and isn't going to get expanded, else this is a false
5273 // optimisation.
5274 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
5275 Load->getValueType(0),
5276 Load->getMemoryVT());
5278 // Resize the constant to the same size as the original memory access before
5279 // extension. If it is still the AllOnesValue then this AND is completely
5280 // unneeded.
5281 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
5283 bool B;
5284 switch (Load->getExtensionType()) {
5285 default: B = false; break;
5286 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
5287 case ISD::ZEXTLOAD:
5288 case ISD::NON_EXTLOAD: B = true; break;
5291 if (B && Constant.isAllOnesValue()) {
5292 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
5293 // preserve semantics once we get rid of the AND.
5294 SDValue NewLoad(Load, 0);
5296 // Fold the AND away. NewLoad may get replaced immediately.
5297 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
5299 if (Load->getExtensionType() == ISD::EXTLOAD) {
5300 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
5301 Load->getValueType(0), SDLoc(Load),
5302 Load->getChain(), Load->getBasePtr(),
5303 Load->getOffset(), Load->getMemoryVT(),
5304 Load->getMemOperand());
5305 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
5306 if (Load->getNumValues() == 3) {
5307 // PRE/POST_INC loads have 3 values.
5308 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
5309 NewLoad.getValue(2) };
5310 CombineTo(Load, To, 3, true);
5311 } else {
5312 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
5316 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5320 // fold (and (load x), 255) -> (zextload x, i8)
5321 // fold (and (extload x, i16), 255) -> (zextload x, i8)
5322 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
5323 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
5324 (N0.getOpcode() == ISD::ANY_EXTEND &&
5325 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
5326 if (SDValue Res = ReduceLoadWidth(N)) {
5327 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
5328 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
5329 AddToWorklist(N);
5330 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res);
5331 return SDValue(N, 0);
5335 if (Level >= AfterLegalizeTypes) {
5336 // Attempt to propagate the AND back up to the leaves which, if they're
5337 // loads, can be combined to narrow loads and the AND node can be removed.
5338 // Perform after legalization so that extend nodes will already be
5339 // combined into the loads.
5340 if (BackwardsPropagateMask(N, DAG)) {
5341 return SDValue(N, 0);
5345 if (SDValue Combined = visitANDLike(N0, N1, N))
5346 return Combined;
5348 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
5349 if (N0.getOpcode() == N1.getOpcode())
5350 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5351 return V;
5353 // Masking the negated extension of a boolean is just the zero-extended
5354 // boolean:
5355 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
5356 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
5358 // Note: the SimplifyDemandedBits fold below can make an information-losing
5359 // transform, and then we have no way to find this better fold.
5360 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
5361 if (isNullOrNullSplat(N0.getOperand(0))) {
5362 SDValue SubRHS = N0.getOperand(1);
5363 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
5364 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5365 return SubRHS;
5366 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
5367 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5368 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
5372 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
5373 // fold (and (sra)) -> (and (srl)) when possible.
5374 if (SimplifyDemandedBits(SDValue(N, 0)))
5375 return SDValue(N, 0);
5377 // fold (zext_inreg (extload x)) -> (zextload x)
5378 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
5379 if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
5380 (ISD::isEXTLoad(N0.getNode()) ||
5381 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
5382 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5383 EVT MemVT = LN0->getMemoryVT();
5384 // If we zero all the possible extended bits, then we can turn this into
5385 // a zextload if we are running before legalize or the operation is legal.
5386 unsigned ExtBitSize = N1.getScalarValueSizeInBits();
5387 unsigned MemBitSize = MemVT.getScalarSizeInBits();
5388 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
5389 if (DAG.MaskedValueIsZero(N1, ExtBits) &&
5390 ((!LegalOperations && !LN0->isVolatile()) ||
5391 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
5392 SDValue ExtLoad =
5393 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
5394 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
5395 AddToWorklist(N);
5396 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5397 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5401 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
5402 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
5403 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5404 N0.getOperand(1), false))
5405 return BSwap;
5408 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
5409 return Shifts;
5411 return SDValue();
5414 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
5415 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
5416 bool DemandHighBits) {
5417 if (!LegalOperations)
5418 return SDValue();
5420 EVT VT = N->getValueType(0);
5421 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
5422 return SDValue();
5423 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
5424 return SDValue();
5426 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
5427 bool LookPassAnd0 = false;
5428 bool LookPassAnd1 = false;
5429 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
5430 std::swap(N0, N1);
5431 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
5432 std::swap(N0, N1);
5433 if (N0.getOpcode() == ISD::AND) {
5434 if (!N0.getNode()->hasOneUse())
5435 return SDValue();
5436 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5437 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
5438 // This is needed for X86.
5439 if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
5440 N01C->getZExtValue() != 0xFFFF))
5441 return SDValue();
5442 N0 = N0.getOperand(0);
5443 LookPassAnd0 = true;
5446 if (N1.getOpcode() == ISD::AND) {
5447 if (!N1.getNode()->hasOneUse())
5448 return SDValue();
5449 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5450 if (!N11C || N11C->getZExtValue() != 0xFF)
5451 return SDValue();
5452 N1 = N1.getOperand(0);
5453 LookPassAnd1 = true;
5456 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
5457 std::swap(N0, N1);
5458 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
5459 return SDValue();
5460 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
5461 return SDValue();
5463 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5464 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5465 if (!N01C || !N11C)
5466 return SDValue();
5467 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
5468 return SDValue();
5470 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
5471 SDValue N00 = N0->getOperand(0);
5472 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
5473 if (!N00.getNode()->hasOneUse())
5474 return SDValue();
5475 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
5476 if (!N001C || N001C->getZExtValue() != 0xFF)
5477 return SDValue();
5478 N00 = N00.getOperand(0);
5479 LookPassAnd0 = true;
5482 SDValue N10 = N1->getOperand(0);
5483 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
5484 if (!N10.getNode()->hasOneUse())
5485 return SDValue();
5486 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
5487 // Also allow 0xFFFF since the bits will be shifted out. This is needed
5488 // for X86.
5489 if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
5490 N101C->getZExtValue() != 0xFFFF))
5491 return SDValue();
5492 N10 = N10.getOperand(0);
5493 LookPassAnd1 = true;
5496 if (N00 != N10)
5497 return SDValue();
5499 // Make sure everything beyond the low halfword gets set to zero since the SRL
5500 // 16 will clear the top bits.
5501 unsigned OpSizeInBits = VT.getSizeInBits();
5502 if (DemandHighBits && OpSizeInBits > 16) {
5503 // If the left-shift isn't masked out then the only way this is a bswap is
5504 // if all bits beyond the low 8 are 0. In that case the entire pattern
5505 // reduces to a left shift anyway: leave it for other parts of the combiner.
5506 if (!LookPassAnd0)
5507 return SDValue();
5509 // However, if the right shift isn't masked out then it might be because
5510 // it's not needed. See if we can spot that too.
5511 if (!LookPassAnd1 &&
5512 !DAG.MaskedValueIsZero(
5513 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
5514 return SDValue();
5517 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
5518 if (OpSizeInBits > 16) {
5519 SDLoc DL(N);
5520 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
5521 DAG.getConstant(OpSizeInBits - 16, DL,
5522 getShiftAmountTy(VT)));
5524 return Res;
5527 /// Return true if the specified node is an element that makes up a 32-bit
5528 /// packed halfword byteswap.
5529 /// ((x & 0x000000ff) << 8) |
5530 /// ((x & 0x0000ff00) >> 8) |
5531 /// ((x & 0x00ff0000) << 8) |
5532 /// ((x & 0xff000000) >> 8)
5533 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
5534 if (!N.getNode()->hasOneUse())
5535 return false;
5537 unsigned Opc = N.getOpcode();
5538 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
5539 return false;
5541 SDValue N0 = N.getOperand(0);
5542 unsigned Opc0 = N0.getOpcode();
5543 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
5544 return false;
5546 ConstantSDNode *N1C = nullptr;
5547 // SHL or SRL: look upstream for AND mask operand
5548 if (Opc == ISD::AND)
5549 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5550 else if (Opc0 == ISD::AND)
5551 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5552 if (!N1C)
5553 return false;
5555 unsigned MaskByteOffset;
5556 switch (N1C->getZExtValue()) {
5557 default:
5558 return false;
5559 case 0xFF: MaskByteOffset = 0; break;
5560 case 0xFF00: MaskByteOffset = 1; break;
5561 case 0xFFFF:
5562 // In case demanded bits didn't clear the bits that will be shifted out.
5563 // This is needed for X86.
5564 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
5565 MaskByteOffset = 1;
5566 break;
5568 return false;
5569 case 0xFF0000: MaskByteOffset = 2; break;
5570 case 0xFF000000: MaskByteOffset = 3; break;
5573 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
5574 if (Opc == ISD::AND) {
5575 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
5576 // (x >> 8) & 0xff
5577 // (x >> 8) & 0xff0000
5578 if (Opc0 != ISD::SRL)
5579 return false;
5580 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5581 if (!C || C->getZExtValue() != 8)
5582 return false;
5583 } else {
5584 // (x << 8) & 0xff00
5585 // (x << 8) & 0xff000000
5586 if (Opc0 != ISD::SHL)
5587 return false;
5588 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5589 if (!C || C->getZExtValue() != 8)
5590 return false;
5592 } else if (Opc == ISD::SHL) {
5593 // (x & 0xff) << 8
5594 // (x & 0xff0000) << 8
5595 if (MaskByteOffset != 0 && MaskByteOffset != 2)
5596 return false;
5597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5598 if (!C || C->getZExtValue() != 8)
5599 return false;
5600 } else { // Opc == ISD::SRL
5601 // (x & 0xff00) >> 8
5602 // (x & 0xff000000) >> 8
5603 if (MaskByteOffset != 1 && MaskByteOffset != 3)
5604 return false;
5605 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5606 if (!C || C->getZExtValue() != 8)
5607 return false;
5610 if (Parts[MaskByteOffset])
5611 return false;
5613 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
5614 return true;
5617 /// Match a 32-bit packed halfword bswap. That is
5618 /// ((x & 0x000000ff) << 8) |
5619 /// ((x & 0x0000ff00) >> 8) |
5620 /// ((x & 0x00ff0000) << 8) |
5621 /// ((x & 0xff000000) >> 8)
5622 /// => (rotl (bswap x), 16)
5623 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
5624 if (!LegalOperations)
5625 return SDValue();
5627 EVT VT = N->getValueType(0);
5628 if (VT != MVT::i32)
5629 return SDValue();
5630 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
5631 return SDValue();
5633 // Look for either
5634 // (or (or (and), (and)), (or (and), (and)))
5635 // (or (or (or (and), (and)), (and)), (and))
5636 if (N0.getOpcode() != ISD::OR)
5637 return SDValue();
5638 SDValue N00 = N0.getOperand(0);
5639 SDValue N01 = N0.getOperand(1);
5640 SDNode *Parts[4] = {};
5642 if (N1.getOpcode() == ISD::OR &&
5643 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
5644 // (or (or (and), (and)), (or (and), (and)))
5645 if (!isBSwapHWordElement(N00, Parts))
5646 return SDValue();
5648 if (!isBSwapHWordElement(N01, Parts))
5649 return SDValue();
5650 SDValue N10 = N1.getOperand(0);
5651 if (!isBSwapHWordElement(N10, Parts))
5652 return SDValue();
5653 SDValue N11 = N1.getOperand(1);
5654 if (!isBSwapHWordElement(N11, Parts))
5655 return SDValue();
5656 } else {
5657 // (or (or (or (and), (and)), (and)), (and))
5658 if (!isBSwapHWordElement(N1, Parts))
5659 return SDValue();
5660 if (!isBSwapHWordElement(N01, Parts))
5661 return SDValue();
5662 if (N00.getOpcode() != ISD::OR)
5663 return SDValue();
5664 SDValue N000 = N00.getOperand(0);
5665 if (!isBSwapHWordElement(N000, Parts))
5666 return SDValue();
5667 SDValue N001 = N00.getOperand(1);
5668 if (!isBSwapHWordElement(N001, Parts))
5669 return SDValue();
5672 // Make sure the parts are all coming from the same node.
5673 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
5674 return SDValue();
5676 SDLoc DL(N);
5677 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
5678 SDValue(Parts[0], 0));
5680 // Result of the bswap should be rotated by 16. If it's not legal, then
5681 // do (x << 16) | (x >> 16).
5682 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
5683 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
5684 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
5685 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
5686 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
5687 return DAG.getNode(ISD::OR, DL, VT,
5688 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
5689 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
5692 /// This contains all DAGCombine rules which reduce two values combined by
5693 /// an Or operation to a single value \see visitANDLike().
5694 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
5695 EVT VT = N1.getValueType();
5696 SDLoc DL(N);
5698 // fold (or x, undef) -> -1
5699 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
5700 return DAG.getAllOnesConstant(DL, VT);
5702 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
5703 return V;
5705 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
5706 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
5707 // Don't increase # computations.
5708 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
5709 // We can only do this xform if we know that bits from X that are set in C2
5710 // but not in C1 are already zero. Likewise for Y.
5711 if (const ConstantSDNode *N0O1C =
5712 getAsNonOpaqueConstant(N0.getOperand(1))) {
5713 if (const ConstantSDNode *N1O1C =
5714 getAsNonOpaqueConstant(N1.getOperand(1))) {
5715 // We can only do this xform if we know that bits from X that are set in
5716 // C2 but not in C1 are already zero. Likewise for Y.
5717 const APInt &LHSMask = N0O1C->getAPIntValue();
5718 const APInt &RHSMask = N1O1C->getAPIntValue();
5720 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
5721 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
5722 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
5723 N0.getOperand(0), N1.getOperand(0));
5724 return DAG.getNode(ISD::AND, DL, VT, X,
5725 DAG.getConstant(LHSMask | RHSMask, DL, VT));
5731 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
5732 if (N0.getOpcode() == ISD::AND &&
5733 N1.getOpcode() == ISD::AND &&
5734 N0.getOperand(0) == N1.getOperand(0) &&
5735 // Don't increase # computations.
5736 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
5737 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
5738 N0.getOperand(1), N1.getOperand(1));
5739 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
5742 return SDValue();
5745 /// OR combines for which the commuted variant will be tried as well.
5746 static SDValue visitORCommutative(
5747 SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) {
5748 EVT VT = N0.getValueType();
5749 if (N0.getOpcode() == ISD::AND) {
5750 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
5751 if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1)
5752 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1);
5754 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
5755 if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1)
5756 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1);
5759 return SDValue();
5762 SDValue DAGCombiner::visitOR(SDNode *N) {
5763 SDValue N0 = N->getOperand(0);
5764 SDValue N1 = N->getOperand(1);
5765 EVT VT = N1.getValueType();
5767 // x | x --> x
5768 if (N0 == N1)
5769 return N0;
5771 // fold vector ops
5772 if (VT.isVector()) {
5773 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5774 return FoldedVOp;
5776 // fold (or x, 0) -> x, vector edition
5777 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5778 return N1;
5779 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5780 return N0;
5782 // fold (or x, -1) -> -1, vector edition
5783 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5784 // do not return N0, because undef node may exist in N0
5785 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
5786 if (ISD::isBuildVectorAllOnes(N1.getNode()))
5787 // do not return N1, because undef node may exist in N1
5788 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
5790 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
5791 // Do this only if the resulting shuffle is legal.
5792 if (isa<ShuffleVectorSDNode>(N0) &&
5793 isa<ShuffleVectorSDNode>(N1) &&
5794 // Avoid folding a node with illegal type.
5795 TLI.isTypeLegal(VT)) {
5796 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
5797 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
5798 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5799 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
5800 // Ensure both shuffles have a zero input.
5801 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
5802 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
5803 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
5804 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
5805 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
5806 bool CanFold = true;
5807 int NumElts = VT.getVectorNumElements();
5808 SmallVector<int, 4> Mask(NumElts);
5810 for (int i = 0; i != NumElts; ++i) {
5811 int M0 = SV0->getMaskElt(i);
5812 int M1 = SV1->getMaskElt(i);
5814 // Determine if either index is pointing to a zero vector.
5815 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
5816 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
5818 // If one element is zero and the otherside is undef, keep undef.
5819 // This also handles the case that both are undef.
5820 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
5821 Mask[i] = -1;
5822 continue;
5825 // Make sure only one of the elements is zero.
5826 if (M0Zero == M1Zero) {
5827 CanFold = false;
5828 break;
5831 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
5833 // We have a zero and non-zero element. If the non-zero came from
5834 // SV0 make the index a LHS index. If it came from SV1, make it
5835 // a RHS index. We need to mod by NumElts because we don't care
5836 // which operand it came from in the original shuffles.
5837 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
5840 if (CanFold) {
5841 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
5842 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
5844 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
5845 if (!LegalMask) {
5846 std::swap(NewLHS, NewRHS);
5847 ShuffleVectorSDNode::commuteMask(Mask);
5848 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
5851 if (LegalMask)
5852 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
5858 // fold (or c1, c2) -> c1|c2
5859 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5860 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5861 if (N0C && N1C && !N1C->isOpaque())
5862 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
5863 // canonicalize constant to RHS
5864 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5865 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5866 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
5867 // fold (or x, 0) -> x
5868 if (isNullConstant(N1))
5869 return N0;
5870 // fold (or x, -1) -> -1
5871 if (isAllOnesConstant(N1))
5872 return N1;
5874 if (SDValue NewSel = foldBinOpIntoSelect(N))
5875 return NewSel;
5877 // fold (or x, c) -> c iff (x & ~c) == 0
5878 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
5879 return N1;
5881 if (SDValue Combined = visitORLike(N0, N1, N))
5882 return Combined;
5884 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
5885 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
5886 return BSwap;
5887 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
5888 return BSwap;
5890 // reassociate or
5891 if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags()))
5892 return ROR;
5894 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
5895 // iff (c1 & c2) != 0 or c1/c2 are undef.
5896 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
5897 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
5899 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5900 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
5901 if (SDValue COR = DAG.FoldConstantArithmetic(
5902 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
5903 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
5904 AddToWorklist(IOR.getNode());
5905 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
5909 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
5910 return Combined;
5911 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
5912 return Combined;
5914 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
5915 if (N0.getOpcode() == N1.getOpcode())
5916 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5917 return V;
5919 // See if this is some rotate idiom.
5920 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
5921 return SDValue(Rot, 0);
5923 if (SDValue Load = MatchLoadCombine(N))
5924 return Load;
5926 // Simplify the operands using demanded-bits information.
5927 if (SimplifyDemandedBits(SDValue(N, 0)))
5928 return SDValue(N, 0);
5930 // If OR can be rewritten into ADD, try combines based on ADD.
5931 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
5932 DAG.haveNoCommonBitsSet(N0, N1))
5933 if (SDValue Combined = visitADDLike(N))
5934 return Combined;
5936 return SDValue();
5939 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) {
5940 if (Op.getOpcode() == ISD::AND &&
5941 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
5942 Mask = Op.getOperand(1);
5943 return Op.getOperand(0);
5945 return Op;
5948 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
5949 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift,
5950 SDValue &Mask) {
5951 Op = stripConstantMask(DAG, Op, Mask);
5952 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
5953 Shift = Op;
5954 return true;
5956 return false;
5959 /// Helper function for visitOR to extract the needed side of a rotate idiom
5960 /// from a shl/srl/mul/udiv. This is meant to handle cases where
5961 /// InstCombine merged some outside op with one of the shifts from
5962 /// the rotate pattern.
5963 /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
5964 /// Otherwise, returns an expansion of \p ExtractFrom based on the following
5965 /// patterns:
5967 /// (or (mul v c0) (shrl (mul v c1) c2)):
5968 /// expands (mul v c0) -> (shl (mul v c1) c3)
5970 /// (or (udiv v c0) (shl (udiv v c1) c2)):
5971 /// expands (udiv v c0) -> (shrl (udiv v c1) c3)
5973 /// (or (shl v c0) (shrl (shl v c1) c2)):
5974 /// expands (shl v c0) -> (shl (shl v c1) c3)
5976 /// (or (shrl v c0) (shl (shrl v c1) c2)):
5977 /// expands (shrl v c0) -> (shrl (shrl v c1) c3)
5979 /// Such that in all cases, c3+c2==bitwidth(op v c1).
5980 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift,
5981 SDValue ExtractFrom, SDValue &Mask,
5982 const SDLoc &DL) {
5983 assert(OppShift && ExtractFrom && "Empty SDValue");
5984 assert(
5985 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) &&
5986 "Existing shift must be valid as a rotate half");
5988 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
5989 // Preconditions:
5990 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
5992 // Find opcode of the needed shift to be extracted from (op0 v c0).
5993 unsigned Opcode = ISD::DELETED_NODE;
5994 bool IsMulOrDiv = false;
5995 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
5996 // opcode or its arithmetic (mul or udiv) variant.
5997 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
5998 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
5999 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
6000 return false;
6001 Opcode = NeededShift;
6002 return true;
6004 // op0 must be either the needed shift opcode or the mul/udiv equivalent
6005 // that the needed shift can be extracted from.
6006 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
6007 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
6008 return SDValue();
6010 // op0 must be the same opcode on both sides, have the same LHS argument,
6011 // and produce the same value type.
6012 SDValue OppShiftLHS = OppShift.getOperand(0);
6013 EVT ShiftedVT = OppShiftLHS.getValueType();
6014 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
6015 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
6016 ShiftedVT != ExtractFrom.getValueType())
6017 return SDValue();
6019 // Amount of the existing shift.
6020 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
6021 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
6022 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
6023 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
6024 ConstantSDNode *ExtractFromCst =
6025 isConstOrConstSplat(ExtractFrom.getOperand(1));
6026 // TODO: We should be able to handle non-uniform constant vectors for these values
6027 // Check that we have constant values.
6028 if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
6029 !OppLHSCst || !OppLHSCst->getAPIntValue() ||
6030 !ExtractFromCst || !ExtractFromCst->getAPIntValue())
6031 return SDValue();
6033 // Compute the shift amount we need to extract to complete the rotate.
6034 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
6035 if (OppShiftCst->getAPIntValue().ugt(VTWidth))
6036 return SDValue();
6037 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
6038 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
6039 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
6040 APInt OppLHSAmt = OppLHSCst->getAPIntValue();
6041 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
6043 // Now try extract the needed shift from the ExtractFrom op and see if the
6044 // result matches up with the existing shift's LHS op.
6045 if (IsMulOrDiv) {
6046 // Op to extract from is a mul or udiv by a constant.
6047 // Check:
6048 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
6049 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
6050 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
6051 NeededShiftAmt.getZExtValue());
6052 APInt ResultAmt;
6053 APInt Rem;
6054 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
6055 if (Rem != 0 || ResultAmt != OppLHSAmt)
6056 return SDValue();
6057 } else {
6058 // Op to extract from is a shift by a constant.
6059 // Check:
6060 // c2 - (bitwidth(op0 v c0) - c1) == c0
6061 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
6062 ExtractFromAmt.getBitWidth()))
6063 return SDValue();
6066 // Return the expanded shift op that should allow a rotate to be formed.
6067 EVT ShiftVT = OppShift.getOperand(1).getValueType();
6068 EVT ResVT = ExtractFrom.getValueType();
6069 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
6070 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
6073 // Return true if we can prove that, whenever Neg and Pos are both in the
6074 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
6075 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
6077 // (or (shift1 X, Neg), (shift2 X, Pos))
6079 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
6080 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
6081 // to consider shift amounts with defined behavior.
6082 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
6083 SelectionDAG &DAG) {
6084 // If EltSize is a power of 2 then:
6086 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
6087 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
6089 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
6090 // for the stronger condition:
6092 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
6094 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
6095 // we can just replace Neg with Neg' for the rest of the function.
6097 // In other cases we check for the even stronger condition:
6099 // Neg == EltSize - Pos [B]
6101 // for all Neg and Pos. Note that the (or ...) then invokes undefined
6102 // behavior if Pos == 0 (and consequently Neg == EltSize).
6104 // We could actually use [A] whenever EltSize is a power of 2, but the
6105 // only extra cases that it would match are those uninteresting ones
6106 // where Neg and Pos are never in range at the same time. E.g. for
6107 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
6108 // as well as (sub 32, Pos), but:
6110 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
6112 // always invokes undefined behavior for 32-bit X.
6114 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
6115 unsigned MaskLoBits = 0;
6116 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
6117 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
6118 KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0));
6119 unsigned Bits = Log2_64(EltSize);
6120 if (NegC->getAPIntValue().getActiveBits() <= Bits &&
6121 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) {
6122 Neg = Neg.getOperand(0);
6123 MaskLoBits = Bits;
6128 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
6129 if (Neg.getOpcode() != ISD::SUB)
6130 return false;
6131 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
6132 if (!NegC)
6133 return false;
6134 SDValue NegOp1 = Neg.getOperand(1);
6136 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
6137 // Pos'. The truncation is redundant for the purpose of the equality.
6138 if (MaskLoBits && Pos.getOpcode() == ISD::AND) {
6139 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) {
6140 KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0));
6141 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
6142 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >=
6143 MaskLoBits))
6144 Pos = Pos.getOperand(0);
6148 // The condition we need is now:
6150 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
6152 // If NegOp1 == Pos then we need:
6154 // EltSize & Mask == NegC & Mask
6156 // (because "x & Mask" is a truncation and distributes through subtraction).
6157 APInt Width;
6158 if (Pos == NegOp1)
6159 Width = NegC->getAPIntValue();
6161 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
6162 // Then the condition we want to prove becomes:
6164 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
6166 // which, again because "x & Mask" is a truncation, becomes:
6168 // NegC & Mask == (EltSize - PosC) & Mask
6169 // EltSize & Mask == (NegC + PosC) & Mask
6170 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
6171 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
6172 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
6173 else
6174 return false;
6175 } else
6176 return false;
6178 // Now we just need to check that EltSize & Mask == Width & Mask.
6179 if (MaskLoBits)
6180 // EltSize & Mask is 0 since Mask is EltSize - 1.
6181 return Width.getLoBits(MaskLoBits) == 0;
6182 return Width == EltSize;
6185 // A subroutine of MatchRotate used once we have found an OR of two opposite
6186 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
6187 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
6188 // former being preferred if supported. InnerPos and InnerNeg are Pos and
6189 // Neg with outer conversions stripped away.
6190 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
6191 SDValue Neg, SDValue InnerPos,
6192 SDValue InnerNeg, unsigned PosOpcode,
6193 unsigned NegOpcode, const SDLoc &DL) {
6194 // fold (or (shl x, (*ext y)),
6195 // (srl x, (*ext (sub 32, y)))) ->
6196 // (rotl x, y) or (rotr x, (sub 32, y))
6198 // fold (or (shl x, (*ext (sub 32, y))),
6199 // (srl x, (*ext y))) ->
6200 // (rotr x, y) or (rotl x, (sub 32, y))
6201 EVT VT = Shifted.getValueType();
6202 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) {
6203 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
6204 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
6205 HasPos ? Pos : Neg).getNode();
6208 return nullptr;
6211 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
6212 // idioms for rotate, and if the target supports rotation instructions, generate
6213 // a rot[lr].
6214 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
6215 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
6216 EVT VT = LHS.getValueType();
6217 if (!TLI.isTypeLegal(VT)) return nullptr;
6219 // The target must have at least one rotate flavor.
6220 bool HasROTL = hasOperation(ISD::ROTL, VT);
6221 bool HasROTR = hasOperation(ISD::ROTR, VT);
6222 if (!HasROTL && !HasROTR) return nullptr;
6224 // Check for truncated rotate.
6225 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
6226 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
6227 assert(LHS.getValueType() == RHS.getValueType());
6228 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
6229 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
6230 SDValue(Rot, 0)).getNode();
6234 // Match "(X shl/srl V1) & V2" where V2 may not be present.
6235 SDValue LHSShift; // The shift.
6236 SDValue LHSMask; // AND value if any.
6237 matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
6239 SDValue RHSShift; // The shift.
6240 SDValue RHSMask; // AND value if any.
6241 matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
6243 // If neither side matched a rotate half, bail
6244 if (!LHSShift && !RHSShift)
6245 return nullptr;
6247 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
6248 // side of the rotate, so try to handle that here. In all cases we need to
6249 // pass the matched shift from the opposite side to compute the opcode and
6250 // needed shift amount to extract. We still want to do this if both sides
6251 // matched a rotate half because one half may be a potential overshift that
6252 // can be broken down (ie if InstCombine merged two shl or srl ops into a
6253 // single one).
6255 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
6256 if (LHSShift)
6257 if (SDValue NewRHSShift =
6258 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
6259 RHSShift = NewRHSShift;
6260 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
6261 if (RHSShift)
6262 if (SDValue NewLHSShift =
6263 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
6264 LHSShift = NewLHSShift;
6266 // If a side is still missing, nothing else we can do.
6267 if (!RHSShift || !LHSShift)
6268 return nullptr;
6270 // At this point we've matched or extracted a shift op on each side.
6272 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
6273 return nullptr; // Not shifting the same value.
6275 if (LHSShift.getOpcode() == RHSShift.getOpcode())
6276 return nullptr; // Shifts must disagree.
6278 // Canonicalize shl to left side in a shl/srl pair.
6279 if (RHSShift.getOpcode() == ISD::SHL) {
6280 std::swap(LHS, RHS);
6281 std::swap(LHSShift, RHSShift);
6282 std::swap(LHSMask, RHSMask);
6285 unsigned EltSizeInBits = VT.getScalarSizeInBits();
6286 SDValue LHSShiftArg = LHSShift.getOperand(0);
6287 SDValue LHSShiftAmt = LHSShift.getOperand(1);
6288 SDValue RHSShiftArg = RHSShift.getOperand(0);
6289 SDValue RHSShiftAmt = RHSShift.getOperand(1);
6291 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
6292 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
6293 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
6294 ConstantSDNode *RHS) {
6295 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
6297 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
6298 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
6299 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
6301 // If there is an AND of either shifted operand, apply it to the result.
6302 if (LHSMask.getNode() || RHSMask.getNode()) {
6303 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
6304 SDValue Mask = AllOnes;
6306 if (LHSMask.getNode()) {
6307 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
6308 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
6309 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
6311 if (RHSMask.getNode()) {
6312 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
6313 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
6314 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
6317 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
6320 return Rot.getNode();
6323 // If there is a mask here, and we have a variable shift, we can't be sure
6324 // that we're masking out the right stuff.
6325 if (LHSMask.getNode() || RHSMask.getNode())
6326 return nullptr;
6328 // If the shift amount is sign/zext/any-extended just peel it off.
6329 SDValue LExtOp0 = LHSShiftAmt;
6330 SDValue RExtOp0 = RHSShiftAmt;
6331 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
6332 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
6333 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
6334 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
6335 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
6336 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
6337 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
6338 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
6339 LExtOp0 = LHSShiftAmt.getOperand(0);
6340 RExtOp0 = RHSShiftAmt.getOperand(0);
6343 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
6344 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
6345 if (TryL)
6346 return TryL;
6348 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
6349 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
6350 if (TryR)
6351 return TryR;
6353 return nullptr;
6356 namespace {
6358 /// Represents known origin of an individual byte in load combine pattern. The
6359 /// value of the byte is either constant zero or comes from memory.
6360 struct ByteProvider {
6361 // For constant zero providers Load is set to nullptr. For memory providers
6362 // Load represents the node which loads the byte from memory.
6363 // ByteOffset is the offset of the byte in the value produced by the load.
6364 LoadSDNode *Load = nullptr;
6365 unsigned ByteOffset = 0;
6367 ByteProvider() = default;
6369 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
6370 return ByteProvider(Load, ByteOffset);
6373 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
6375 bool isConstantZero() const { return !Load; }
6376 bool isMemory() const { return Load; }
6378 bool operator==(const ByteProvider &Other) const {
6379 return Other.Load == Load && Other.ByteOffset == ByteOffset;
6382 private:
6383 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
6384 : Load(Load), ByteOffset(ByteOffset) {}
6387 } // end anonymous namespace
6389 /// Recursively traverses the expression calculating the origin of the requested
6390 /// byte of the given value. Returns None if the provider can't be calculated.
6392 /// For all the values except the root of the expression verifies that the value
6393 /// has exactly one use and if it's not true return None. This way if the origin
6394 /// of the byte is returned it's guaranteed that the values which contribute to
6395 /// the byte are not used outside of this expression.
6397 /// Because the parts of the expression are not allowed to have more than one
6398 /// use this function iterates over trees, not DAGs. So it never visits the same
6399 /// node more than once.
6400 static const Optional<ByteProvider>
6401 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
6402 bool Root = false) {
6403 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
6404 if (Depth == 10)
6405 return None;
6407 if (!Root && !Op.hasOneUse())
6408 return None;
6410 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
6411 unsigned BitWidth = Op.getValueSizeInBits();
6412 if (BitWidth % 8 != 0)
6413 return None;
6414 unsigned ByteWidth = BitWidth / 8;
6415 assert(Index < ByteWidth && "invalid index requested");
6416 (void) ByteWidth;
6418 switch (Op.getOpcode()) {
6419 case ISD::OR: {
6420 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
6421 if (!LHS)
6422 return None;
6423 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
6424 if (!RHS)
6425 return None;
6427 if (LHS->isConstantZero())
6428 return RHS;
6429 if (RHS->isConstantZero())
6430 return LHS;
6431 return None;
6433 case ISD::SHL: {
6434 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
6435 if (!ShiftOp)
6436 return None;
6438 uint64_t BitShift = ShiftOp->getZExtValue();
6439 if (BitShift % 8 != 0)
6440 return None;
6441 uint64_t ByteShift = BitShift / 8;
6443 return Index < ByteShift
6444 ? ByteProvider::getConstantZero()
6445 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
6446 Depth + 1);
6448 case ISD::ANY_EXTEND:
6449 case ISD::SIGN_EXTEND:
6450 case ISD::ZERO_EXTEND: {
6451 SDValue NarrowOp = Op->getOperand(0);
6452 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
6453 if (NarrowBitWidth % 8 != 0)
6454 return None;
6455 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6457 if (Index >= NarrowByteWidth)
6458 return Op.getOpcode() == ISD::ZERO_EXTEND
6459 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
6460 : None;
6461 return calculateByteProvider(NarrowOp, Index, Depth + 1);
6463 case ISD::BSWAP:
6464 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
6465 Depth + 1);
6466 case ISD::LOAD: {
6467 auto L = cast<LoadSDNode>(Op.getNode());
6468 if (L->isVolatile() || L->isIndexed())
6469 return None;
6471 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
6472 if (NarrowBitWidth % 8 != 0)
6473 return None;
6474 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6476 if (Index >= NarrowByteWidth)
6477 return L->getExtensionType() == ISD::ZEXTLOAD
6478 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
6479 : None;
6480 return ByteProvider::getMemory(L, Index);
6484 return None;
6487 static unsigned LittleEndianByteAt(unsigned BW, unsigned i) {
6488 return i;
6491 static unsigned BigEndianByteAt(unsigned BW, unsigned i) {
6492 return BW - i - 1;
6495 // Check if the bytes offsets we are looking at match with either big or
6496 // little endian value loaded. Return true for big endian, false for little
6497 // endian, and None if match failed.
6498 static Optional<bool> isBigEndian(const SmallVector<int64_t, 4> &ByteOffsets,
6499 int64_t FirstOffset) {
6500 // The endian can be decided only when it is 2 bytes at least.
6501 unsigned Width = ByteOffsets.size();
6502 if (Width < 2)
6503 return None;
6505 bool BigEndian = true, LittleEndian = true;
6506 for (unsigned i = 0; i < Width; i++) {
6507 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
6508 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(Width, i);
6509 BigEndian &= CurrentByteOffset == BigEndianByteAt(Width, i);
6510 if (!BigEndian && !LittleEndian)
6511 return None;
6514 assert((BigEndian != LittleEndian) && "It should be either big endian or"
6515 "little endian");
6516 return BigEndian;
6519 static SDValue stripTruncAndExt(SDValue Value) {
6520 switch (Value.getOpcode()) {
6521 case ISD::TRUNCATE:
6522 case ISD::ZERO_EXTEND:
6523 case ISD::SIGN_EXTEND:
6524 case ISD::ANY_EXTEND:
6525 return stripTruncAndExt(Value.getOperand(0));
6527 return Value;
6530 /// Match a pattern where a wide type scalar value is stored by several narrow
6531 /// stores. Fold it into a single store or a BSWAP and a store if the targets
6532 /// supports it.
6534 /// Assuming little endian target:
6535 /// i8 *p = ...
6536 /// i32 val = ...
6537 /// p[0] = (val >> 0) & 0xFF;
6538 /// p[1] = (val >> 8) & 0xFF;
6539 /// p[2] = (val >> 16) & 0xFF;
6540 /// p[3] = (val >> 24) & 0xFF;
6541 /// =>
6542 /// *((i32)p) = val;
6544 /// i8 *p = ...
6545 /// i32 val = ...
6546 /// p[0] = (val >> 24) & 0xFF;
6547 /// p[1] = (val >> 16) & 0xFF;
6548 /// p[2] = (val >> 8) & 0xFF;
6549 /// p[3] = (val >> 0) & 0xFF;
6550 /// =>
6551 /// *((i32)p) = BSWAP(val);
6552 SDValue DAGCombiner::MatchStoreCombine(StoreSDNode *N) {
6553 // Collect all the stores in the chain.
6554 SDValue Chain;
6555 SmallVector<StoreSDNode *, 8> Stores;
6556 for (StoreSDNode *Store = N; Store; Store = dyn_cast<StoreSDNode>(Chain)) {
6557 if (Store->getMemoryVT() != MVT::i8 ||
6558 Store->isVolatile() || Store->isIndexed())
6559 return SDValue();
6560 Stores.push_back(Store);
6561 Chain = Store->getChain();
6563 // Handle the simple type only.
6564 unsigned Width = Stores.size();
6565 EVT VT = EVT::getIntegerVT(
6566 *DAG.getContext(), Width * N->getMemoryVT().getSizeInBits());
6567 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6568 return SDValue();
6570 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6571 if (LegalOperations && !TLI.isOperationLegal(ISD::STORE, VT))
6572 return SDValue();
6574 // Check if all the bytes of the combined value we are looking at are stored
6575 // to the same base address. Collect bytes offsets from Base address into
6576 // ByteOffsets.
6577 SDValue CombinedValue;
6578 SmallVector<int64_t, 4> ByteOffsets(Width, INT64_MAX);
6579 int64_t FirstOffset = INT64_MAX;
6580 StoreSDNode *FirstStore = nullptr;
6581 Optional<BaseIndexOffset> Base;
6582 for (auto Store : Stores) {
6583 // All the stores store different byte of the CombinedValue. A truncate is
6584 // required to get that byte value.
6585 SDValue Trunc = Store->getValue();
6586 if (Trunc.getOpcode() != ISD::TRUNCATE)
6587 return SDValue();
6588 // A shift operation is required to get the right byte offset, except the
6589 // first byte.
6590 int64_t Offset = 0;
6591 SDValue Value = Trunc.getOperand(0);
6592 if (Value.getOpcode() == ISD::SRL ||
6593 Value.getOpcode() == ISD::SRA) {
6594 ConstantSDNode *ShiftOffset =
6595 dyn_cast<ConstantSDNode>(Value.getOperand(1));
6596 // Trying to match the following pattern. The shift offset must be
6597 // a constant and a multiple of 8. It is the byte offset in "y".
6599 // x = srl y, offset
6600 // i8 z = trunc x
6601 // store z, ...
6602 if (!ShiftOffset || (ShiftOffset->getSExtValue() % 8))
6603 return SDValue();
6605 Offset = ShiftOffset->getSExtValue()/8;
6606 Value = Value.getOperand(0);
6609 // Stores must share the same combined value with different offsets.
6610 if (!CombinedValue)
6611 CombinedValue = Value;
6612 else if (stripTruncAndExt(CombinedValue) != stripTruncAndExt(Value))
6613 return SDValue();
6615 // The trunc and all the extend operation should be stripped to get the
6616 // real value we are stored.
6617 else if (CombinedValue.getValueType() != VT) {
6618 if (Value.getValueType() == VT ||
6619 Value.getValueSizeInBits() > CombinedValue.getValueSizeInBits())
6620 CombinedValue = Value;
6621 // Give up if the combined value type is smaller than the store size.
6622 if (CombinedValue.getValueSizeInBits() < VT.getSizeInBits())
6623 return SDValue();
6626 // Stores must share the same base address
6627 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
6628 int64_t ByteOffsetFromBase = 0;
6629 if (!Base)
6630 Base = Ptr;
6631 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
6632 return SDValue();
6634 // Remember the first byte store
6635 if (ByteOffsetFromBase < FirstOffset) {
6636 FirstStore = Store;
6637 FirstOffset = ByteOffsetFromBase;
6639 // Map the offset in the store and the offset in the combined value, and
6640 // early return if it has been set before.
6641 if (Offset < 0 || Offset >= Width || ByteOffsets[Offset] != INT64_MAX)
6642 return SDValue();
6643 ByteOffsets[Offset] = ByteOffsetFromBase;
6646 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
6647 assert(FirstStore && "First store must be set");
6649 // Check if the bytes of the combined value we are looking at match with
6650 // either big or little endian value store.
6651 Optional<bool> IsBigEndian = isBigEndian(ByteOffsets, FirstOffset);
6652 if (!IsBigEndian.hasValue())
6653 return SDValue();
6655 // The node we are looking at matches with the pattern, check if we can
6656 // replace it with a single bswap if needed and store.
6658 // If the store needs byte swap check if the target supports it
6659 bool NeedsBswap = DAG.getDataLayout().isBigEndian() != *IsBigEndian;
6661 // Before legalize we can introduce illegal bswaps which will be later
6662 // converted to an explicit bswap sequence. This way we end up with a single
6663 // store and byte shuffling instead of several stores and byte shuffling.
6664 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
6665 return SDValue();
6667 // Check that a store of the wide type is both allowed and fast on the target
6668 bool Fast = false;
6669 bool Allowed =
6670 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
6671 *FirstStore->getMemOperand(), &Fast);
6672 if (!Allowed || !Fast)
6673 return SDValue();
6675 if (VT != CombinedValue.getValueType()) {
6676 assert(CombinedValue.getValueType().getSizeInBits() > VT.getSizeInBits() &&
6677 "Get unexpected store value to combine");
6678 CombinedValue = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
6679 CombinedValue);
6682 if (NeedsBswap)
6683 CombinedValue = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, CombinedValue);
6685 SDValue NewStore =
6686 DAG.getStore(Chain, SDLoc(N), CombinedValue, FirstStore->getBasePtr(),
6687 FirstStore->getPointerInfo(), FirstStore->getAlignment());
6689 // Rely on other DAG combine rules to remove the other individual stores.
6690 DAG.ReplaceAllUsesWith(N, NewStore.getNode());
6691 return NewStore;
6694 /// Match a pattern where a wide type scalar value is loaded by several narrow
6695 /// loads and combined by shifts and ors. Fold it into a single load or a load
6696 /// and a BSWAP if the targets supports it.
6698 /// Assuming little endian target:
6699 /// i8 *a = ...
6700 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
6701 /// =>
6702 /// i32 val = *((i32)a)
6704 /// i8 *a = ...
6705 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
6706 /// =>
6707 /// i32 val = BSWAP(*((i32)a))
6709 /// TODO: This rule matches complex patterns with OR node roots and doesn't
6710 /// interact well with the worklist mechanism. When a part of the pattern is
6711 /// updated (e.g. one of the loads) its direct users are put into the worklist,
6712 /// but the root node of the pattern which triggers the load combine is not
6713 /// necessarily a direct user of the changed node. For example, once the address
6714 /// of t28 load is reassociated load combine won't be triggered:
6715 /// t25: i32 = add t4, Constant:i32<2>
6716 /// t26: i64 = sign_extend t25
6717 /// t27: i64 = add t2, t26
6718 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
6719 /// t29: i32 = zero_extend t28
6720 /// t32: i32 = shl t29, Constant:i8<8>
6721 /// t33: i32 = or t23, t32
6722 /// As a possible fix visitLoad can check if the load can be a part of a load
6723 /// combine pattern and add corresponding OR roots to the worklist.
6724 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
6725 assert(N->getOpcode() == ISD::OR &&
6726 "Can only match load combining against OR nodes");
6728 // Handles simple types only
6729 EVT VT = N->getValueType(0);
6730 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6731 return SDValue();
6732 unsigned ByteWidth = VT.getSizeInBits() / 8;
6734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6735 // Before legalize we can introduce too wide illegal loads which will be later
6736 // split into legal sized loads. This enables us to combine i64 load by i8
6737 // patterns to a couple of i32 loads on 32 bit targets.
6738 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
6739 return SDValue();
6741 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
6742 auto MemoryByteOffset = [&] (ByteProvider P) {
6743 assert(P.isMemory() && "Must be a memory byte provider");
6744 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
6745 assert(LoadBitWidth % 8 == 0 &&
6746 "can only analyze providers for individual bytes not bit");
6747 unsigned LoadByteWidth = LoadBitWidth / 8;
6748 return IsBigEndianTarget
6749 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
6750 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
6753 Optional<BaseIndexOffset> Base;
6754 SDValue Chain;
6756 SmallPtrSet<LoadSDNode *, 8> Loads;
6757 Optional<ByteProvider> FirstByteProvider;
6758 int64_t FirstOffset = INT64_MAX;
6760 // Check if all the bytes of the OR we are looking at are loaded from the same
6761 // base address. Collect bytes offsets from Base address in ByteOffsets.
6762 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
6763 for (unsigned i = 0; i < ByteWidth; i++) {
6764 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
6765 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
6766 return SDValue();
6768 LoadSDNode *L = P->Load;
6769 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
6770 "Must be enforced by calculateByteProvider");
6771 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
6773 // All loads must share the same chain
6774 SDValue LChain = L->getChain();
6775 if (!Chain)
6776 Chain = LChain;
6777 else if (Chain != LChain)
6778 return SDValue();
6780 // Loads must share the same base address
6781 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
6782 int64_t ByteOffsetFromBase = 0;
6783 if (!Base)
6784 Base = Ptr;
6785 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
6786 return SDValue();
6788 // Calculate the offset of the current byte from the base address
6789 ByteOffsetFromBase += MemoryByteOffset(*P);
6790 ByteOffsets[i] = ByteOffsetFromBase;
6792 // Remember the first byte load
6793 if (ByteOffsetFromBase < FirstOffset) {
6794 FirstByteProvider = P;
6795 FirstOffset = ByteOffsetFromBase;
6798 Loads.insert(L);
6800 assert(!Loads.empty() && "All the bytes of the value must be loaded from "
6801 "memory, so there must be at least one load which produces the value");
6802 assert(Base && "Base address of the accessed memory location must be set");
6803 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
6805 // Check if the bytes of the OR we are looking at match with either big or
6806 // little endian value load
6807 Optional<bool> IsBigEndian = isBigEndian(ByteOffsets, FirstOffset);
6808 if (!IsBigEndian.hasValue())
6809 return SDValue();
6811 assert(FirstByteProvider && "must be set");
6813 // Ensure that the first byte is loaded from zero offset of the first load.
6814 // So the combined value can be loaded from the first load address.
6815 if (MemoryByteOffset(*FirstByteProvider) != 0)
6816 return SDValue();
6817 LoadSDNode *FirstLoad = FirstByteProvider->Load;
6819 // The node we are looking at matches with the pattern, check if we can
6820 // replace it with a single load and bswap if needed.
6822 // If the load needs byte swap check if the target supports it
6823 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
6825 // Before legalize we can introduce illegal bswaps which will be later
6826 // converted to an explicit bswap sequence. This way we end up with a single
6827 // load and byte shuffling instead of several loads and byte shuffling.
6828 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
6829 return SDValue();
6831 // Check that a load of the wide type is both allowed and fast on the target
6832 bool Fast = false;
6833 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
6834 VT, *FirstLoad->getMemOperand(), &Fast);
6835 if (!Allowed || !Fast)
6836 return SDValue();
6838 SDValue NewLoad =
6839 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
6840 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
6842 // Transfer chain users from old loads to the new load.
6843 for (LoadSDNode *L : Loads)
6844 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
6846 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
6849 // If the target has andn, bsl, or a similar bit-select instruction,
6850 // we want to unfold masked merge, with canonical pattern of:
6851 // | A | |B|
6852 // ((x ^ y) & m) ^ y
6853 // | D |
6854 // Into:
6855 // (x & m) | (y & ~m)
6856 // If y is a constant, and the 'andn' does not work with immediates,
6857 // we unfold into a different pattern:
6858 // ~(~x & m) & (m | y)
6859 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
6860 // the very least that breaks andnpd / andnps patterns, and because those
6861 // patterns are simplified in IR and shouldn't be created in the DAG
6862 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
6863 assert(N->getOpcode() == ISD::XOR);
6865 // Don't touch 'not' (i.e. where y = -1).
6866 if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
6867 return SDValue();
6869 EVT VT = N->getValueType(0);
6871 // There are 3 commutable operators in the pattern,
6872 // so we have to deal with 8 possible variants of the basic pattern.
6873 SDValue X, Y, M;
6874 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
6875 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
6876 return false;
6877 SDValue Xor = And.getOperand(XorIdx);
6878 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
6879 return false;
6880 SDValue Xor0 = Xor.getOperand(0);
6881 SDValue Xor1 = Xor.getOperand(1);
6882 // Don't touch 'not' (i.e. where y = -1).
6883 if (isAllOnesOrAllOnesSplat(Xor1))
6884 return false;
6885 if (Other == Xor0)
6886 std::swap(Xor0, Xor1);
6887 if (Other != Xor1)
6888 return false;
6889 X = Xor0;
6890 Y = Xor1;
6891 M = And.getOperand(XorIdx ? 0 : 1);
6892 return true;
6895 SDValue N0 = N->getOperand(0);
6896 SDValue N1 = N->getOperand(1);
6897 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
6898 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
6899 return SDValue();
6901 // Don't do anything if the mask is constant. This should not be reachable.
6902 // InstCombine should have already unfolded this pattern, and DAGCombiner
6903 // probably shouldn't produce it, too.
6904 if (isa<ConstantSDNode>(M.getNode()))
6905 return SDValue();
6907 // We can transform if the target has AndNot
6908 if (!TLI.hasAndNot(M))
6909 return SDValue();
6911 SDLoc DL(N);
6913 // If Y is a constant, check that 'andn' works with immediates.
6914 if (!TLI.hasAndNot(Y)) {
6915 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
6916 // If not, we need to do a bit more work to make sure andn is still used.
6917 SDValue NotX = DAG.getNOT(DL, X, VT);
6918 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
6919 SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
6920 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
6921 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
6924 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
6925 SDValue NotM = DAG.getNOT(DL, M, VT);
6926 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
6928 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
6931 SDValue DAGCombiner::visitXOR(SDNode *N) {
6932 SDValue N0 = N->getOperand(0);
6933 SDValue N1 = N->getOperand(1);
6934 EVT VT = N0.getValueType();
6936 // fold vector ops
6937 if (VT.isVector()) {
6938 if (SDValue FoldedVOp = SimplifyVBinOp(N))
6939 return FoldedVOp;
6941 // fold (xor x, 0) -> x, vector edition
6942 if (ISD::isBuildVectorAllZeros(N0.getNode()))
6943 return N1;
6944 if (ISD::isBuildVectorAllZeros(N1.getNode()))
6945 return N0;
6948 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
6949 SDLoc DL(N);
6950 if (N0.isUndef() && N1.isUndef())
6951 return DAG.getConstant(0, DL, VT);
6952 // fold (xor x, undef) -> undef
6953 if (N0.isUndef())
6954 return N0;
6955 if (N1.isUndef())
6956 return N1;
6957 // fold (xor c1, c2) -> c1^c2
6958 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6959 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
6960 if (N0C && N1C)
6961 return DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, N0C, N1C);
6962 // canonicalize constant to RHS
6963 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
6964 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
6965 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
6966 // fold (xor x, 0) -> x
6967 if (isNullConstant(N1))
6968 return N0;
6970 if (SDValue NewSel = foldBinOpIntoSelect(N))
6971 return NewSel;
6973 // reassociate xor
6974 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
6975 return RXOR;
6977 // fold !(x cc y) -> (x !cc y)
6978 unsigned N0Opcode = N0.getOpcode();
6979 SDValue LHS, RHS, CC;
6980 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
6981 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
6982 LHS.getValueType().isInteger());
6983 if (!LegalOperations ||
6984 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
6985 switch (N0Opcode) {
6986 default:
6987 llvm_unreachable("Unhandled SetCC Equivalent!");
6988 case ISD::SETCC:
6989 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
6990 case ISD::SELECT_CC:
6991 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
6992 N0.getOperand(3), NotCC);
6997 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
6998 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
6999 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
7000 SDValue V = N0.getOperand(0);
7001 SDLoc DL0(N0);
7002 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
7003 DAG.getConstant(1, DL0, V.getValueType()));
7004 AddToWorklist(V.getNode());
7005 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
7008 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
7009 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
7010 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
7011 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7012 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
7013 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
7014 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
7015 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
7016 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
7017 return DAG.getNode(NewOpcode, DL, VT, LHS, RHS);
7020 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
7021 if (isAllOnesConstant(N1) && N0.hasOneUse() &&
7022 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
7023 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7024 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
7025 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
7026 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
7027 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
7028 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
7029 return DAG.getNode(NewOpcode, DL, VT, LHS, RHS);
7033 // fold (not (neg x)) -> (add X, -1)
7034 // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
7035 // Y is a constant or the subtract has a single use.
7036 if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB &&
7037 isNullConstant(N0.getOperand(0))) {
7038 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
7039 DAG.getAllOnesConstant(DL, VT));
7042 // fold (xor (and x, y), y) -> (and (not x), y)
7043 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
7044 SDValue X = N0.getOperand(0);
7045 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
7046 AddToWorklist(NotX.getNode());
7047 return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
7050 if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) {
7051 ConstantSDNode *XorC = isConstOrConstSplat(N1);
7052 ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1));
7053 unsigned BitWidth = VT.getScalarSizeInBits();
7054 if (XorC && ShiftC) {
7055 // Don't crash on an oversized shift. We can not guarantee that a bogus
7056 // shift has been simplified to undef.
7057 uint64_t ShiftAmt = ShiftC->getLimitedValue();
7058 if (ShiftAmt < BitWidth) {
7059 APInt Ones = APInt::getAllOnesValue(BitWidth);
7060 Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt);
7061 if (XorC->getAPIntValue() == Ones) {
7062 // If the xor constant is a shifted -1, do a 'not' before the shift:
7063 // xor (X << ShiftC), XorC --> (not X) << ShiftC
7064 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
7065 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
7066 return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1));
7072 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
7073 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
7074 SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
7075 SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
7076 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
7077 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
7078 SDValue S0 = S.getOperand(0);
7079 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) {
7080 unsigned OpSizeInBits = VT.getScalarSizeInBits();
7081 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
7082 if (C->getAPIntValue() == (OpSizeInBits - 1))
7083 return DAG.getNode(ISD::ABS, DL, VT, S0);
7088 // fold (xor x, x) -> 0
7089 if (N0 == N1)
7090 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
7092 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
7093 // Here is a concrete example of this equivalence:
7094 // i16 x == 14
7095 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
7096 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
7098 // =>
7100 // i16 ~1 == 0b1111111111111110
7101 // i16 rol(~1, 14) == 0b1011111111111111
7103 // Some additional tips to help conceptualize this transform:
7104 // - Try to see the operation as placing a single zero in a value of all ones.
7105 // - There exists no value for x which would allow the result to contain zero.
7106 // - Values of x larger than the bitwidth are undefined and do not require a
7107 // consistent result.
7108 // - Pushing the zero left requires shifting one bits in from the right.
7109 // A rotate left of ~1 is a nice way of achieving the desired result.
7110 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
7111 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
7112 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
7113 N0.getOperand(1));
7116 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
7117 if (N0Opcode == N1.getOpcode())
7118 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
7119 return V;
7121 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
7122 if (SDValue MM = unfoldMaskedMerge(N))
7123 return MM;
7125 // Simplify the expression using non-local knowledge.
7126 if (SimplifyDemandedBits(SDValue(N, 0)))
7127 return SDValue(N, 0);
7129 return SDValue();
7132 /// Handle transforms common to the three shifts, when the shift amount is a
7133 /// constant.
7134 /// We are looking for: (shift being one of shl/sra/srl)
7135 /// shift (binop X, C0), C1
7136 /// And want to transform into:
7137 /// binop (shift X, C1), (shift C0, C1)
7138 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
7139 // Do not turn a 'not' into a regular xor.
7140 if (isBitwiseNot(N->getOperand(0)))
7141 return SDValue();
7143 // The inner binop must be one-use, since we want to replace it.
7144 SDNode *LHS = N->getOperand(0).getNode();
7145 if (!LHS->hasOneUse()) return SDValue();
7147 // We want to pull some binops through shifts, so that we have (and (shift))
7148 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
7149 // thing happens with address calculations, so it's important to canonicalize
7150 // it.
7151 switch (LHS->getOpcode()) {
7152 default:
7153 return SDValue();
7154 case ISD::OR:
7155 case ISD::XOR:
7156 case ISD::AND:
7157 break;
7158 case ISD::ADD:
7159 if (N->getOpcode() != ISD::SHL)
7160 return SDValue(); // only shl(add) not sr[al](add).
7161 break;
7164 // We require the RHS of the binop to be a constant and not opaque as well.
7165 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
7166 if (!BinOpCst)
7167 return SDValue();
7169 // FIXME: disable this unless the input to the binop is a shift by a constant
7170 // or is copy/select. Enable this in other cases when figure out it's exactly
7171 // profitable.
7172 SDValue BinOpLHSVal = LHS->getOperand(0);
7173 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
7174 BinOpLHSVal.getOpcode() == ISD::SRA ||
7175 BinOpLHSVal.getOpcode() == ISD::SRL) &&
7176 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
7177 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
7178 BinOpLHSVal.getOpcode() == ISD::SELECT;
7180 if (!IsShiftByConstant && !IsCopyOrSelect)
7181 return SDValue();
7183 if (IsCopyOrSelect && N->hasOneUse())
7184 return SDValue();
7186 EVT VT = N->getValueType(0);
7188 if (!TLI.isDesirableToCommuteWithShift(N, Level))
7189 return SDValue();
7191 // Fold the constants, shifting the binop RHS by the shift amount.
7192 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
7193 N->getValueType(0),
7194 LHS->getOperand(1), N->getOperand(1));
7195 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
7197 // Create the new shift.
7198 SDValue NewShift = DAG.getNode(N->getOpcode(),
7199 SDLoc(LHS->getOperand(0)),
7200 VT, LHS->getOperand(0), N->getOperand(1));
7202 // Create the new binop.
7203 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
7206 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
7207 assert(N->getOpcode() == ISD::TRUNCATE);
7208 assert(N->getOperand(0).getOpcode() == ISD::AND);
7210 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
7211 EVT TruncVT = N->getValueType(0);
7212 if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
7213 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
7214 SDValue N01 = N->getOperand(0).getOperand(1);
7215 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
7216 SDLoc DL(N);
7217 SDValue N00 = N->getOperand(0).getOperand(0);
7218 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
7219 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
7220 AddToWorklist(Trunc00.getNode());
7221 AddToWorklist(Trunc01.getNode());
7222 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
7226 return SDValue();
7229 SDValue DAGCombiner::visitRotate(SDNode *N) {
7230 SDLoc dl(N);
7231 SDValue N0 = N->getOperand(0);
7232 SDValue N1 = N->getOperand(1);
7233 EVT VT = N->getValueType(0);
7234 unsigned Bitsize = VT.getScalarSizeInBits();
7236 // fold (rot x, 0) -> x
7237 if (isNullOrNullSplat(N1))
7238 return N0;
7240 // fold (rot x, c) -> x iff (c % BitSize) == 0
7241 if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
7242 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
7243 if (DAG.MaskedValueIsZero(N1, ModuloMask))
7244 return N0;
7247 // fold (rot x, c) -> (rot x, c % BitSize)
7248 // TODO - support non-uniform vector amounts.
7249 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
7250 if (Cst->getAPIntValue().uge(Bitsize)) {
7251 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
7252 return DAG.getNode(N->getOpcode(), dl, VT, N0,
7253 DAG.getConstant(RotAmt, dl, N1.getValueType()));
7257 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
7258 if (N1.getOpcode() == ISD::TRUNCATE &&
7259 N1.getOperand(0).getOpcode() == ISD::AND) {
7260 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7261 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
7264 unsigned NextOp = N0.getOpcode();
7265 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
7266 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
7267 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
7268 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
7269 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
7270 EVT ShiftVT = C1->getValueType(0);
7271 bool SameSide = (N->getOpcode() == NextOp);
7272 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
7273 if (SDValue CombinedShift =
7274 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
7275 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
7276 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
7277 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
7278 BitsizeC.getNode());
7279 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
7280 CombinedShiftNorm);
7284 return SDValue();
7287 SDValue DAGCombiner::visitSHL(SDNode *N) {
7288 SDValue N0 = N->getOperand(0);
7289 SDValue N1 = N->getOperand(1);
7290 if (SDValue V = DAG.simplifyShift(N0, N1))
7291 return V;
7293 EVT VT = N0.getValueType();
7294 EVT ShiftVT = N1.getValueType();
7295 unsigned OpSizeInBits = VT.getScalarSizeInBits();
7297 // fold vector ops
7298 if (VT.isVector()) {
7299 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7300 return FoldedVOp;
7302 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
7303 // If setcc produces all-one true value then:
7304 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
7305 if (N1CV && N1CV->isConstant()) {
7306 if (N0.getOpcode() == ISD::AND) {
7307 SDValue N00 = N0->getOperand(0);
7308 SDValue N01 = N0->getOperand(1);
7309 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
7311 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
7312 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
7313 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7314 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
7315 N01CV, N1CV))
7316 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
7322 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7324 // fold (shl c1, c2) -> c1<<c2
7325 // TODO - support non-uniform vector shift amounts.
7326 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
7327 if (N0C && N1C && !N1C->isOpaque())
7328 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
7330 if (SDValue NewSel = foldBinOpIntoSelect(N))
7331 return NewSel;
7333 // if (shl x, c) is known to be zero, return 0
7334 if (DAG.MaskedValueIsZero(SDValue(N, 0),
7335 APInt::getAllOnesValue(OpSizeInBits)))
7336 return DAG.getConstant(0, SDLoc(N), VT);
7338 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
7339 if (N1.getOpcode() == ISD::TRUNCATE &&
7340 N1.getOperand(0).getOpcode() == ISD::AND) {
7341 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7342 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
7345 // TODO - support non-uniform vector shift amounts.
7346 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
7347 return SDValue(N, 0);
7349 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
7350 if (N0.getOpcode() == ISD::SHL) {
7351 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
7352 ConstantSDNode *RHS) {
7353 APInt c1 = LHS->getAPIntValue();
7354 APInt c2 = RHS->getAPIntValue();
7355 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7356 return (c1 + c2).uge(OpSizeInBits);
7358 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
7359 return DAG.getConstant(0, SDLoc(N), VT);
7361 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
7362 ConstantSDNode *RHS) {
7363 APInt c1 = LHS->getAPIntValue();
7364 APInt c2 = RHS->getAPIntValue();
7365 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7366 return (c1 + c2).ult(OpSizeInBits);
7368 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
7369 SDLoc DL(N);
7370 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
7371 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
7375 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
7376 // For this to be valid, the second form must not preserve any of the bits
7377 // that are shifted out by the inner shift in the first form. This means
7378 // the outer shift size must be >= the number of bits added by the ext.
7379 // As a corollary, we don't care what kind of ext it is.
7380 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
7381 N0.getOpcode() == ISD::ANY_EXTEND ||
7382 N0.getOpcode() == ISD::SIGN_EXTEND) &&
7383 N0.getOperand(0).getOpcode() == ISD::SHL) {
7384 SDValue N0Op0 = N0.getOperand(0);
7385 SDValue InnerShiftAmt = N0Op0.getOperand(1);
7386 EVT InnerVT = N0Op0.getValueType();
7387 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
7389 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
7390 ConstantSDNode *RHS) {
7391 APInt c1 = LHS->getAPIntValue();
7392 APInt c2 = RHS->getAPIntValue();
7393 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7394 return c2.uge(OpSizeInBits - InnerBitwidth) &&
7395 (c1 + c2).uge(OpSizeInBits);
7397 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
7398 /*AllowUndefs*/ false,
7399 /*AllowTypeMismatch*/ true))
7400 return DAG.getConstant(0, SDLoc(N), VT);
7402 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
7403 ConstantSDNode *RHS) {
7404 APInt c1 = LHS->getAPIntValue();
7405 APInt c2 = RHS->getAPIntValue();
7406 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7407 return c2.uge(OpSizeInBits - InnerBitwidth) &&
7408 (c1 + c2).ult(OpSizeInBits);
7410 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
7411 /*AllowUndefs*/ false,
7412 /*AllowTypeMismatch*/ true)) {
7413 SDLoc DL(N);
7414 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
7415 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
7416 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
7417 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
7421 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
7422 // Only fold this if the inner zext has no other uses to avoid increasing
7423 // the total number of instructions.
7424 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
7425 N0.getOperand(0).getOpcode() == ISD::SRL) {
7426 SDValue N0Op0 = N0.getOperand(0);
7427 SDValue InnerShiftAmt = N0Op0.getOperand(1);
7429 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7430 APInt c1 = LHS->getAPIntValue();
7431 APInt c2 = RHS->getAPIntValue();
7432 zeroExtendToMatch(c1, c2);
7433 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
7435 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
7436 /*AllowUndefs*/ false,
7437 /*AllowTypeMismatch*/ true)) {
7438 SDLoc DL(N);
7439 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
7440 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
7441 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
7442 AddToWorklist(NewSHL.getNode());
7443 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
7447 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
7448 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
7449 // TODO - support non-uniform vector shift amounts.
7450 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
7451 N0->getFlags().hasExact()) {
7452 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
7453 uint64_t C1 = N0C1->getZExtValue();
7454 uint64_t C2 = N1C->getZExtValue();
7455 SDLoc DL(N);
7456 if (C1 <= C2)
7457 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
7458 DAG.getConstant(C2 - C1, DL, ShiftVT));
7459 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
7460 DAG.getConstant(C1 - C2, DL, ShiftVT));
7464 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
7465 // (and (srl x, (sub c1, c2), MASK)
7466 // Only fold this if the inner shift has no other uses -- if it does, folding
7467 // this will increase the total number of instructions.
7468 // TODO - drop hasOneUse requirement if c1 == c2?
7469 // TODO - support non-uniform vector shift amounts.
7470 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
7471 TLI.shouldFoldConstantShiftPairToMask(N, Level)) {
7472 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
7473 if (N0C1->getAPIntValue().ult(OpSizeInBits)) {
7474 uint64_t c1 = N0C1->getZExtValue();
7475 uint64_t c2 = N1C->getZExtValue();
7476 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
7477 SDValue Shift;
7478 if (c2 > c1) {
7479 Mask <<= c2 - c1;
7480 SDLoc DL(N);
7481 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
7482 DAG.getConstant(c2 - c1, DL, ShiftVT));
7483 } else {
7484 Mask.lshrInPlace(c1 - c2);
7485 SDLoc DL(N);
7486 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
7487 DAG.getConstant(c1 - c2, DL, ShiftVT));
7489 SDLoc DL(N0);
7490 return DAG.getNode(ISD::AND, DL, VT, Shift,
7491 DAG.getConstant(Mask, DL, VT));
7496 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
7497 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
7498 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
7499 SDLoc DL(N);
7500 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
7501 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
7502 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
7505 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7506 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7507 // Variant of version done on multiply, except mul by a power of 2 is turned
7508 // into a shift.
7509 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
7510 N0.getNode()->hasOneUse() &&
7511 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
7512 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) &&
7513 TLI.isDesirableToCommuteWithShift(N, Level)) {
7514 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
7515 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
7516 AddToWorklist(Shl0.getNode());
7517 AddToWorklist(Shl1.getNode());
7518 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
7521 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
7522 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
7523 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
7524 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
7525 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
7526 if (isConstantOrConstantVector(Shl))
7527 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
7530 if (N1C && !N1C->isOpaque())
7531 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
7532 return NewSHL;
7534 return SDValue();
7537 SDValue DAGCombiner::visitSRA(SDNode *N) {
7538 SDValue N0 = N->getOperand(0);
7539 SDValue N1 = N->getOperand(1);
7540 if (SDValue V = DAG.simplifyShift(N0, N1))
7541 return V;
7543 EVT VT = N0.getValueType();
7544 unsigned OpSizeInBits = VT.getScalarSizeInBits();
7546 // Arithmetic shifting an all-sign-bit value is a no-op.
7547 // fold (sra 0, x) -> 0
7548 // fold (sra -1, x) -> -1
7549 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
7550 return N0;
7552 // fold vector ops
7553 if (VT.isVector())
7554 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7555 return FoldedVOp;
7557 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7559 // fold (sra c1, c2) -> (sra c1, c2)
7560 // TODO - support non-uniform vector shift amounts.
7561 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
7562 if (N0C && N1C && !N1C->isOpaque())
7563 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
7565 if (SDValue NewSel = foldBinOpIntoSelect(N))
7566 return NewSel;
7568 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
7569 // sext_inreg.
7570 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
7571 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
7572 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
7573 if (VT.isVector())
7574 ExtVT = EVT::getVectorVT(*DAG.getContext(),
7575 ExtVT, VT.getVectorNumElements());
7576 if ((!LegalOperations ||
7577 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
7578 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7579 N0.getOperand(0), DAG.getValueType(ExtVT));
7582 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
7583 // clamp (add c1, c2) to max shift.
7584 if (N0.getOpcode() == ISD::SRA) {
7585 SDLoc DL(N);
7586 EVT ShiftVT = N1.getValueType();
7587 EVT ShiftSVT = ShiftVT.getScalarType();
7588 SmallVector<SDValue, 16> ShiftValues;
7590 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7591 APInt c1 = LHS->getAPIntValue();
7592 APInt c2 = RHS->getAPIntValue();
7593 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7594 APInt Sum = c1 + c2;
7595 unsigned ShiftSum =
7596 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
7597 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
7598 return true;
7600 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
7601 SDValue ShiftValue;
7602 if (VT.isVector())
7603 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
7604 else
7605 ShiftValue = ShiftValues[0];
7606 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
7610 // fold (sra (shl X, m), (sub result_size, n))
7611 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
7612 // result_size - n != m.
7613 // If truncate is free for the target sext(shl) is likely to result in better
7614 // code.
7615 if (N0.getOpcode() == ISD::SHL && N1C) {
7616 // Get the two constanst of the shifts, CN0 = m, CN = n.
7617 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
7618 if (N01C) {
7619 LLVMContext &Ctx = *DAG.getContext();
7620 // Determine what the truncate's result bitsize and type would be.
7621 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
7623 if (VT.isVector())
7624 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
7626 // Determine the residual right-shift amount.
7627 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
7629 // If the shift is not a no-op (in which case this should be just a sign
7630 // extend already), the truncated to type is legal, sign_extend is legal
7631 // on that type, and the truncate to that type is both legal and free,
7632 // perform the transform.
7633 if ((ShiftAmt > 0) &&
7634 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
7635 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
7636 TLI.isTruncateFree(VT, TruncVT)) {
7637 SDLoc DL(N);
7638 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
7639 getShiftAmountTy(N0.getOperand(0).getValueType()));
7640 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
7641 N0.getOperand(0), Amt);
7642 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
7643 Shift);
7644 return DAG.getNode(ISD::SIGN_EXTEND, DL,
7645 N->getValueType(0), Trunc);
7650 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
7651 // sra (add (shl X, N1C), AddC), N1C -->
7652 // sext (add (trunc X to (width - N1C)), AddC')
7653 if (!LegalTypes && N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C &&
7654 N0.getOperand(0).getOpcode() == ISD::SHL &&
7655 N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) {
7656 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
7657 SDValue Shl = N0.getOperand(0);
7658 // Determine what the truncate's type would be and ask the target if that
7659 // is a free operation.
7660 LLVMContext &Ctx = *DAG.getContext();
7661 unsigned ShiftAmt = N1C->getZExtValue();
7662 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt);
7663 if (VT.isVector())
7664 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
7666 // TODO: The simple type check probably belongs in the default hook
7667 // implementation and/or target-specific overrides (because
7668 // non-simple types likely require masking when legalized), but that
7669 // restriction may conflict with other transforms.
7670 if (TruncVT.isSimple() && TLI.isTruncateFree(VT, TruncVT)) {
7671 SDLoc DL(N);
7672 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
7673 SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).
7674 trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT);
7675 SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
7676 return DAG.getSExtOrTrunc(Add, DL, VT);
7681 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
7682 if (N1.getOpcode() == ISD::TRUNCATE &&
7683 N1.getOperand(0).getOpcode() == ISD::AND) {
7684 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7685 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
7688 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
7689 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
7690 // if c1 is equal to the number of bits the trunc removes
7691 // TODO - support non-uniform vector shift amounts.
7692 if (N0.getOpcode() == ISD::TRUNCATE &&
7693 (N0.getOperand(0).getOpcode() == ISD::SRL ||
7694 N0.getOperand(0).getOpcode() == ISD::SRA) &&
7695 N0.getOperand(0).hasOneUse() &&
7696 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
7697 SDValue N0Op0 = N0.getOperand(0);
7698 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
7699 EVT LargeVT = N0Op0.getValueType();
7700 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
7701 if (LargeShift->getAPIntValue() == TruncBits) {
7702 SDLoc DL(N);
7703 SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL,
7704 getShiftAmountTy(LargeVT));
7705 SDValue SRA =
7706 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
7707 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
7712 // Simplify, based on bits shifted out of the LHS.
7713 // TODO - support non-uniform vector shift amounts.
7714 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
7715 return SDValue(N, 0);
7717 // If the sign bit is known to be zero, switch this to a SRL.
7718 if (DAG.SignBitIsZero(N0))
7719 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
7721 if (N1C && !N1C->isOpaque())
7722 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
7723 return NewSRA;
7725 return SDValue();
7728 SDValue DAGCombiner::visitSRL(SDNode *N) {
7729 SDValue N0 = N->getOperand(0);
7730 SDValue N1 = N->getOperand(1);
7731 if (SDValue V = DAG.simplifyShift(N0, N1))
7732 return V;
7734 EVT VT = N0.getValueType();
7735 unsigned OpSizeInBits = VT.getScalarSizeInBits();
7737 // fold vector ops
7738 if (VT.isVector())
7739 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7740 return FoldedVOp;
7742 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7744 // fold (srl c1, c2) -> c1 >>u c2
7745 // TODO - support non-uniform vector shift amounts.
7746 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
7747 if (N0C && N1C && !N1C->isOpaque())
7748 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
7750 if (SDValue NewSel = foldBinOpIntoSelect(N))
7751 return NewSel;
7753 // if (srl x, c) is known to be zero, return 0
7754 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
7755 APInt::getAllOnesValue(OpSizeInBits)))
7756 return DAG.getConstant(0, SDLoc(N), VT);
7758 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
7759 if (N0.getOpcode() == ISD::SRL) {
7760 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
7761 ConstantSDNode *RHS) {
7762 APInt c1 = LHS->getAPIntValue();
7763 APInt c2 = RHS->getAPIntValue();
7764 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7765 return (c1 + c2).uge(OpSizeInBits);
7767 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
7768 return DAG.getConstant(0, SDLoc(N), VT);
7770 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
7771 ConstantSDNode *RHS) {
7772 APInt c1 = LHS->getAPIntValue();
7773 APInt c2 = RHS->getAPIntValue();
7774 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7775 return (c1 + c2).ult(OpSizeInBits);
7777 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
7778 SDLoc DL(N);
7779 EVT ShiftVT = N1.getValueType();
7780 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
7781 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
7785 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
7786 // TODO - support non-uniform vector shift amounts.
7787 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
7788 N0.getOperand(0).getOpcode() == ISD::SRL) {
7789 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
7790 uint64_t c1 = N001C->getZExtValue();
7791 uint64_t c2 = N1C->getZExtValue();
7792 EVT InnerShiftVT = N0.getOperand(0).getValueType();
7793 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
7794 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
7795 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
7796 if (c1 + OpSizeInBits == InnerShiftSize) {
7797 SDLoc DL(N0);
7798 if (c1 + c2 >= InnerShiftSize)
7799 return DAG.getConstant(0, DL, VT);
7800 return DAG.getNode(ISD::TRUNCATE, DL, VT,
7801 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
7802 N0.getOperand(0).getOperand(0),
7803 DAG.getConstant(c1 + c2, DL,
7804 ShiftCountVT)));
7809 // fold (srl (shl x, c), c) -> (and x, cst2)
7810 // TODO - (srl (shl x, c1), c2).
7811 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
7812 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
7813 SDLoc DL(N);
7814 SDValue Mask =
7815 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
7816 AddToWorklist(Mask.getNode());
7817 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
7820 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
7821 // TODO - support non-uniform vector shift amounts.
7822 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
7823 // Shifting in all undef bits?
7824 EVT SmallVT = N0.getOperand(0).getValueType();
7825 unsigned BitSize = SmallVT.getScalarSizeInBits();
7826 if (N1C->getAPIntValue().uge(BitSize))
7827 return DAG.getUNDEF(VT);
7829 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
7830 uint64_t ShiftAmt = N1C->getZExtValue();
7831 SDLoc DL0(N0);
7832 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
7833 N0.getOperand(0),
7834 DAG.getConstant(ShiftAmt, DL0,
7835 getShiftAmountTy(SmallVT)));
7836 AddToWorklist(SmallShift.getNode());
7837 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
7838 SDLoc DL(N);
7839 return DAG.getNode(ISD::AND, DL, VT,
7840 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
7841 DAG.getConstant(Mask, DL, VT));
7845 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
7846 // bit, which is unmodified by sra.
7847 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
7848 if (N0.getOpcode() == ISD::SRA)
7849 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
7852 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
7853 if (N1C && N0.getOpcode() == ISD::CTLZ &&
7854 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
7855 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
7857 // If any of the input bits are KnownOne, then the input couldn't be all
7858 // zeros, thus the result of the srl will always be zero.
7859 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
7861 // If all of the bits input the to ctlz node are known to be zero, then
7862 // the result of the ctlz is "32" and the result of the shift is one.
7863 APInt UnknownBits = ~Known.Zero;
7864 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
7866 // Otherwise, check to see if there is exactly one bit input to the ctlz.
7867 if (UnknownBits.isPowerOf2()) {
7868 // Okay, we know that only that the single bit specified by UnknownBits
7869 // could be set on input to the CTLZ node. If this bit is set, the SRL
7870 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
7871 // to an SRL/XOR pair, which is likely to simplify more.
7872 unsigned ShAmt = UnknownBits.countTrailingZeros();
7873 SDValue Op = N0.getOperand(0);
7875 if (ShAmt) {
7876 SDLoc DL(N0);
7877 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
7878 DAG.getConstant(ShAmt, DL,
7879 getShiftAmountTy(Op.getValueType())));
7880 AddToWorklist(Op.getNode());
7883 SDLoc DL(N);
7884 return DAG.getNode(ISD::XOR, DL, VT,
7885 Op, DAG.getConstant(1, DL, VT));
7889 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
7890 if (N1.getOpcode() == ISD::TRUNCATE &&
7891 N1.getOperand(0).getOpcode() == ISD::AND) {
7892 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7893 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
7896 // fold operands of srl based on knowledge that the low bits are not
7897 // demanded.
7898 // TODO - support non-uniform vector shift amounts.
7899 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
7900 return SDValue(N, 0);
7902 if (N1C && !N1C->isOpaque())
7903 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
7904 return NewSRL;
7906 // Attempt to convert a srl of a load into a narrower zero-extending load.
7907 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7908 return NarrowLoad;
7910 // Here is a common situation. We want to optimize:
7912 // %a = ...
7913 // %b = and i32 %a, 2
7914 // %c = srl i32 %b, 1
7915 // brcond i32 %c ...
7917 // into
7919 // %a = ...
7920 // %b = and %a, 2
7921 // %c = setcc eq %b, 0
7922 // brcond %c ...
7924 // However when after the source operand of SRL is optimized into AND, the SRL
7925 // itself may not be optimized further. Look for it and add the BRCOND into
7926 // the worklist.
7927 if (N->hasOneUse()) {
7928 SDNode *Use = *N->use_begin();
7929 if (Use->getOpcode() == ISD::BRCOND)
7930 AddToWorklist(Use);
7931 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
7932 // Also look pass the truncate.
7933 Use = *Use->use_begin();
7934 if (Use->getOpcode() == ISD::BRCOND)
7935 AddToWorklist(Use);
7939 return SDValue();
7942 SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
7943 EVT VT = N->getValueType(0);
7944 SDValue N0 = N->getOperand(0);
7945 SDValue N1 = N->getOperand(1);
7946 SDValue N2 = N->getOperand(2);
7947 bool IsFSHL = N->getOpcode() == ISD::FSHL;
7948 unsigned BitWidth = VT.getScalarSizeInBits();
7950 // fold (fshl N0, N1, 0) -> N0
7951 // fold (fshr N0, N1, 0) -> N1
7952 if (isPowerOf2_32(BitWidth))
7953 if (DAG.MaskedValueIsZero(
7954 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
7955 return IsFSHL ? N0 : N1;
7957 auto IsUndefOrZero = [](SDValue V) {
7958 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
7961 // TODO - support non-uniform vector shift amounts.
7962 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
7963 EVT ShAmtTy = N2.getValueType();
7965 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
7966 if (Cst->getAPIntValue().uge(BitWidth)) {
7967 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
7968 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1,
7969 DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy));
7972 unsigned ShAmt = Cst->getZExtValue();
7973 if (ShAmt == 0)
7974 return IsFSHL ? N0 : N1;
7976 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
7977 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
7978 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
7979 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
7980 if (IsUndefOrZero(N0))
7981 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1,
7982 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt,
7983 SDLoc(N), ShAmtTy));
7984 if (IsUndefOrZero(N1))
7985 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
7986 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt,
7987 SDLoc(N), ShAmtTy));
7990 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
7991 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
7992 // iff We know the shift amount is in range.
7993 // TODO: when is it worth doing SUB(BW, N2) as well?
7994 if (isPowerOf2_32(BitWidth)) {
7995 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
7996 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
7997 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2);
7998 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
7999 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2);
8002 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
8003 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
8004 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
8005 // is legal as well we might be better off avoiding non-constant (BW - N2).
8006 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
8007 if (N0 == N1 && hasOperation(RotOpc, VT))
8008 return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2);
8010 // Simplify, based on bits shifted out of N0/N1.
8011 if (SimplifyDemandedBits(SDValue(N, 0)))
8012 return SDValue(N, 0);
8014 return SDValue();
8017 SDValue DAGCombiner::visitABS(SDNode *N) {
8018 SDValue N0 = N->getOperand(0);
8019 EVT VT = N->getValueType(0);
8021 // fold (abs c1) -> c2
8022 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8023 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
8024 // fold (abs (abs x)) -> (abs x)
8025 if (N0.getOpcode() == ISD::ABS)
8026 return N0;
8027 // fold (abs x) -> x iff not-negative
8028 if (DAG.SignBitIsZero(N0))
8029 return N0;
8030 return SDValue();
8033 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
8034 SDValue N0 = N->getOperand(0);
8035 EVT VT = N->getValueType(0);
8037 // fold (bswap c1) -> c2
8038 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8039 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
8040 // fold (bswap (bswap x)) -> x
8041 if (N0.getOpcode() == ISD::BSWAP)
8042 return N0->getOperand(0);
8043 return SDValue();
8046 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
8047 SDValue N0 = N->getOperand(0);
8048 EVT VT = N->getValueType(0);
8050 // fold (bitreverse c1) -> c2
8051 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8052 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
8053 // fold (bitreverse (bitreverse x)) -> x
8054 if (N0.getOpcode() == ISD::BITREVERSE)
8055 return N0.getOperand(0);
8056 return SDValue();
8059 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
8060 SDValue N0 = N->getOperand(0);
8061 EVT VT = N->getValueType(0);
8063 // fold (ctlz c1) -> c2
8064 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8065 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
8067 // If the value is known never to be zero, switch to the undef version.
8068 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
8069 if (DAG.isKnownNeverZero(N0))
8070 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8073 return SDValue();
8076 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
8077 SDValue N0 = N->getOperand(0);
8078 EVT VT = N->getValueType(0);
8080 // fold (ctlz_zero_undef c1) -> c2
8081 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8082 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8083 return SDValue();
8086 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
8087 SDValue N0 = N->getOperand(0);
8088 EVT VT = N->getValueType(0);
8090 // fold (cttz c1) -> c2
8091 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8092 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
8094 // If the value is known never to be zero, switch to the undef version.
8095 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
8096 if (DAG.isKnownNeverZero(N0))
8097 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8100 return SDValue();
8103 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
8104 SDValue N0 = N->getOperand(0);
8105 EVT VT = N->getValueType(0);
8107 // fold (cttz_zero_undef c1) -> c2
8108 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8109 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8110 return SDValue();
8113 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
8114 SDValue N0 = N->getOperand(0);
8115 EVT VT = N->getValueType(0);
8117 // fold (ctpop c1) -> c2
8118 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8119 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
8120 return SDValue();
8123 // FIXME: This should be checking for no signed zeros on individual operands, as
8124 // well as no nans.
8125 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS,
8126 SDValue RHS,
8127 const TargetLowering &TLI) {
8128 const TargetOptions &Options = DAG.getTarget().Options;
8129 EVT VT = LHS.getValueType();
8131 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() &&
8132 TLI.isProfitableToCombineMinNumMaxNum(VT) &&
8133 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS);
8136 /// Generate Min/Max node
8137 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
8138 SDValue RHS, SDValue True, SDValue False,
8139 ISD::CondCode CC, const TargetLowering &TLI,
8140 SelectionDAG &DAG) {
8141 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
8142 return SDValue();
8144 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
8145 switch (CC) {
8146 case ISD::SETOLT:
8147 case ISD::SETOLE:
8148 case ISD::SETLT:
8149 case ISD::SETLE:
8150 case ISD::SETULT:
8151 case ISD::SETULE: {
8152 // Since it's known never nan to get here already, either fminnum or
8153 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
8154 // expanded in terms of it.
8155 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
8156 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
8157 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
8159 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
8160 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
8161 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8162 return SDValue();
8164 case ISD::SETOGT:
8165 case ISD::SETOGE:
8166 case ISD::SETGT:
8167 case ISD::SETGE:
8168 case ISD::SETUGT:
8169 case ISD::SETUGE: {
8170 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
8171 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
8172 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
8174 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
8175 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
8176 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8177 return SDValue();
8179 default:
8180 return SDValue();
8184 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
8185 SDValue Cond = N->getOperand(0);
8186 SDValue N1 = N->getOperand(1);
8187 SDValue N2 = N->getOperand(2);
8188 EVT VT = N->getValueType(0);
8189 EVT CondVT = Cond.getValueType();
8190 SDLoc DL(N);
8192 if (!VT.isInteger())
8193 return SDValue();
8195 auto *C1 = dyn_cast<ConstantSDNode>(N1);
8196 auto *C2 = dyn_cast<ConstantSDNode>(N2);
8197 if (!C1 || !C2)
8198 return SDValue();
8200 // Only do this before legalization to avoid conflicting with target-specific
8201 // transforms in the other direction (create a select from a zext/sext). There
8202 // is also a target-independent combine here in DAGCombiner in the other
8203 // direction for (select Cond, -1, 0) when the condition is not i1.
8204 if (CondVT == MVT::i1 && !LegalOperations) {
8205 if (C1->isNullValue() && C2->isOne()) {
8206 // select Cond, 0, 1 --> zext (!Cond)
8207 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
8208 if (VT != MVT::i1)
8209 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
8210 return NotCond;
8212 if (C1->isNullValue() && C2->isAllOnesValue()) {
8213 // select Cond, 0, -1 --> sext (!Cond)
8214 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
8215 if (VT != MVT::i1)
8216 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
8217 return NotCond;
8219 if (C1->isOne() && C2->isNullValue()) {
8220 // select Cond, 1, 0 --> zext (Cond)
8221 if (VT != MVT::i1)
8222 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
8223 return Cond;
8225 if (C1->isAllOnesValue() && C2->isNullValue()) {
8226 // select Cond, -1, 0 --> sext (Cond)
8227 if (VT != MVT::i1)
8228 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
8229 return Cond;
8232 // For any constants that differ by 1, we can transform the select into an
8233 // extend and add. Use a target hook because some targets may prefer to
8234 // transform in the other direction.
8235 if (TLI.convertSelectOfConstantsToMath(VT)) {
8236 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
8237 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
8238 if (VT != MVT::i1)
8239 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
8240 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
8242 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
8243 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
8244 if (VT != MVT::i1)
8245 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
8246 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
8250 return SDValue();
8253 // fold (select Cond, 0, 1) -> (xor Cond, 1)
8254 // We can't do this reliably if integer based booleans have different contents
8255 // to floating point based booleans. This is because we can't tell whether we
8256 // have an integer-based boolean or a floating-point-based boolean unless we
8257 // can find the SETCC that produced it and inspect its operands. This is
8258 // fairly easy if C is the SETCC node, but it can potentially be
8259 // undiscoverable (or not reasonably discoverable). For example, it could be
8260 // in another basic block or it could require searching a complicated
8261 // expression.
8262 if (CondVT.isInteger() &&
8263 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
8264 TargetLowering::ZeroOrOneBooleanContent &&
8265 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
8266 TargetLowering::ZeroOrOneBooleanContent &&
8267 C1->isNullValue() && C2->isOne()) {
8268 SDValue NotCond =
8269 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
8270 if (VT.bitsEq(CondVT))
8271 return NotCond;
8272 return DAG.getZExtOrTrunc(NotCond, DL, VT);
8275 return SDValue();
8278 SDValue DAGCombiner::visitSELECT(SDNode *N) {
8279 SDValue N0 = N->getOperand(0);
8280 SDValue N1 = N->getOperand(1);
8281 SDValue N2 = N->getOperand(2);
8282 EVT VT = N->getValueType(0);
8283 EVT VT0 = N0.getValueType();
8284 SDLoc DL(N);
8285 SDNodeFlags Flags = N->getFlags();
8287 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
8288 return V;
8290 // fold (select X, X, Y) -> (or X, Y)
8291 // fold (select X, 1, Y) -> (or C, Y)
8292 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
8293 return DAG.getNode(ISD::OR, DL, VT, N0, N2);
8295 if (SDValue V = foldSelectOfConstants(N))
8296 return V;
8298 // fold (select C, 0, X) -> (and (not C), X)
8299 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
8300 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
8301 AddToWorklist(NOTNode.getNode());
8302 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
8304 // fold (select C, X, 1) -> (or (not C), X)
8305 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
8306 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
8307 AddToWorklist(NOTNode.getNode());
8308 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
8310 // fold (select X, Y, X) -> (and X, Y)
8311 // fold (select X, Y, 0) -> (and X, Y)
8312 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
8313 return DAG.getNode(ISD::AND, DL, VT, N0, N1);
8315 // If we can fold this based on the true/false value, do so.
8316 if (SimplifySelectOps(N, N1, N2))
8317 return SDValue(N, 0); // Don't revisit N.
8319 if (VT0 == MVT::i1) {
8320 // The code in this block deals with the following 2 equivalences:
8321 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
8322 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
8323 // The target can specify its preferred form with the
8324 // shouldNormalizeToSelectSequence() callback. However we always transform
8325 // to the right anyway if we find the inner select exists in the DAG anyway
8326 // and we always transform to the left side if we know that we can further
8327 // optimize the combination of the conditions.
8328 bool normalizeToSequence =
8329 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
8330 // select (and Cond0, Cond1), X, Y
8331 // -> select Cond0, (select Cond1, X, Y), Y
8332 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
8333 SDValue Cond0 = N0->getOperand(0);
8334 SDValue Cond1 = N0->getOperand(1);
8335 SDValue InnerSelect =
8336 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
8337 if (normalizeToSequence || !InnerSelect.use_empty())
8338 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
8339 InnerSelect, N2, Flags);
8340 // Cleanup on failure.
8341 if (InnerSelect.use_empty())
8342 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8344 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
8345 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
8346 SDValue Cond0 = N0->getOperand(0);
8347 SDValue Cond1 = N0->getOperand(1);
8348 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
8349 Cond1, N1, N2, Flags);
8350 if (normalizeToSequence || !InnerSelect.use_empty())
8351 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
8352 InnerSelect, Flags);
8353 // Cleanup on failure.
8354 if (InnerSelect.use_empty())
8355 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8358 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
8359 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
8360 SDValue N1_0 = N1->getOperand(0);
8361 SDValue N1_1 = N1->getOperand(1);
8362 SDValue N1_2 = N1->getOperand(2);
8363 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
8364 // Create the actual and node if we can generate good code for it.
8365 if (!normalizeToSequence) {
8366 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
8367 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
8368 N2, Flags);
8370 // Otherwise see if we can optimize the "and" to a better pattern.
8371 if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
8372 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
8373 N2, Flags);
8377 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
8378 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
8379 SDValue N2_0 = N2->getOperand(0);
8380 SDValue N2_1 = N2->getOperand(1);
8381 SDValue N2_2 = N2->getOperand(2);
8382 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
8383 // Create the actual or node if we can generate good code for it.
8384 if (!normalizeToSequence) {
8385 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
8386 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
8387 N2_2, Flags);
8389 // Otherwise see if we can optimize to a better pattern.
8390 if (SDValue Combined = visitORLike(N0, N2_0, N))
8391 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
8392 N2_2, Flags);
8397 // select (not Cond), N1, N2 -> select Cond, N2, N1
8398 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) {
8399 SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1);
8400 SelectOp->setFlags(Flags);
8401 return SelectOp;
8404 // Fold selects based on a setcc into other things, such as min/max/abs.
8405 if (N0.getOpcode() == ISD::SETCC) {
8406 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
8407 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
8409 // select (fcmp lt x, y), x, y -> fminnum x, y
8410 // select (fcmp gt x, y), x, y -> fmaxnum x, y
8412 // This is OK if we don't care what happens if either operand is a NaN.
8413 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI))
8414 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2,
8415 CC, TLI, DAG))
8416 return FMinMax;
8418 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
8419 // This is conservatively limited to pre-legal-operations to give targets
8420 // a chance to reverse the transform if they want to do that. Also, it is
8421 // unlikely that the pattern would be formed late, so it's probably not
8422 // worth going through the other checks.
8423 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
8424 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
8425 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
8426 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
8427 auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
8428 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
8429 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
8430 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
8432 // The IR equivalent of this transform would have this form:
8433 // %a = add %x, C
8434 // %c = icmp ugt %x, ~C
8435 // %r = select %c, -1, %a
8436 // =>
8437 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
8438 // %u0 = extractvalue %u, 0
8439 // %u1 = extractvalue %u, 1
8440 // %r = select %u1, -1, %u0
8441 SDVTList VTs = DAG.getVTList(VT, VT0);
8442 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
8443 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
8447 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
8448 (!LegalOperations &&
8449 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) {
8450 // Any flags available in a select/setcc fold will be on the setcc as they
8451 // migrated from fcmp
8452 Flags = N0.getNode()->getFlags();
8453 SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1,
8454 N2, N0.getOperand(2));
8455 SelectNode->setFlags(Flags);
8456 return SelectNode;
8459 return SimplifySelect(DL, N0, N1, N2);
8462 return SDValue();
8465 // This function assumes all the vselect's arguments are CONCAT_VECTOR
8466 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
8467 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
8468 SDLoc DL(N);
8469 SDValue Cond = N->getOperand(0);
8470 SDValue LHS = N->getOperand(1);
8471 SDValue RHS = N->getOperand(2);
8472 EVT VT = N->getValueType(0);
8473 int NumElems = VT.getVectorNumElements();
8474 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
8475 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
8476 Cond.getOpcode() == ISD::BUILD_VECTOR);
8478 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
8479 // binary ones here.
8480 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
8481 return SDValue();
8483 // We're sure we have an even number of elements due to the
8484 // concat_vectors we have as arguments to vselect.
8485 // Skip BV elements until we find one that's not an UNDEF
8486 // After we find an UNDEF element, keep looping until we get to half the
8487 // length of the BV and see if all the non-undef nodes are the same.
8488 ConstantSDNode *BottomHalf = nullptr;
8489 for (int i = 0; i < NumElems / 2; ++i) {
8490 if (Cond->getOperand(i)->isUndef())
8491 continue;
8493 if (BottomHalf == nullptr)
8494 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
8495 else if (Cond->getOperand(i).getNode() != BottomHalf)
8496 return SDValue();
8499 // Do the same for the second half of the BuildVector
8500 ConstantSDNode *TopHalf = nullptr;
8501 for (int i = NumElems / 2; i < NumElems; ++i) {
8502 if (Cond->getOperand(i)->isUndef())
8503 continue;
8505 if (TopHalf == nullptr)
8506 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
8507 else if (Cond->getOperand(i).getNode() != TopHalf)
8508 return SDValue();
8511 assert(TopHalf && BottomHalf &&
8512 "One half of the selector was all UNDEFs and the other was all the "
8513 "same value. This should have been addressed before this function.");
8514 return DAG.getNode(
8515 ISD::CONCAT_VECTORS, DL, VT,
8516 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
8517 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
8520 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
8521 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
8522 SDValue Mask = MSC->getMask();
8523 SDValue Chain = MSC->getChain();
8524 SDLoc DL(N);
8526 // Zap scatters with a zero mask.
8527 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
8528 return Chain;
8530 return SDValue();
8533 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
8534 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
8535 SDValue Mask = MST->getMask();
8536 SDValue Chain = MST->getChain();
8537 SDLoc DL(N);
8539 // Zap masked stores with a zero mask.
8540 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
8541 return Chain;
8543 return SDValue();
8546 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
8547 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
8548 SDValue Mask = MGT->getMask();
8549 SDLoc DL(N);
8551 // Zap gathers with a zero mask.
8552 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
8553 return CombineTo(N, MGT->getPassThru(), MGT->getChain());
8555 return SDValue();
8558 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
8559 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
8560 SDValue Mask = MLD->getMask();
8561 SDLoc DL(N);
8563 // Zap masked loads with a zero mask.
8564 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
8565 return CombineTo(N, MLD->getPassThru(), MLD->getChain());
8567 return SDValue();
8570 /// A vector select of 2 constant vectors can be simplified to math/logic to
8571 /// avoid a variable select instruction and possibly avoid constant loads.
8572 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
8573 SDValue Cond = N->getOperand(0);
8574 SDValue N1 = N->getOperand(1);
8575 SDValue N2 = N->getOperand(2);
8576 EVT VT = N->getValueType(0);
8577 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
8578 !TLI.convertSelectOfConstantsToMath(VT) ||
8579 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
8580 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
8581 return SDValue();
8583 // Check if we can use the condition value to increment/decrement a single
8584 // constant value. This simplifies a select to an add and removes a constant
8585 // load/materialization from the general case.
8586 bool AllAddOne = true;
8587 bool AllSubOne = true;
8588 unsigned Elts = VT.getVectorNumElements();
8589 for (unsigned i = 0; i != Elts; ++i) {
8590 SDValue N1Elt = N1.getOperand(i);
8591 SDValue N2Elt = N2.getOperand(i);
8592 if (N1Elt.isUndef() || N2Elt.isUndef())
8593 continue;
8595 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
8596 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
8597 if (C1 != C2 + 1)
8598 AllAddOne = false;
8599 if (C1 != C2 - 1)
8600 AllSubOne = false;
8603 // Further simplifications for the extra-special cases where the constants are
8604 // all 0 or all -1 should be implemented as folds of these patterns.
8605 SDLoc DL(N);
8606 if (AllAddOne || AllSubOne) {
8607 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
8608 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
8609 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
8610 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
8611 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
8614 // The general case for select-of-constants:
8615 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
8616 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
8617 // leave that to a machine-specific pass.
8618 return SDValue();
8621 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
8622 SDValue N0 = N->getOperand(0);
8623 SDValue N1 = N->getOperand(1);
8624 SDValue N2 = N->getOperand(2);
8625 EVT VT = N->getValueType(0);
8626 SDLoc DL(N);
8628 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
8629 return V;
8631 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
8632 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
8633 return DAG.getSelect(DL, VT, F, N2, N1);
8635 // Canonicalize integer abs.
8636 // vselect (setg[te] X, 0), X, -X ->
8637 // vselect (setgt X, -1), X, -X ->
8638 // vselect (setl[te] X, 0), -X, X ->
8639 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8640 if (N0.getOpcode() == ISD::SETCC) {
8641 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
8642 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
8643 bool isAbs = false;
8644 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
8646 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
8647 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
8648 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
8649 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
8650 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
8651 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
8652 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
8654 if (isAbs) {
8655 EVT VT = LHS.getValueType();
8656 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
8657 return DAG.getNode(ISD::ABS, DL, VT, LHS);
8659 SDValue Shift = DAG.getNode(
8660 ISD::SRA, DL, VT, LHS,
8661 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
8662 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
8663 AddToWorklist(Shift.getNode());
8664 AddToWorklist(Add.getNode());
8665 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
8668 // vselect x, y (fcmp lt x, y) -> fminnum x, y
8669 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
8671 // This is OK if we don't care about what happens if either operand is a
8672 // NaN.
8674 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N0.getOperand(0),
8675 N0.getOperand(1), TLI)) {
8676 if (SDValue FMinMax = combineMinNumMaxNum(
8677 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
8678 return FMinMax;
8681 // If this select has a condition (setcc) with narrower operands than the
8682 // select, try to widen the compare to match the select width.
8683 // TODO: This should be extended to handle any constant.
8684 // TODO: This could be extended to handle non-loading patterns, but that
8685 // requires thorough testing to avoid regressions.
8686 if (isNullOrNullSplat(RHS)) {
8687 EVT NarrowVT = LHS.getValueType();
8688 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger();
8689 EVT SetCCVT = getSetCCResultType(LHS.getValueType());
8690 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
8691 unsigned WideWidth = WideVT.getScalarSizeInBits();
8692 bool IsSigned = isSignedIntSetCC(CC);
8693 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
8694 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() &&
8695 SetCCWidth != 1 && SetCCWidth < WideWidth &&
8696 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) &&
8697 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
8698 // Both compare operands can be widened for free. The LHS can use an
8699 // extended load, and the RHS is a constant:
8700 // vselect (ext (setcc load(X), C)), N1, N2 -->
8701 // vselect (setcc extload(X), C'), N1, N2
8702 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8703 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
8704 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
8705 EVT WideSetCCVT = getSetCCResultType(WideVT);
8706 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
8707 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
8712 if (SimplifySelectOps(N, N1, N2))
8713 return SDValue(N, 0); // Don't revisit N.
8715 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
8716 if (ISD::isBuildVectorAllOnes(N0.getNode()))
8717 return N1;
8718 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
8719 if (ISD::isBuildVectorAllZeros(N0.getNode()))
8720 return N2;
8722 // The ConvertSelectToConcatVector function is assuming both the above
8723 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
8724 // and addressed.
8725 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8726 N2.getOpcode() == ISD::CONCAT_VECTORS &&
8727 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
8728 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
8729 return CV;
8732 if (SDValue V = foldVSelectOfConstants(N))
8733 return V;
8735 return SDValue();
8738 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
8739 SDValue N0 = N->getOperand(0);
8740 SDValue N1 = N->getOperand(1);
8741 SDValue N2 = N->getOperand(2);
8742 SDValue N3 = N->getOperand(3);
8743 SDValue N4 = N->getOperand(4);
8744 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
8746 // fold select_cc lhs, rhs, x, x, cc -> x
8747 if (N2 == N3)
8748 return N2;
8750 // Determine if the condition we're dealing with is constant
8751 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
8752 CC, SDLoc(N), false)) {
8753 AddToWorklist(SCC.getNode());
8755 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
8756 if (!SCCC->isNullValue())
8757 return N2; // cond always true -> true val
8758 else
8759 return N3; // cond always false -> false val
8760 } else if (SCC->isUndef()) {
8761 // When the condition is UNDEF, just return the first operand. This is
8762 // coherent the DAG creation, no setcc node is created in this case
8763 return N2;
8764 } else if (SCC.getOpcode() == ISD::SETCC) {
8765 // Fold to a simpler select_cc
8766 SDValue SelectOp = DAG.getNode(
8767 ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0),
8768 SCC.getOperand(1), N2, N3, SCC.getOperand(2));
8769 SelectOp->setFlags(SCC->getFlags());
8770 return SelectOp;
8774 // If we can fold this based on the true/false value, do so.
8775 if (SimplifySelectOps(N, N2, N3))
8776 return SDValue(N, 0); // Don't revisit N.
8778 // fold select_cc into other things, such as min/max/abs
8779 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
8782 SDValue DAGCombiner::visitSETCC(SDNode *N) {
8783 // setcc is very commonly used as an argument to brcond. This pattern
8784 // also lend itself to numerous combines and, as a result, it is desired
8785 // we keep the argument to a brcond as a setcc as much as possible.
8786 bool PreferSetCC =
8787 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
8789 SDValue Combined = SimplifySetCC(
8790 N->getValueType(0), N->getOperand(0), N->getOperand(1),
8791 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC);
8793 if (!Combined)
8794 return SDValue();
8796 // If we prefer to have a setcc, and we don't, we'll try our best to
8797 // recreate one using rebuildSetCC.
8798 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
8799 SDValue NewSetCC = rebuildSetCC(Combined);
8801 // We don't have anything interesting to combine to.
8802 if (NewSetCC.getNode() == N)
8803 return SDValue();
8805 if (NewSetCC)
8806 return NewSetCC;
8809 return Combined;
8812 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
8813 SDValue LHS = N->getOperand(0);
8814 SDValue RHS = N->getOperand(1);
8815 SDValue Carry = N->getOperand(2);
8816 SDValue Cond = N->getOperand(3);
8818 // If Carry is false, fold to a regular SETCC.
8819 if (isNullConstant(Carry))
8820 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
8822 return SDValue();
8825 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
8826 /// a build_vector of constants.
8827 /// This function is called by the DAGCombiner when visiting sext/zext/aext
8828 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
8829 /// Vector extends are not folded if operations are legal; this is to
8830 /// avoid introducing illegal build_vector dag nodes.
8831 static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
8832 SelectionDAG &DAG, bool LegalTypes) {
8833 unsigned Opcode = N->getOpcode();
8834 SDValue N0 = N->getOperand(0);
8835 EVT VT = N->getValueType(0);
8836 SDLoc DL(N);
8838 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
8839 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
8840 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
8841 && "Expected EXTEND dag node in input!");
8843 // fold (sext c1) -> c1
8844 // fold (zext c1) -> c1
8845 // fold (aext c1) -> c1
8846 if (isa<ConstantSDNode>(N0))
8847 return DAG.getNode(Opcode, DL, VT, N0);
8849 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
8850 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
8851 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
8852 if (N0->getOpcode() == ISD::SELECT) {
8853 SDValue Op1 = N0->getOperand(1);
8854 SDValue Op2 = N0->getOperand(2);
8855 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
8856 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
8857 // For any_extend, choose sign extension of the constants to allow a
8858 // possible further transform to sign_extend_inreg.i.e.
8860 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
8861 // t2: i64 = any_extend t1
8862 // -->
8863 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
8864 // -->
8865 // t4: i64 = sign_extend_inreg t3
8866 unsigned FoldOpc = Opcode;
8867 if (FoldOpc == ISD::ANY_EXTEND)
8868 FoldOpc = ISD::SIGN_EXTEND;
8869 return DAG.getSelect(DL, VT, N0->getOperand(0),
8870 DAG.getNode(FoldOpc, DL, VT, Op1),
8871 DAG.getNode(FoldOpc, DL, VT, Op2));
8875 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
8876 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
8877 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
8878 EVT SVT = VT.getScalarType();
8879 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
8880 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
8881 return SDValue();
8883 // We can fold this node into a build_vector.
8884 unsigned VTBits = SVT.getSizeInBits();
8885 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
8886 SmallVector<SDValue, 8> Elts;
8887 unsigned NumElts = VT.getVectorNumElements();
8889 // For zero-extensions, UNDEF elements still guarantee to have the upper
8890 // bits set to zero.
8891 bool IsZext =
8892 Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG;
8894 for (unsigned i = 0; i != NumElts; ++i) {
8895 SDValue Op = N0.getOperand(i);
8896 if (Op.isUndef()) {
8897 Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT));
8898 continue;
8901 SDLoc DL(Op);
8902 // Get the constant value and if needed trunc it to the size of the type.
8903 // Nodes like build_vector might have constants wider than the scalar type.
8904 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
8905 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
8906 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
8907 else
8908 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
8911 return DAG.getBuildVector(VT, DL, Elts);
8914 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
8915 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
8916 // transformation. Returns true if extension are possible and the above
8917 // mentioned transformation is profitable.
8918 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
8919 unsigned ExtOpc,
8920 SmallVectorImpl<SDNode *> &ExtendNodes,
8921 const TargetLowering &TLI) {
8922 bool HasCopyToRegUses = false;
8923 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
8924 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
8925 UE = N0.getNode()->use_end();
8926 UI != UE; ++UI) {
8927 SDNode *User = *UI;
8928 if (User == N)
8929 continue;
8930 if (UI.getUse().getResNo() != N0.getResNo())
8931 continue;
8932 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
8933 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
8934 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
8935 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
8936 // Sign bits will be lost after a zext.
8937 return false;
8938 bool Add = false;
8939 for (unsigned i = 0; i != 2; ++i) {
8940 SDValue UseOp = User->getOperand(i);
8941 if (UseOp == N0)
8942 continue;
8943 if (!isa<ConstantSDNode>(UseOp))
8944 return false;
8945 Add = true;
8947 if (Add)
8948 ExtendNodes.push_back(User);
8949 continue;
8951 // If truncates aren't free and there are users we can't
8952 // extend, it isn't worthwhile.
8953 if (!isTruncFree)
8954 return false;
8955 // Remember if this value is live-out.
8956 if (User->getOpcode() == ISD::CopyToReg)
8957 HasCopyToRegUses = true;
8960 if (HasCopyToRegUses) {
8961 bool BothLiveOut = false;
8962 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8963 UI != UE; ++UI) {
8964 SDUse &Use = UI.getUse();
8965 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
8966 BothLiveOut = true;
8967 break;
8970 if (BothLiveOut)
8971 // Both unextended and extended values are live out. There had better be
8972 // a good reason for the transformation.
8973 return ExtendNodes.size();
8975 return true;
8978 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
8979 SDValue OrigLoad, SDValue ExtLoad,
8980 ISD::NodeType ExtType) {
8981 // Extend SetCC uses if necessary.
8982 SDLoc DL(ExtLoad);
8983 for (SDNode *SetCC : SetCCs) {
8984 SmallVector<SDValue, 4> Ops;
8986 for (unsigned j = 0; j != 2; ++j) {
8987 SDValue SOp = SetCC->getOperand(j);
8988 if (SOp == OrigLoad)
8989 Ops.push_back(ExtLoad);
8990 else
8991 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
8994 Ops.push_back(SetCC->getOperand(2));
8995 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
8999 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
9000 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
9001 SDValue N0 = N->getOperand(0);
9002 EVT DstVT = N->getValueType(0);
9003 EVT SrcVT = N0.getValueType();
9005 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
9006 N->getOpcode() == ISD::ZERO_EXTEND) &&
9007 "Unexpected node type (not an extend)!");
9009 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
9010 // For example, on a target with legal v4i32, but illegal v8i32, turn:
9011 // (v8i32 (sext (v8i16 (load x))))
9012 // into:
9013 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9014 // (v4i32 (sextload (x + 16)))))
9015 // Where uses of the original load, i.e.:
9016 // (v8i16 (load x))
9017 // are replaced with:
9018 // (v8i16 (truncate
9019 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9020 // (v4i32 (sextload (x + 16)))))))
9022 // This combine is only applicable to illegal, but splittable, vectors.
9023 // All legal types, and illegal non-vector types, are handled elsewhere.
9024 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
9026 if (N0->getOpcode() != ISD::LOAD)
9027 return SDValue();
9029 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9031 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
9032 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
9033 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
9034 return SDValue();
9036 SmallVector<SDNode *, 4> SetCCs;
9037 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
9038 return SDValue();
9040 ISD::LoadExtType ExtType =
9041 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
9043 // Try to split the vector types to get down to legal types.
9044 EVT SplitSrcVT = SrcVT;
9045 EVT SplitDstVT = DstVT;
9046 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
9047 SplitSrcVT.getVectorNumElements() > 1) {
9048 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
9049 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
9052 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
9053 return SDValue();
9055 SDLoc DL(N);
9056 const unsigned NumSplits =
9057 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
9058 const unsigned Stride = SplitSrcVT.getStoreSize();
9059 SmallVector<SDValue, 4> Loads;
9060 SmallVector<SDValue, 4> Chains;
9062 SDValue BasePtr = LN0->getBasePtr();
9063 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
9064 const unsigned Offset = Idx * Stride;
9065 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
9067 SDValue SplitLoad = DAG.getExtLoad(
9068 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
9069 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
9070 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
9072 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9073 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
9075 Loads.push_back(SplitLoad.getValue(0));
9076 Chains.push_back(SplitLoad.getValue(1));
9079 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9080 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
9082 // Simplify TF.
9083 AddToWorklist(NewChain.getNode());
9085 CombineTo(N, NewValue);
9087 // Replace uses of the original load (before extension)
9088 // with a truncate of the concatenated sextloaded vectors.
9089 SDValue Trunc =
9090 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
9091 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
9092 CombineTo(N0.getNode(), Trunc, NewChain);
9093 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9096 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9097 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9098 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
9099 assert(N->getOpcode() == ISD::ZERO_EXTEND);
9100 EVT VT = N->getValueType(0);
9101 EVT OrigVT = N->getOperand(0).getValueType();
9102 if (TLI.isZExtFree(OrigVT, VT))
9103 return SDValue();
9105 // and/or/xor
9106 SDValue N0 = N->getOperand(0);
9107 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
9108 N0.getOpcode() == ISD::XOR) ||
9109 N0.getOperand(1).getOpcode() != ISD::Constant ||
9110 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
9111 return SDValue();
9113 // shl/shr
9114 SDValue N1 = N0->getOperand(0);
9115 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
9116 N1.getOperand(1).getOpcode() != ISD::Constant ||
9117 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
9118 return SDValue();
9120 // load
9121 if (!isa<LoadSDNode>(N1.getOperand(0)))
9122 return SDValue();
9123 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
9124 EVT MemVT = Load->getMemoryVT();
9125 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
9126 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
9127 return SDValue();
9130 // If the shift op is SHL, the logic op must be AND, otherwise the result
9131 // will be wrong.
9132 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
9133 return SDValue();
9135 if (!N0.hasOneUse() || !N1.hasOneUse())
9136 return SDValue();
9138 SmallVector<SDNode*, 4> SetCCs;
9139 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
9140 ISD::ZERO_EXTEND, SetCCs, TLI))
9141 return SDValue();
9143 // Actually do the transformation.
9144 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
9145 Load->getChain(), Load->getBasePtr(),
9146 Load->getMemoryVT(), Load->getMemOperand());
9148 SDLoc DL1(N1);
9149 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
9150 N1.getOperand(1));
9152 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9153 Mask = Mask.zext(VT.getSizeInBits());
9154 SDLoc DL0(N0);
9155 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
9156 DAG.getConstant(Mask, DL0, VT));
9158 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
9159 CombineTo(N, And);
9160 if (SDValue(Load, 0).hasOneUse()) {
9161 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
9162 } else {
9163 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
9164 Load->getValueType(0), ExtLoad);
9165 CombineTo(Load, Trunc, ExtLoad.getValue(1));
9168 // N0 is dead at this point.
9169 recursivelyDeleteUnusedNodes(N0.getNode());
9171 return SDValue(N,0); // Return N so it doesn't get rechecked!
9174 /// If we're narrowing or widening the result of a vector select and the final
9175 /// size is the same size as a setcc (compare) feeding the select, then try to
9176 /// apply the cast operation to the select's operands because matching vector
9177 /// sizes for a select condition and other operands should be more efficient.
9178 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
9179 unsigned CastOpcode = Cast->getOpcode();
9180 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
9181 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
9182 CastOpcode == ISD::FP_ROUND) &&
9183 "Unexpected opcode for vector select narrowing/widening");
9185 // We only do this transform before legal ops because the pattern may be
9186 // obfuscated by target-specific operations after legalization. Do not create
9187 // an illegal select op, however, because that may be difficult to lower.
9188 EVT VT = Cast->getValueType(0);
9189 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
9190 return SDValue();
9192 SDValue VSel = Cast->getOperand(0);
9193 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
9194 VSel.getOperand(0).getOpcode() != ISD::SETCC)
9195 return SDValue();
9197 // Does the setcc have the same vector size as the casted select?
9198 SDValue SetCC = VSel.getOperand(0);
9199 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
9200 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
9201 return SDValue();
9203 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
9204 SDValue A = VSel.getOperand(1);
9205 SDValue B = VSel.getOperand(2);
9206 SDValue CastA, CastB;
9207 SDLoc DL(Cast);
9208 if (CastOpcode == ISD::FP_ROUND) {
9209 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
9210 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
9211 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
9212 } else {
9213 CastA = DAG.getNode(CastOpcode, DL, VT, A);
9214 CastB = DAG.getNode(CastOpcode, DL, VT, B);
9216 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
9219 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9220 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9221 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
9222 const TargetLowering &TLI, EVT VT,
9223 bool LegalOperations, SDNode *N,
9224 SDValue N0, ISD::LoadExtType ExtLoadType) {
9225 SDNode *N0Node = N0.getNode();
9226 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
9227 : ISD::isZEXTLoad(N0Node);
9228 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
9229 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
9230 return SDValue();
9232 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9233 EVT MemVT = LN0->getMemoryVT();
9234 if ((LegalOperations || LN0->isVolatile() || VT.isVector()) &&
9235 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
9236 return SDValue();
9238 SDValue ExtLoad =
9239 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
9240 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
9241 Combiner.CombineTo(N, ExtLoad);
9242 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9243 if (LN0->use_empty())
9244 Combiner.recursivelyDeleteUnusedNodes(LN0);
9245 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9248 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9249 // Only generate vector extloads when 1) they're legal, and 2) they are
9250 // deemed desirable by the target.
9251 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
9252 const TargetLowering &TLI, EVT VT,
9253 bool LegalOperations, SDNode *N, SDValue N0,
9254 ISD::LoadExtType ExtLoadType,
9255 ISD::NodeType ExtOpc) {
9256 if (!ISD::isNON_EXTLoad(N0.getNode()) ||
9257 !ISD::isUNINDEXEDLoad(N0.getNode()) ||
9258 ((LegalOperations || VT.isVector() ||
9259 cast<LoadSDNode>(N0)->isVolatile()) &&
9260 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
9261 return {};
9263 bool DoXform = true;
9264 SmallVector<SDNode *, 4> SetCCs;
9265 if (!N0.hasOneUse())
9266 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
9267 if (VT.isVector())
9268 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
9269 if (!DoXform)
9270 return {};
9272 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9273 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
9274 LN0->getBasePtr(), N0.getValueType(),
9275 LN0->getMemOperand());
9276 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
9277 // If the load value is used only by N, replace it via CombineTo N.
9278 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
9279 Combiner.CombineTo(N, ExtLoad);
9280 if (NoReplaceTrunc) {
9281 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9282 Combiner.recursivelyDeleteUnusedNodes(LN0);
9283 } else {
9284 SDValue Trunc =
9285 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
9286 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
9288 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9291 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG,
9292 bool LegalOperations) {
9293 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
9294 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
9296 SDValue SetCC = N->getOperand(0);
9297 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
9298 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
9299 return SDValue();
9301 SDValue X = SetCC.getOperand(0);
9302 SDValue Ones = SetCC.getOperand(1);
9303 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
9304 EVT VT = N->getValueType(0);
9305 EVT XVT = X.getValueType();
9306 // setge X, C is canonicalized to setgt, so we do not need to match that
9307 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
9308 // not require the 'not' op.
9309 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
9310 // Invert and smear/shift the sign bit:
9311 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
9312 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
9313 SDLoc DL(N);
9314 SDValue NotX = DAG.getNOT(DL, X, VT);
9315 SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT);
9316 auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
9317 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
9319 return SDValue();
9322 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
9323 SDValue N0 = N->getOperand(0);
9324 EVT VT = N->getValueType(0);
9325 SDLoc DL(N);
9327 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
9328 return Res;
9330 // fold (sext (sext x)) -> (sext x)
9331 // fold (sext (aext x)) -> (sext x)
9332 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
9333 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
9335 if (N0.getOpcode() == ISD::TRUNCATE) {
9336 // fold (sext (truncate (load x))) -> (sext (smaller load x))
9337 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
9338 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
9339 SDNode *oye = N0.getOperand(0).getNode();
9340 if (NarrowLoad.getNode() != N0.getNode()) {
9341 CombineTo(N0.getNode(), NarrowLoad);
9342 // CombineTo deleted the truncate, if needed, but not what's under it.
9343 AddToWorklist(oye);
9345 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9348 // See if the value being truncated is already sign extended. If so, just
9349 // eliminate the trunc/sext pair.
9350 SDValue Op = N0.getOperand(0);
9351 unsigned OpBits = Op.getScalarValueSizeInBits();
9352 unsigned MidBits = N0.getScalarValueSizeInBits();
9353 unsigned DestBits = VT.getScalarSizeInBits();
9354 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
9356 if (OpBits == DestBits) {
9357 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9358 // bits, it is already ready.
9359 if (NumSignBits > DestBits-MidBits)
9360 return Op;
9361 } else if (OpBits < DestBits) {
9362 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9363 // bits, just sext from i32.
9364 if (NumSignBits > OpBits-MidBits)
9365 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
9366 } else {
9367 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9368 // bits, just truncate to i32.
9369 if (NumSignBits > OpBits-MidBits)
9370 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
9373 // fold (sext (truncate x)) -> (sextinreg x).
9374 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
9375 N0.getValueType())) {
9376 if (OpBits < DestBits)
9377 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
9378 else if (OpBits > DestBits)
9379 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
9380 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
9381 DAG.getValueType(N0.getValueType()));
9385 // Try to simplify (sext (load x)).
9386 if (SDValue foldedExt =
9387 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
9388 ISD::SEXTLOAD, ISD::SIGN_EXTEND))
9389 return foldedExt;
9391 // fold (sext (load x)) to multiple smaller sextloads.
9392 // Only on illegal but splittable vectors.
9393 if (SDValue ExtLoad = CombineExtLoad(N))
9394 return ExtLoad;
9396 // Try to simplify (sext (sextload x)).
9397 if (SDValue foldedExt = tryToFoldExtOfExtload(
9398 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
9399 return foldedExt;
9401 // fold (sext (and/or/xor (load x), cst)) ->
9402 // (and/or/xor (sextload x), (sext cst))
9403 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
9404 N0.getOpcode() == ISD::XOR) &&
9405 isa<LoadSDNode>(N0.getOperand(0)) &&
9406 N0.getOperand(1).getOpcode() == ISD::Constant &&
9407 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
9408 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
9409 EVT MemVT = LN00->getMemoryVT();
9410 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
9411 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
9412 SmallVector<SDNode*, 4> SetCCs;
9413 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
9414 ISD::SIGN_EXTEND, SetCCs, TLI);
9415 if (DoXform) {
9416 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
9417 LN00->getChain(), LN00->getBasePtr(),
9418 LN00->getMemoryVT(),
9419 LN00->getMemOperand());
9420 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9421 Mask = Mask.sext(VT.getSizeInBits());
9422 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
9423 ExtLoad, DAG.getConstant(Mask, DL, VT));
9424 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
9425 bool NoReplaceTruncAnd = !N0.hasOneUse();
9426 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
9427 CombineTo(N, And);
9428 // If N0 has multiple uses, change other uses as well.
9429 if (NoReplaceTruncAnd) {
9430 SDValue TruncAnd =
9431 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
9432 CombineTo(N0.getNode(), TruncAnd);
9434 if (NoReplaceTrunc) {
9435 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
9436 } else {
9437 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
9438 LN00->getValueType(0), ExtLoad);
9439 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
9441 return SDValue(N,0); // Return N so it doesn't get rechecked!
9446 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
9447 return V;
9449 if (N0.getOpcode() == ISD::SETCC) {
9450 SDValue N00 = N0.getOperand(0);
9451 SDValue N01 = N0.getOperand(1);
9452 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
9453 EVT N00VT = N0.getOperand(0).getValueType();
9455 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
9456 // Only do this before legalize for now.
9457 if (VT.isVector() && !LegalOperations &&
9458 TLI.getBooleanContents(N00VT) ==
9459 TargetLowering::ZeroOrNegativeOneBooleanContent) {
9460 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
9461 // of the same size as the compared operands. Only optimize sext(setcc())
9462 // if this is the case.
9463 EVT SVT = getSetCCResultType(N00VT);
9465 // If we already have the desired type, don't change it.
9466 if (SVT != N0.getValueType()) {
9467 // We know that the # elements of the results is the same as the
9468 // # elements of the compare (and the # elements of the compare result
9469 // for that matter). Check to see that they are the same size. If so,
9470 // we know that the element size of the sext'd result matches the
9471 // element size of the compare operands.
9472 if (VT.getSizeInBits() == SVT.getSizeInBits())
9473 return DAG.getSetCC(DL, VT, N00, N01, CC);
9475 // If the desired elements are smaller or larger than the source
9476 // elements, we can use a matching integer vector type and then
9477 // truncate/sign extend.
9478 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
9479 if (SVT == MatchingVecType) {
9480 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
9481 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
9486 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
9487 // Here, T can be 1 or -1, depending on the type of the setcc and
9488 // getBooleanContents().
9489 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
9491 // To determine the "true" side of the select, we need to know the high bit
9492 // of the value returned by the setcc if it evaluates to true.
9493 // If the type of the setcc is i1, then the true case of the select is just
9494 // sext(i1 1), that is, -1.
9495 // If the type of the setcc is larger (say, i8) then the value of the high
9496 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
9497 // of the appropriate width.
9498 SDValue ExtTrueVal = (SetCCWidth == 1)
9499 ? DAG.getAllOnesConstant(DL, VT)
9500 : DAG.getBoolConstant(true, DL, VT, N00VT);
9501 SDValue Zero = DAG.getConstant(0, DL, VT);
9502 if (SDValue SCC =
9503 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
9504 return SCC;
9506 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
9507 EVT SetCCVT = getSetCCResultType(N00VT);
9508 // Don't do this transform for i1 because there's a select transform
9509 // that would reverse it.
9510 // TODO: We should not do this transform at all without a target hook
9511 // because a sext is likely cheaper than a select?
9512 if (SetCCVT.getScalarSizeInBits() != 1 &&
9513 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
9514 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
9515 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
9520 // fold (sext x) -> (zext x) if the sign bit is known zero.
9521 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
9522 DAG.SignBitIsZero(N0))
9523 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
9525 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
9526 return NewVSel;
9528 // Eliminate this sign extend by doing a negation in the destination type:
9529 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
9530 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
9531 isNullOrNullSplat(N0.getOperand(0)) &&
9532 N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND &&
9533 TLI.isOperationLegalOrCustom(ISD::SUB, VT)) {
9534 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
9535 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext);
9537 // Eliminate this sign extend by doing a decrement in the destination type:
9538 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
9539 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
9540 isAllOnesOrAllOnesSplat(N0.getOperand(1)) &&
9541 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
9542 TLI.isOperationLegalOrCustom(ISD::ADD, VT)) {
9543 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
9544 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
9547 return SDValue();
9550 // isTruncateOf - If N is a truncate of some other value, return true, record
9551 // the value being truncated in Op and which of Op's bits are zero/one in Known.
9552 // This function computes KnownBits to avoid a duplicated call to
9553 // computeKnownBits in the caller.
9554 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
9555 KnownBits &Known) {
9556 if (N->getOpcode() == ISD::TRUNCATE) {
9557 Op = N->getOperand(0);
9558 Known = DAG.computeKnownBits(Op);
9559 return true;
9562 if (N.getOpcode() != ISD::SETCC ||
9563 N.getValueType().getScalarType() != MVT::i1 ||
9564 cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE)
9565 return false;
9567 SDValue Op0 = N->getOperand(0);
9568 SDValue Op1 = N->getOperand(1);
9569 assert(Op0.getValueType() == Op1.getValueType());
9571 if (isNullOrNullSplat(Op0))
9572 Op = Op1;
9573 else if (isNullOrNullSplat(Op1))
9574 Op = Op0;
9575 else
9576 return false;
9578 Known = DAG.computeKnownBits(Op);
9580 return (Known.Zero | 1).isAllOnesValue();
9583 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
9584 SDValue N0 = N->getOperand(0);
9585 EVT VT = N->getValueType(0);
9587 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
9588 return Res;
9590 // fold (zext (zext x)) -> (zext x)
9591 // fold (zext (aext x)) -> (zext x)
9592 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
9593 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
9594 N0.getOperand(0));
9596 // fold (zext (truncate x)) -> (zext x) or
9597 // (zext (truncate x)) -> (truncate x)
9598 // This is valid when the truncated bits of x are already zero.
9599 SDValue Op;
9600 KnownBits Known;
9601 if (isTruncateOf(DAG, N0, Op, Known)) {
9602 APInt TruncatedBits =
9603 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
9604 APInt(Op.getScalarValueSizeInBits(), 0) :
9605 APInt::getBitsSet(Op.getScalarValueSizeInBits(),
9606 N0.getScalarValueSizeInBits(),
9607 std::min(Op.getScalarValueSizeInBits(),
9608 VT.getScalarSizeInBits()));
9609 if (TruncatedBits.isSubsetOf(Known.Zero))
9610 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
9613 // fold (zext (truncate x)) -> (and x, mask)
9614 if (N0.getOpcode() == ISD::TRUNCATE) {
9615 // fold (zext (truncate (load x))) -> (zext (smaller load x))
9616 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
9617 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
9618 SDNode *oye = N0.getOperand(0).getNode();
9619 if (NarrowLoad.getNode() != N0.getNode()) {
9620 CombineTo(N0.getNode(), NarrowLoad);
9621 // CombineTo deleted the truncate, if needed, but not what's under it.
9622 AddToWorklist(oye);
9624 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9627 EVT SrcVT = N0.getOperand(0).getValueType();
9628 EVT MinVT = N0.getValueType();
9630 // Try to mask before the extension to avoid having to generate a larger mask,
9631 // possibly over several sub-vectors.
9632 if (SrcVT.bitsLT(VT) && VT.isVector()) {
9633 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
9634 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
9635 SDValue Op = N0.getOperand(0);
9636 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
9637 AddToWorklist(Op.getNode());
9638 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
9639 // Transfer the debug info; the new node is equivalent to N0.
9640 DAG.transferDbgValues(N0, ZExtOrTrunc);
9641 return ZExtOrTrunc;
9645 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
9646 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
9647 AddToWorklist(Op.getNode());
9648 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
9649 // We may safely transfer the debug info describing the truncate node over
9650 // to the equivalent and operation.
9651 DAG.transferDbgValues(N0, And);
9652 return And;
9656 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
9657 // if either of the casts is not free.
9658 if (N0.getOpcode() == ISD::AND &&
9659 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
9660 N0.getOperand(1).getOpcode() == ISD::Constant &&
9661 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
9662 N0.getValueType()) ||
9663 !TLI.isZExtFree(N0.getValueType(), VT))) {
9664 SDValue X = N0.getOperand(0).getOperand(0);
9665 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
9666 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9667 Mask = Mask.zext(VT.getSizeInBits());
9668 SDLoc DL(N);
9669 return DAG.getNode(ISD::AND, DL, VT,
9670 X, DAG.getConstant(Mask, DL, VT));
9673 // Try to simplify (zext (load x)).
9674 if (SDValue foldedExt =
9675 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
9676 ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
9677 return foldedExt;
9679 // fold (zext (load x)) to multiple smaller zextloads.
9680 // Only on illegal but splittable vectors.
9681 if (SDValue ExtLoad = CombineExtLoad(N))
9682 return ExtLoad;
9684 // fold (zext (and/or/xor (load x), cst)) ->
9685 // (and/or/xor (zextload x), (zext cst))
9686 // Unless (and (load x) cst) will match as a zextload already and has
9687 // additional users.
9688 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
9689 N0.getOpcode() == ISD::XOR) &&
9690 isa<LoadSDNode>(N0.getOperand(0)) &&
9691 N0.getOperand(1).getOpcode() == ISD::Constant &&
9692 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
9693 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
9694 EVT MemVT = LN00->getMemoryVT();
9695 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
9696 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
9697 bool DoXform = true;
9698 SmallVector<SDNode*, 4> SetCCs;
9699 if (!N0.hasOneUse()) {
9700 if (N0.getOpcode() == ISD::AND) {
9701 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
9702 EVT LoadResultTy = AndC->getValueType(0);
9703 EVT ExtVT;
9704 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
9705 DoXform = false;
9708 if (DoXform)
9709 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
9710 ISD::ZERO_EXTEND, SetCCs, TLI);
9711 if (DoXform) {
9712 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
9713 LN00->getChain(), LN00->getBasePtr(),
9714 LN00->getMemoryVT(),
9715 LN00->getMemOperand());
9716 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9717 Mask = Mask.zext(VT.getSizeInBits());
9718 SDLoc DL(N);
9719 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
9720 ExtLoad, DAG.getConstant(Mask, DL, VT));
9721 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
9722 bool NoReplaceTruncAnd = !N0.hasOneUse();
9723 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
9724 CombineTo(N, And);
9725 // If N0 has multiple uses, change other uses as well.
9726 if (NoReplaceTruncAnd) {
9727 SDValue TruncAnd =
9728 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
9729 CombineTo(N0.getNode(), TruncAnd);
9731 if (NoReplaceTrunc) {
9732 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
9733 } else {
9734 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
9735 LN00->getValueType(0), ExtLoad);
9736 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
9738 return SDValue(N,0); // Return N so it doesn't get rechecked!
9743 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9744 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9745 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
9746 return ZExtLoad;
9748 // Try to simplify (zext (zextload x)).
9749 if (SDValue foldedExt = tryToFoldExtOfExtload(
9750 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
9751 return foldedExt;
9753 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
9754 return V;
9756 if (N0.getOpcode() == ISD::SETCC) {
9757 // Only do this before legalize for now.
9758 if (!LegalOperations && VT.isVector() &&
9759 N0.getValueType().getVectorElementType() == MVT::i1) {
9760 EVT N00VT = N0.getOperand(0).getValueType();
9761 if (getSetCCResultType(N00VT) == N0.getValueType())
9762 return SDValue();
9764 // We know that the # elements of the results is the same as the #
9765 // elements of the compare (and the # elements of the compare result for
9766 // that matter). Check to see that they are the same size. If so, we know
9767 // that the element size of the sext'd result matches the element size of
9768 // the compare operands.
9769 SDLoc DL(N);
9770 SDValue VecOnes = DAG.getConstant(1, DL, VT);
9771 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
9772 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
9773 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
9774 N0.getOperand(1), N0.getOperand(2));
9775 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
9778 // If the desired elements are smaller or larger than the source
9779 // elements we can use a matching integer vector type and then
9780 // truncate/sign extend.
9781 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
9782 SDValue VsetCC =
9783 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
9784 N0.getOperand(1), N0.getOperand(2));
9785 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
9786 VecOnes);
9789 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
9790 SDLoc DL(N);
9791 if (SDValue SCC = SimplifySelectCC(
9792 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
9793 DAG.getConstant(0, DL, VT),
9794 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
9795 return SCC;
9798 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
9799 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
9800 isa<ConstantSDNode>(N0.getOperand(1)) &&
9801 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
9802 N0.hasOneUse()) {
9803 SDValue ShAmt = N0.getOperand(1);
9804 if (N0.getOpcode() == ISD::SHL) {
9805 SDValue InnerZExt = N0.getOperand(0);
9806 // If the original shl may be shifting out bits, do not perform this
9807 // transformation.
9808 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
9809 InnerZExt.getOperand(0).getValueSizeInBits();
9810 if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits))
9811 return SDValue();
9814 SDLoc DL(N);
9816 // Ensure that the shift amount is wide enough for the shifted value.
9817 if (VT.getSizeInBits() >= 256)
9818 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
9820 return DAG.getNode(N0.getOpcode(), DL, VT,
9821 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
9822 ShAmt);
9825 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
9826 return NewVSel;
9828 return SDValue();
9831 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
9832 SDValue N0 = N->getOperand(0);
9833 EVT VT = N->getValueType(0);
9835 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
9836 return Res;
9838 // fold (aext (aext x)) -> (aext x)
9839 // fold (aext (zext x)) -> (zext x)
9840 // fold (aext (sext x)) -> (sext x)
9841 if (N0.getOpcode() == ISD::ANY_EXTEND ||
9842 N0.getOpcode() == ISD::ZERO_EXTEND ||
9843 N0.getOpcode() == ISD::SIGN_EXTEND)
9844 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
9846 // fold (aext (truncate (load x))) -> (aext (smaller load x))
9847 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
9848 if (N0.getOpcode() == ISD::TRUNCATE) {
9849 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
9850 SDNode *oye = N0.getOperand(0).getNode();
9851 if (NarrowLoad.getNode() != N0.getNode()) {
9852 CombineTo(N0.getNode(), NarrowLoad);
9853 // CombineTo deleted the truncate, if needed, but not what's under it.
9854 AddToWorklist(oye);
9856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9860 // fold (aext (truncate x))
9861 if (N0.getOpcode() == ISD::TRUNCATE)
9862 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
9864 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
9865 // if the trunc is not free.
9866 if (N0.getOpcode() == ISD::AND &&
9867 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
9868 N0.getOperand(1).getOpcode() == ISD::Constant &&
9869 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
9870 N0.getValueType())) {
9871 SDLoc DL(N);
9872 SDValue X = N0.getOperand(0).getOperand(0);
9873 X = DAG.getAnyExtOrTrunc(X, DL, VT);
9874 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9875 Mask = Mask.zext(VT.getSizeInBits());
9876 return DAG.getNode(ISD::AND, DL, VT,
9877 X, DAG.getConstant(Mask, DL, VT));
9880 // fold (aext (load x)) -> (aext (truncate (extload x)))
9881 // None of the supported targets knows how to perform load and any_ext
9882 // on vectors in one instruction. We only perform this transformation on
9883 // scalars.
9884 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
9885 ISD::isUNINDEXEDLoad(N0.getNode()) &&
9886 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9887 bool DoXform = true;
9888 SmallVector<SDNode*, 4> SetCCs;
9889 if (!N0.hasOneUse())
9890 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs,
9891 TLI);
9892 if (DoXform) {
9893 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9894 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9895 LN0->getChain(),
9896 LN0->getBasePtr(), N0.getValueType(),
9897 LN0->getMemOperand());
9898 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
9899 // If the load value is used only by N, replace it via CombineTo N.
9900 bool NoReplaceTrunc = N0.hasOneUse();
9901 CombineTo(N, ExtLoad);
9902 if (NoReplaceTrunc) {
9903 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9904 recursivelyDeleteUnusedNodes(LN0);
9905 } else {
9906 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
9907 N0.getValueType(), ExtLoad);
9908 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
9910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9914 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
9915 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
9916 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
9917 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
9918 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
9919 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9920 ISD::LoadExtType ExtType = LN0->getExtensionType();
9921 EVT MemVT = LN0->getMemoryVT();
9922 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
9923 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
9924 VT, LN0->getChain(), LN0->getBasePtr(),
9925 MemVT, LN0->getMemOperand());
9926 CombineTo(N, ExtLoad);
9927 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9928 recursivelyDeleteUnusedNodes(LN0);
9929 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9933 if (N0.getOpcode() == ISD::SETCC) {
9934 // For vectors:
9935 // aext(setcc) -> vsetcc
9936 // aext(setcc) -> truncate(vsetcc)
9937 // aext(setcc) -> aext(vsetcc)
9938 // Only do this before legalize for now.
9939 if (VT.isVector() && !LegalOperations) {
9940 EVT N00VT = N0.getOperand(0).getValueType();
9941 if (getSetCCResultType(N00VT) == N0.getValueType())
9942 return SDValue();
9944 // We know that the # elements of the results is the same as the
9945 // # elements of the compare (and the # elements of the compare result
9946 // for that matter). Check to see that they are the same size. If so,
9947 // we know that the element size of the sext'd result matches the
9948 // element size of the compare operands.
9949 if (VT.getSizeInBits() == N00VT.getSizeInBits())
9950 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
9951 N0.getOperand(1),
9952 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9954 // If the desired elements are smaller or larger than the source
9955 // elements we can use a matching integer vector type and then
9956 // truncate/any extend
9957 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
9958 SDValue VsetCC =
9959 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
9960 N0.getOperand(1),
9961 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9962 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
9965 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
9966 SDLoc DL(N);
9967 if (SDValue SCC = SimplifySelectCC(
9968 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
9969 DAG.getConstant(0, DL, VT),
9970 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
9971 return SCC;
9974 return SDValue();
9977 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
9978 unsigned Opcode = N->getOpcode();
9979 SDValue N0 = N->getOperand(0);
9980 SDValue N1 = N->getOperand(1);
9981 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
9983 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
9984 if (N0.getOpcode() == Opcode &&
9985 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
9986 return N0;
9988 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
9989 N0.getOperand(0).getOpcode() == Opcode) {
9990 // We have an assert, truncate, assert sandwich. Make one stronger assert
9991 // by asserting on the smallest asserted type to the larger source type.
9992 // This eliminates the later assert:
9993 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
9994 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
9995 SDValue BigA = N0.getOperand(0);
9996 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
9997 assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
9998 "Asserting zero/sign-extended bits to a type larger than the "
9999 "truncated destination does not provide information");
10001 SDLoc DL(N);
10002 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
10003 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
10004 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
10005 BigA.getOperand(0), MinAssertVTVal);
10006 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
10009 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
10010 // than X. Just move the AssertZext in front of the truncate and drop the
10011 // AssertSExt.
10012 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
10013 N0.getOperand(0).getOpcode() == ISD::AssertSext &&
10014 Opcode == ISD::AssertZext) {
10015 SDValue BigA = N0.getOperand(0);
10016 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
10017 assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
10018 "Asserting zero/sign-extended bits to a type larger than the "
10019 "truncated destination does not provide information");
10021 if (AssertVT.bitsLT(BigA_AssertVT)) {
10022 SDLoc DL(N);
10023 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
10024 BigA.getOperand(0), N1);
10025 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
10029 return SDValue();
10032 /// If the result of a wider load is shifted to right of N bits and then
10033 /// truncated to a narrower type and where N is a multiple of number of bits of
10034 /// the narrower type, transform it to a narrower load from address + N / num of
10035 /// bits of new type. Also narrow the load if the result is masked with an AND
10036 /// to effectively produce a smaller type. If the result is to be extended, also
10037 /// fold the extension to form a extending load.
10038 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
10039 unsigned Opc = N->getOpcode();
10041 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
10042 SDValue N0 = N->getOperand(0);
10043 EVT VT = N->getValueType(0);
10044 EVT ExtVT = VT;
10046 // This transformation isn't valid for vector loads.
10047 if (VT.isVector())
10048 return SDValue();
10050 unsigned ShAmt = 0;
10051 bool HasShiftedOffset = false;
10052 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
10053 // extended to VT.
10054 if (Opc == ISD::SIGN_EXTEND_INREG) {
10055 ExtType = ISD::SEXTLOAD;
10056 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10057 } else if (Opc == ISD::SRL) {
10058 // Another special-case: SRL is basically zero-extending a narrower value,
10059 // or it maybe shifting a higher subword, half or byte into the lowest
10060 // bits.
10061 ExtType = ISD::ZEXTLOAD;
10062 N0 = SDValue(N, 0);
10064 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
10065 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10066 if (!N01 || !LN0)
10067 return SDValue();
10069 uint64_t ShiftAmt = N01->getZExtValue();
10070 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
10071 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
10072 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
10073 else
10074 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
10075 VT.getSizeInBits() - ShiftAmt);
10076 } else if (Opc == ISD::AND) {
10077 // An AND with a constant mask is the same as a truncate + zero-extend.
10078 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
10079 if (!AndC)
10080 return SDValue();
10082 const APInt &Mask = AndC->getAPIntValue();
10083 unsigned ActiveBits = 0;
10084 if (Mask.isMask()) {
10085 ActiveBits = Mask.countTrailingOnes();
10086 } else if (Mask.isShiftedMask()) {
10087 ShAmt = Mask.countTrailingZeros();
10088 APInt ShiftedMask = Mask.lshr(ShAmt);
10089 ActiveBits = ShiftedMask.countTrailingOnes();
10090 HasShiftedOffset = true;
10091 } else
10092 return SDValue();
10094 ExtType = ISD::ZEXTLOAD;
10095 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
10098 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
10099 SDValue SRL = N0;
10100 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) {
10101 ShAmt = ConstShift->getZExtValue();
10102 unsigned EVTBits = ExtVT.getSizeInBits();
10103 // Is the shift amount a multiple of size of VT?
10104 if ((ShAmt & (EVTBits-1)) == 0) {
10105 N0 = N0.getOperand(0);
10106 // Is the load width a multiple of size of VT?
10107 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
10108 return SDValue();
10111 // At this point, we must have a load or else we can't do the transform.
10112 if (!isa<LoadSDNode>(N0)) return SDValue();
10114 auto *LN0 = cast<LoadSDNode>(N0);
10116 // Because a SRL must be assumed to *need* to zero-extend the high bits
10117 // (as opposed to anyext the high bits), we can't combine the zextload
10118 // lowering of SRL and an sextload.
10119 if (LN0->getExtensionType() == ISD::SEXTLOAD)
10120 return SDValue();
10122 // If the shift amount is larger than the input type then we're not
10123 // accessing any of the loaded bytes. If the load was a zextload/extload
10124 // then the result of the shift+trunc is zero/undef (handled elsewhere).
10125 if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
10126 return SDValue();
10128 // If the SRL is only used by a masking AND, we may be able to adjust
10129 // the ExtVT to make the AND redundant.
10130 SDNode *Mask = *(SRL->use_begin());
10131 if (Mask->getOpcode() == ISD::AND &&
10132 isa<ConstantSDNode>(Mask->getOperand(1))) {
10133 const APInt &ShiftMask =
10134 cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue();
10135 if (ShiftMask.isMask()) {
10136 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
10137 ShiftMask.countTrailingOnes());
10138 // If the mask is smaller, recompute the type.
10139 if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) &&
10140 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT))
10141 ExtVT = MaskedVT;
10147 // If the load is shifted left (and the result isn't shifted back right),
10148 // we can fold the truncate through the shift.
10149 unsigned ShLeftAmt = 0;
10150 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
10151 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
10152 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
10153 ShLeftAmt = N01->getZExtValue();
10154 N0 = N0.getOperand(0);
10158 // If we haven't found a load, we can't narrow it.
10159 if (!isa<LoadSDNode>(N0))
10160 return SDValue();
10162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10163 if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
10164 return SDValue();
10166 auto AdjustBigEndianShift = [&](unsigned ShAmt) {
10167 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
10168 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
10169 return LVTStoreBits - EVTStoreBits - ShAmt;
10172 // For big endian targets, we need to adjust the offset to the pointer to
10173 // load the correct bytes.
10174 if (DAG.getDataLayout().isBigEndian())
10175 ShAmt = AdjustBigEndianShift(ShAmt);
10177 EVT PtrType = N0.getOperand(1).getValueType();
10178 uint64_t PtrOff = ShAmt / 8;
10179 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
10180 SDLoc DL(LN0);
10181 // The original load itself didn't wrap, so an offset within it doesn't.
10182 SDNodeFlags Flags;
10183 Flags.setNoUnsignedWrap(true);
10184 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
10185 PtrType, LN0->getBasePtr(),
10186 DAG.getConstant(PtrOff, DL, PtrType),
10187 Flags);
10188 AddToWorklist(NewPtr.getNode());
10190 SDValue Load;
10191 if (ExtType == ISD::NON_EXTLOAD)
10192 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
10193 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
10194 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
10195 else
10196 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
10197 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
10198 NewAlign, LN0->getMemOperand()->getFlags(),
10199 LN0->getAAInfo());
10201 // Replace the old load's chain with the new load's chain.
10202 WorklistRemover DeadNodes(*this);
10203 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
10205 // Shift the result left, if we've swallowed a left shift.
10206 SDValue Result = Load;
10207 if (ShLeftAmt != 0) {
10208 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
10209 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
10210 ShImmTy = VT;
10211 // If the shift amount is as large as the result size (but, presumably,
10212 // no larger than the source) then the useful bits of the result are
10213 // zero; we can't simply return the shortened shift, because the result
10214 // of that operation is undefined.
10215 SDLoc DL(N0);
10216 if (ShLeftAmt >= VT.getSizeInBits())
10217 Result = DAG.getConstant(0, DL, VT);
10218 else
10219 Result = DAG.getNode(ISD::SHL, DL, VT,
10220 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
10223 if (HasShiftedOffset) {
10224 // Recalculate the shift amount after it has been altered to calculate
10225 // the offset.
10226 if (DAG.getDataLayout().isBigEndian())
10227 ShAmt = AdjustBigEndianShift(ShAmt);
10229 // We're using a shifted mask, so the load now has an offset. This means
10230 // that data has been loaded into the lower bytes than it would have been
10231 // before, so we need to shl the loaded data into the correct position in the
10232 // register.
10233 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT);
10234 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
10235 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
10238 // Return the new loaded value.
10239 return Result;
10242 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
10243 SDValue N0 = N->getOperand(0);
10244 SDValue N1 = N->getOperand(1);
10245 EVT VT = N->getValueType(0);
10246 EVT EVT = cast<VTSDNode>(N1)->getVT();
10247 unsigned VTBits = VT.getScalarSizeInBits();
10248 unsigned EVTBits = EVT.getScalarSizeInBits();
10250 if (N0.isUndef())
10251 return DAG.getUNDEF(VT);
10253 // fold (sext_in_reg c1) -> c1
10254 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
10255 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
10257 // If the input is already sign extended, just drop the extension.
10258 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
10259 return N0;
10261 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
10262 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
10263 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
10264 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
10265 N0.getOperand(0), N1);
10267 // fold (sext_in_reg (sext x)) -> (sext x)
10268 // fold (sext_in_reg (aext x)) -> (sext x)
10269 // if x is small enough or if we know that x has more than 1 sign bit and the
10270 // sign_extend_inreg is extending from one of them.
10271 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
10272 SDValue N00 = N0.getOperand(0);
10273 unsigned N00Bits = N00.getScalarValueSizeInBits();
10274 if ((N00Bits <= EVTBits ||
10275 (N00Bits - DAG.ComputeNumSignBits(N00)) < EVTBits) &&
10276 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
10277 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00);
10280 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
10281 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
10282 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
10283 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
10284 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
10285 if (!LegalOperations ||
10286 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
10287 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT,
10288 N0.getOperand(0));
10291 // fold (sext_in_reg (zext x)) -> (sext x)
10292 // iff we are extending the source sign bit.
10293 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
10294 SDValue N00 = N0.getOperand(0);
10295 if (N00.getScalarValueSizeInBits() == EVTBits &&
10296 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
10297 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
10300 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
10301 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
10302 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
10304 // fold operands of sext_in_reg based on knowledge that the top bits are not
10305 // demanded.
10306 if (SimplifyDemandedBits(SDValue(N, 0)))
10307 return SDValue(N, 0);
10309 // fold (sext_in_reg (load x)) -> (smaller sextload x)
10310 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
10311 if (SDValue NarrowLoad = ReduceLoadWidth(N))
10312 return NarrowLoad;
10314 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
10315 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
10316 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
10317 if (N0.getOpcode() == ISD::SRL) {
10318 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
10319 if (ShAmt->getAPIntValue().ule(VTBits - EVTBits)) {
10320 // We can turn this into an SRA iff the input to the SRL is already sign
10321 // extended enough.
10322 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
10323 if (((VTBits - EVTBits) - ShAmt->getZExtValue()) < InSignBits)
10324 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
10325 N0.getOperand(1));
10329 // fold (sext_inreg (extload x)) -> (sextload x)
10330 // If sextload is not supported by target, we can only do the combine when
10331 // load has one use. Doing otherwise can block folding the extload with other
10332 // extends that the target does support.
10333 if (ISD::isEXTLoad(N0.getNode()) &&
10334 ISD::isUNINDEXEDLoad(N0.getNode()) &&
10335 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10336 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
10337 N0.hasOneUse()) ||
10338 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
10339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10340 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
10341 LN0->getChain(),
10342 LN0->getBasePtr(), EVT,
10343 LN0->getMemOperand());
10344 CombineTo(N, ExtLoad);
10345 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
10346 AddToWorklist(ExtLoad.getNode());
10347 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10349 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
10350 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
10351 N0.hasOneUse() &&
10352 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10353 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
10354 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
10355 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10356 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
10357 LN0->getChain(),
10358 LN0->getBasePtr(), EVT,
10359 LN0->getMemOperand());
10360 CombineTo(N, ExtLoad);
10361 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
10362 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10365 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
10366 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
10367 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
10368 N0.getOperand(1), false))
10369 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
10370 BSwap, N1);
10373 return SDValue();
10376 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
10377 SDValue N0 = N->getOperand(0);
10378 EVT VT = N->getValueType(0);
10380 if (N0.isUndef())
10381 return DAG.getUNDEF(VT);
10383 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10384 return Res;
10386 if (SimplifyDemandedVectorElts(SDValue(N, 0)))
10387 return SDValue(N, 0);
10389 return SDValue();
10392 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
10393 SDValue N0 = N->getOperand(0);
10394 EVT VT = N->getValueType(0);
10396 if (N0.isUndef())
10397 return DAG.getUNDEF(VT);
10399 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10400 return Res;
10402 if (SimplifyDemandedVectorElts(SDValue(N, 0)))
10403 return SDValue(N, 0);
10405 return SDValue();
10408 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
10409 SDValue N0 = N->getOperand(0);
10410 EVT VT = N->getValueType(0);
10411 EVT SrcVT = N0.getValueType();
10412 bool isLE = DAG.getDataLayout().isLittleEndian();
10414 // noop truncate
10415 if (SrcVT == VT)
10416 return N0;
10418 // fold (truncate (truncate x)) -> (truncate x)
10419 if (N0.getOpcode() == ISD::TRUNCATE)
10420 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
10422 // fold (truncate c1) -> c1
10423 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
10424 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
10425 if (C.getNode() != N)
10426 return C;
10429 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
10430 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
10431 N0.getOpcode() == ISD::SIGN_EXTEND ||
10432 N0.getOpcode() == ISD::ANY_EXTEND) {
10433 // if the source is smaller than the dest, we still need an extend.
10434 if (N0.getOperand(0).getValueType().bitsLT(VT))
10435 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
10436 // if the source is larger than the dest, than we just need the truncate.
10437 if (N0.getOperand(0).getValueType().bitsGT(VT))
10438 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
10439 // if the source and dest are the same type, we can drop both the extend
10440 // and the truncate.
10441 return N0.getOperand(0);
10444 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
10445 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
10446 return SDValue();
10448 // Fold extract-and-trunc into a narrow extract. For example:
10449 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
10450 // i32 y = TRUNCATE(i64 x)
10451 // -- becomes --
10452 // v16i8 b = BITCAST (v2i64 val)
10453 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
10455 // Note: We only run this optimization after type legalization (which often
10456 // creates this pattern) and before operation legalization after which
10457 // we need to be more careful about the vector instructions that we generate.
10458 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10459 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
10460 EVT VecTy = N0.getOperand(0).getValueType();
10461 EVT ExTy = N0.getValueType();
10462 EVT TrTy = N->getValueType(0);
10464 unsigned NumElem = VecTy.getVectorNumElements();
10465 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
10467 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
10468 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
10470 SDValue EltNo = N0->getOperand(1);
10471 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
10472 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10473 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
10474 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
10476 SDLoc DL(N);
10477 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
10478 DAG.getBitcast(NVT, N0.getOperand(0)),
10479 DAG.getConstant(Index, DL, IndexTy));
10483 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
10484 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
10485 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
10486 TLI.isTruncateFree(SrcVT, VT)) {
10487 SDLoc SL(N0);
10488 SDValue Cond = N0.getOperand(0);
10489 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
10490 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
10491 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
10495 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
10496 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
10497 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
10498 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
10499 SDValue Amt = N0.getOperand(1);
10500 KnownBits Known = DAG.computeKnownBits(Amt);
10501 unsigned Size = VT.getScalarSizeInBits();
10502 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
10503 SDLoc SL(N);
10504 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
10506 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
10507 if (AmtVT != Amt.getValueType()) {
10508 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
10509 AddToWorklist(Amt.getNode());
10511 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
10515 // Attempt to pre-truncate BUILD_VECTOR sources.
10516 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
10517 TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType())) {
10518 SDLoc DL(N);
10519 EVT SVT = VT.getScalarType();
10520 SmallVector<SDValue, 8> TruncOps;
10521 for (const SDValue &Op : N0->op_values()) {
10522 SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op);
10523 TruncOps.push_back(TruncOp);
10525 return DAG.getBuildVector(VT, DL, TruncOps);
10528 // Fold a series of buildvector, bitcast, and truncate if possible.
10529 // For example fold
10530 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
10531 // (2xi32 (buildvector x, y)).
10532 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
10533 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
10534 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10535 N0.getOperand(0).hasOneUse()) {
10536 SDValue BuildVect = N0.getOperand(0);
10537 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
10538 EVT TruncVecEltTy = VT.getVectorElementType();
10540 // Check that the element types match.
10541 if (BuildVectEltTy == TruncVecEltTy) {
10542 // Now we only need to compute the offset of the truncated elements.
10543 unsigned BuildVecNumElts = BuildVect.getNumOperands();
10544 unsigned TruncVecNumElts = VT.getVectorNumElements();
10545 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
10547 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
10548 "Invalid number of elements");
10550 SmallVector<SDValue, 8> Opnds;
10551 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
10552 Opnds.push_back(BuildVect.getOperand(i));
10554 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
10558 // See if we can simplify the input to this truncate through knowledge that
10559 // only the low bits are being used.
10560 // For example "trunc (or (shl x, 8), y)" // -> trunc y
10561 // Currently we only perform this optimization on scalars because vectors
10562 // may have different active low bits.
10563 if (!VT.isVector()) {
10564 APInt Mask =
10565 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
10566 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
10567 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
10570 // fold (truncate (load x)) -> (smaller load x)
10571 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
10572 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
10573 if (SDValue Reduced = ReduceLoadWidth(N))
10574 return Reduced;
10576 // Handle the case where the load remains an extending load even
10577 // after truncation.
10578 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
10579 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10580 if (!LN0->isVolatile() &&
10581 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
10582 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
10583 VT, LN0->getChain(), LN0->getBasePtr(),
10584 LN0->getMemoryVT(),
10585 LN0->getMemOperand());
10586 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
10587 return NewLoad;
10592 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
10593 // where ... are all 'undef'.
10594 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
10595 SmallVector<EVT, 8> VTs;
10596 SDValue V;
10597 unsigned Idx = 0;
10598 unsigned NumDefs = 0;
10600 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10601 SDValue X = N0.getOperand(i);
10602 if (!X.isUndef()) {
10603 V = X;
10604 Idx = i;
10605 NumDefs++;
10607 // Stop if more than one members are non-undef.
10608 if (NumDefs > 1)
10609 break;
10610 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
10611 VT.getVectorElementType(),
10612 X.getValueType().getVectorNumElements()));
10615 if (NumDefs == 0)
10616 return DAG.getUNDEF(VT);
10618 if (NumDefs == 1) {
10619 assert(V.getNode() && "The single defined operand is empty!");
10620 SmallVector<SDValue, 8> Opnds;
10621 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
10622 if (i != Idx) {
10623 Opnds.push_back(DAG.getUNDEF(VTs[i]));
10624 continue;
10626 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
10627 AddToWorklist(NV.getNode());
10628 Opnds.push_back(NV);
10630 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
10634 // Fold truncate of a bitcast of a vector to an extract of the low vector
10635 // element.
10637 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
10638 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
10639 SDValue VecSrc = N0.getOperand(0);
10640 EVT SrcVT = VecSrc.getValueType();
10641 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
10642 (!LegalOperations ||
10643 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
10644 SDLoc SL(N);
10646 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
10647 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
10648 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
10649 VecSrc, DAG.getConstant(Idx, SL, IdxVT));
10653 // Simplify the operands using demanded-bits information.
10654 if (!VT.isVector() &&
10655 SimplifyDemandedBits(SDValue(N, 0)))
10656 return SDValue(N, 0);
10658 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
10659 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
10660 // When the adde's carry is not used.
10661 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
10662 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
10663 // We only do for addcarry before legalize operation
10664 ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) ||
10665 TLI.isOperationLegal(N0.getOpcode(), VT))) {
10666 SDLoc SL(N);
10667 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
10668 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
10669 auto VTs = DAG.getVTList(VT, N0->getValueType(1));
10670 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
10673 // fold (truncate (extract_subvector(ext x))) ->
10674 // (extract_subvector x)
10675 // TODO: This can be generalized to cover cases where the truncate and extract
10676 // do not fully cancel each other out.
10677 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
10678 SDValue N00 = N0.getOperand(0);
10679 if (N00.getOpcode() == ISD::SIGN_EXTEND ||
10680 N00.getOpcode() == ISD::ZERO_EXTEND ||
10681 N00.getOpcode() == ISD::ANY_EXTEND) {
10682 if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
10683 VT.getVectorElementType())
10684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
10685 N00.getOperand(0), N0.getOperand(1));
10689 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10690 return NewVSel;
10692 // Narrow a suitable binary operation with a non-opaque constant operand by
10693 // moving it ahead of the truncate. This is limited to pre-legalization
10694 // because targets may prefer a wider type during later combines and invert
10695 // this transform.
10696 switch (N0.getOpcode()) {
10697 case ISD::ADD:
10698 case ISD::SUB:
10699 case ISD::MUL:
10700 case ISD::AND:
10701 case ISD::OR:
10702 case ISD::XOR:
10703 if (!LegalOperations && N0.hasOneUse() &&
10704 (isConstantOrConstantVector(N0.getOperand(0), true) ||
10705 isConstantOrConstantVector(N0.getOperand(1), true))) {
10706 // TODO: We already restricted this to pre-legalization, but for vectors
10707 // we are extra cautious to not create an unsupported operation.
10708 // Target-specific changes are likely needed to avoid regressions here.
10709 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
10710 SDLoc DL(N);
10711 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
10712 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
10713 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR);
10718 return SDValue();
10721 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
10722 SDValue Elt = N->getOperand(i);
10723 if (Elt.getOpcode() != ISD::MERGE_VALUES)
10724 return Elt.getNode();
10725 return Elt.getOperand(Elt.getResNo()).getNode();
10728 /// build_pair (load, load) -> load
10729 /// if load locations are consecutive.
10730 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
10731 assert(N->getOpcode() == ISD::BUILD_PAIR);
10733 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
10734 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
10736 // A BUILD_PAIR is always having the least significant part in elt 0 and the
10737 // most significant part in elt 1. So when combining into one large load, we
10738 // need to consider the endianness.
10739 if (DAG.getDataLayout().isBigEndian())
10740 std::swap(LD1, LD2);
10742 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
10743 LD1->getAddressSpace() != LD2->getAddressSpace())
10744 return SDValue();
10745 EVT LD1VT = LD1->getValueType(0);
10746 unsigned LD1Bytes = LD1VT.getStoreSize();
10747 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
10748 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
10749 unsigned Align = LD1->getAlignment();
10750 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
10751 VT.getTypeForEVT(*DAG.getContext()));
10753 if (NewAlign <= Align &&
10754 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
10755 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
10756 LD1->getPointerInfo(), Align);
10759 return SDValue();
10762 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
10763 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
10764 // and Lo parts; on big-endian machines it doesn't.
10765 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
10768 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
10769 const TargetLowering &TLI) {
10770 // If this is not a bitcast to an FP type or if the target doesn't have
10771 // IEEE754-compliant FP logic, we're done.
10772 EVT VT = N->getValueType(0);
10773 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
10774 return SDValue();
10776 // TODO: Handle cases where the integer constant is a different scalar
10777 // bitwidth to the FP.
10778 SDValue N0 = N->getOperand(0);
10779 EVT SourceVT = N0.getValueType();
10780 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
10781 return SDValue();
10783 unsigned FPOpcode;
10784 APInt SignMask;
10785 switch (N0.getOpcode()) {
10786 case ISD::AND:
10787 FPOpcode = ISD::FABS;
10788 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
10789 break;
10790 case ISD::XOR:
10791 FPOpcode = ISD::FNEG;
10792 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
10793 break;
10794 case ISD::OR:
10795 FPOpcode = ISD::FABS;
10796 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
10797 break;
10798 default:
10799 return SDValue();
10802 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
10803 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
10804 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
10805 // fneg (fabs X)
10806 SDValue LogicOp0 = N0.getOperand(0);
10807 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
10808 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
10809 LogicOp0.getOpcode() == ISD::BITCAST &&
10810 LogicOp0.getOperand(0).getValueType() == VT) {
10811 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0));
10812 NumFPLogicOpsConv++;
10813 if (N0.getOpcode() == ISD::OR)
10814 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
10815 return FPOp;
10818 return SDValue();
10821 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
10822 SDValue N0 = N->getOperand(0);
10823 EVT VT = N->getValueType(0);
10825 if (N0.isUndef())
10826 return DAG.getUNDEF(VT);
10828 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
10829 // Only do this before legalize types, unless both types are integer and the
10830 // scalar type is legal. Only do this before legalize ops, since the target
10831 // maybe depending on the bitcast.
10832 // First check to see if this is all constant.
10833 // TODO: Support FP bitcasts after legalize types.
10834 if (VT.isVector() &&
10835 (!LegalTypes ||
10836 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
10837 TLI.isTypeLegal(VT.getVectorElementType()))) &&
10838 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
10839 cast<BuildVectorSDNode>(N0)->isConstant())
10840 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(),
10841 VT.getVectorElementType());
10843 // If the input is a constant, let getNode fold it.
10844 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
10845 // If we can't allow illegal operations, we need to check that this is just
10846 // a fp -> int or int -> conversion and that the resulting operation will
10847 // be legal.
10848 if (!LegalOperations ||
10849 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
10850 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
10851 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
10852 TLI.isOperationLegal(ISD::Constant, VT))) {
10853 SDValue C = DAG.getBitcast(VT, N0);
10854 if (C.getNode() != N)
10855 return C;
10859 // (conv (conv x, t1), t2) -> (conv x, t2)
10860 if (N0.getOpcode() == ISD::BITCAST)
10861 return DAG.getBitcast(VT, N0.getOperand(0));
10863 // fold (conv (load x)) -> (load (conv*)x)
10864 // If the resultant load doesn't need a higher alignment than the original!
10865 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10866 // Do not remove the cast if the types differ in endian layout.
10867 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
10868 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
10869 // If the load is volatile, we only want to change the load type if the
10870 // resulting load is legal. Otherwise we might increase the number of
10871 // memory accesses. We don't care if the original type was legal or not
10872 // as we assume software couldn't rely on the number of accesses of an
10873 // illegal type.
10874 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
10875 TLI.isOperationLegal(ISD::LOAD, VT))) {
10876 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10878 if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
10879 *LN0->getMemOperand())) {
10880 SDValue Load =
10881 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10882 LN0->getPointerInfo(), LN0->getAlignment(),
10883 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
10884 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
10885 return Load;
10889 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
10890 return V;
10892 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
10893 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
10895 // For ppc_fp128:
10896 // fold (bitcast (fneg x)) ->
10897 // flipbit = signbit
10898 // (xor (bitcast x) (build_pair flipbit, flipbit))
10900 // fold (bitcast (fabs x)) ->
10901 // flipbit = (and (extract_element (bitcast x), 0), signbit)
10902 // (xor (bitcast x) (build_pair flipbit, flipbit))
10903 // This often reduces constant pool loads.
10904 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
10905 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
10906 N0.getNode()->hasOneUse() && VT.isInteger() &&
10907 !VT.isVector() && !N0.getValueType().isVector()) {
10908 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
10909 AddToWorklist(NewConv.getNode());
10911 SDLoc DL(N);
10912 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
10913 assert(VT.getSizeInBits() == 128);
10914 SDValue SignBit = DAG.getConstant(
10915 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
10916 SDValue FlipBit;
10917 if (N0.getOpcode() == ISD::FNEG) {
10918 FlipBit = SignBit;
10919 AddToWorklist(FlipBit.getNode());
10920 } else {
10921 assert(N0.getOpcode() == ISD::FABS);
10922 SDValue Hi =
10923 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
10924 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
10925 SDLoc(NewConv)));
10926 AddToWorklist(Hi.getNode());
10927 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
10928 AddToWorklist(FlipBit.getNode());
10930 SDValue FlipBits =
10931 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
10932 AddToWorklist(FlipBits.getNode());
10933 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
10935 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
10936 if (N0.getOpcode() == ISD::FNEG)
10937 return DAG.getNode(ISD::XOR, DL, VT,
10938 NewConv, DAG.getConstant(SignBit, DL, VT));
10939 assert(N0.getOpcode() == ISD::FABS);
10940 return DAG.getNode(ISD::AND, DL, VT,
10941 NewConv, DAG.getConstant(~SignBit, DL, VT));
10944 // fold (bitconvert (fcopysign cst, x)) ->
10945 // (or (and (bitconvert x), sign), (and cst, (not sign)))
10946 // Note that we don't handle (copysign x, cst) because this can always be
10947 // folded to an fneg or fabs.
10949 // For ppc_fp128:
10950 // fold (bitcast (fcopysign cst, x)) ->
10951 // flipbit = (and (extract_element
10952 // (xor (bitcast cst), (bitcast x)), 0),
10953 // signbit)
10954 // (xor (bitcast cst) (build_pair flipbit, flipbit))
10955 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
10956 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
10957 VT.isInteger() && !VT.isVector()) {
10958 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
10959 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
10960 if (isTypeLegal(IntXVT)) {
10961 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
10962 AddToWorklist(X.getNode());
10964 // If X has a different width than the result/lhs, sext it or truncate it.
10965 unsigned VTWidth = VT.getSizeInBits();
10966 if (OrigXWidth < VTWidth) {
10967 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
10968 AddToWorklist(X.getNode());
10969 } else if (OrigXWidth > VTWidth) {
10970 // To get the sign bit in the right place, we have to shift it right
10971 // before truncating.
10972 SDLoc DL(X);
10973 X = DAG.getNode(ISD::SRL, DL,
10974 X.getValueType(), X,
10975 DAG.getConstant(OrigXWidth-VTWidth, DL,
10976 X.getValueType()));
10977 AddToWorklist(X.getNode());
10978 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
10979 AddToWorklist(X.getNode());
10982 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
10983 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
10984 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
10985 AddToWorklist(Cst.getNode());
10986 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
10987 AddToWorklist(X.getNode());
10988 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
10989 AddToWorklist(XorResult.getNode());
10990 SDValue XorResult64 = DAG.getNode(
10991 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
10992 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
10993 SDLoc(XorResult)));
10994 AddToWorklist(XorResult64.getNode());
10995 SDValue FlipBit =
10996 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
10997 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
10998 AddToWorklist(FlipBit.getNode());
10999 SDValue FlipBits =
11000 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
11001 AddToWorklist(FlipBits.getNode());
11002 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
11004 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
11005 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
11006 X, DAG.getConstant(SignBit, SDLoc(X), VT));
11007 AddToWorklist(X.getNode());
11009 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
11010 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
11011 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
11012 AddToWorklist(Cst.getNode());
11014 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
11018 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
11019 if (N0.getOpcode() == ISD::BUILD_PAIR)
11020 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
11021 return CombineLD;
11023 // Remove double bitcasts from shuffles - this is often a legacy of
11024 // XformToShuffleWithZero being used to combine bitmaskings (of
11025 // float vectors bitcast to integer vectors) into shuffles.
11026 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
11027 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
11028 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
11029 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
11030 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
11031 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
11033 // If operands are a bitcast, peek through if it casts the original VT.
11034 // If operands are a constant, just bitcast back to original VT.
11035 auto PeekThroughBitcast = [&](SDValue Op) {
11036 if (Op.getOpcode() == ISD::BITCAST &&
11037 Op.getOperand(0).getValueType() == VT)
11038 return SDValue(Op.getOperand(0));
11039 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
11040 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
11041 return DAG.getBitcast(VT, Op);
11042 return SDValue();
11045 // FIXME: If either input vector is bitcast, try to convert the shuffle to
11046 // the result type of this bitcast. This would eliminate at least one
11047 // bitcast. See the transform in InstCombine.
11048 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
11049 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
11050 if (!(SV0 && SV1))
11051 return SDValue();
11053 int MaskScale =
11054 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
11055 SmallVector<int, 8> NewMask;
11056 for (int M : SVN->getMask())
11057 for (int i = 0; i != MaskScale; ++i)
11058 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
11060 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
11061 if (!LegalMask) {
11062 std::swap(SV0, SV1);
11063 ShuffleVectorSDNode::commuteMask(NewMask);
11064 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
11067 if (LegalMask)
11068 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
11071 return SDValue();
11074 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
11075 EVT VT = N->getValueType(0);
11076 return CombineConsecutiveLoads(N, VT);
11079 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
11080 /// operands. DstEltVT indicates the destination element value type.
11081 SDValue DAGCombiner::
11082 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
11083 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
11085 // If this is already the right type, we're done.
11086 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
11088 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
11089 unsigned DstBitSize = DstEltVT.getSizeInBits();
11091 // If this is a conversion of N elements of one type to N elements of another
11092 // type, convert each element. This handles FP<->INT cases.
11093 if (SrcBitSize == DstBitSize) {
11094 SmallVector<SDValue, 8> Ops;
11095 for (SDValue Op : BV->op_values()) {
11096 // If the vector element type is not legal, the BUILD_VECTOR operands
11097 // are promoted and implicitly truncated. Make that explicit here.
11098 if (Op.getValueType() != SrcEltVT)
11099 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
11100 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
11101 AddToWorklist(Ops.back().getNode());
11103 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
11104 BV->getValueType(0).getVectorNumElements());
11105 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
11108 // Otherwise, we're growing or shrinking the elements. To avoid having to
11109 // handle annoying details of growing/shrinking FP values, we convert them to
11110 // int first.
11111 if (SrcEltVT.isFloatingPoint()) {
11112 // Convert the input float vector to a int vector where the elements are the
11113 // same sizes.
11114 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
11115 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
11116 SrcEltVT = IntVT;
11119 // Now we know the input is an integer vector. If the output is a FP type,
11120 // convert to integer first, then to FP of the right size.
11121 if (DstEltVT.isFloatingPoint()) {
11122 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
11123 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
11125 // Next, convert to FP elements of the same size.
11126 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
11129 SDLoc DL(BV);
11131 // Okay, we know the src/dst types are both integers of differing types.
11132 // Handling growing first.
11133 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
11134 if (SrcBitSize < DstBitSize) {
11135 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
11137 SmallVector<SDValue, 8> Ops;
11138 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
11139 i += NumInputsPerOutput) {
11140 bool isLE = DAG.getDataLayout().isLittleEndian();
11141 APInt NewBits = APInt(DstBitSize, 0);
11142 bool EltIsUndef = true;
11143 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
11144 // Shift the previously computed bits over.
11145 NewBits <<= SrcBitSize;
11146 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
11147 if (Op.isUndef()) continue;
11148 EltIsUndef = false;
11150 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
11151 zextOrTrunc(SrcBitSize).zext(DstBitSize);
11154 if (EltIsUndef)
11155 Ops.push_back(DAG.getUNDEF(DstEltVT));
11156 else
11157 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
11160 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
11161 return DAG.getBuildVector(VT, DL, Ops);
11164 // Finally, this must be the case where we are shrinking elements: each input
11165 // turns into multiple outputs.
11166 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
11167 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
11168 NumOutputsPerInput*BV->getNumOperands());
11169 SmallVector<SDValue, 8> Ops;
11171 for (const SDValue &Op : BV->op_values()) {
11172 if (Op.isUndef()) {
11173 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
11174 continue;
11177 APInt OpVal = cast<ConstantSDNode>(Op)->
11178 getAPIntValue().zextOrTrunc(SrcBitSize);
11180 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
11181 APInt ThisVal = OpVal.trunc(DstBitSize);
11182 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
11183 OpVal.lshrInPlace(DstBitSize);
11186 // For big endian targets, swap the order of the pieces of each element.
11187 if (DAG.getDataLayout().isBigEndian())
11188 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
11191 return DAG.getBuildVector(VT, DL, Ops);
11194 static bool isContractable(SDNode *N) {
11195 SDNodeFlags F = N->getFlags();
11196 return F.hasAllowContract() || F.hasAllowReassociation();
11199 /// Try to perform FMA combining on a given FADD node.
11200 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
11201 SDValue N0 = N->getOperand(0);
11202 SDValue N1 = N->getOperand(1);
11203 EVT VT = N->getValueType(0);
11204 SDLoc SL(N);
11206 const TargetOptions &Options = DAG.getTarget().Options;
11208 // Floating-point multiply-add with intermediate rounding.
11209 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
11211 // Floating-point multiply-add without intermediate rounding.
11212 bool HasFMA =
11213 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
11214 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
11216 // No valid opcode, do not combine.
11217 if (!HasFMAD && !HasFMA)
11218 return SDValue();
11220 SDNodeFlags Flags = N->getFlags();
11221 bool CanFuse = Options.UnsafeFPMath || isContractable(N);
11222 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
11223 CanFuse || HasFMAD);
11224 // If the addition is not contractable, do not combine.
11225 if (!AllowFusionGlobally && !isContractable(N))
11226 return SDValue();
11228 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
11229 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
11230 return SDValue();
11232 // Always prefer FMAD to FMA for precision.
11233 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
11234 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
11236 // Is the node an FMUL and contractable either due to global flags or
11237 // SDNodeFlags.
11238 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
11239 if (N.getOpcode() != ISD::FMUL)
11240 return false;
11241 return AllowFusionGlobally || isContractable(N.getNode());
11243 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
11244 // prefer to fold the multiply with fewer uses.
11245 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
11246 if (N0.getNode()->use_size() > N1.getNode()->use_size())
11247 std::swap(N0, N1);
11250 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
11251 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
11252 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11253 N0.getOperand(0), N0.getOperand(1), N1, Flags);
11256 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
11257 // Note: Commutes FADD operands.
11258 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
11259 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11260 N1.getOperand(0), N1.getOperand(1), N0, Flags);
11263 // Look through FP_EXTEND nodes to do more combining.
11265 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
11266 if (N0.getOpcode() == ISD::FP_EXTEND) {
11267 SDValue N00 = N0.getOperand(0);
11268 if (isContractableFMUL(N00) &&
11269 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
11270 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11271 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11272 N00.getOperand(0)),
11273 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11274 N00.getOperand(1)), N1, Flags);
11278 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
11279 // Note: Commutes FADD operands.
11280 if (N1.getOpcode() == ISD::FP_EXTEND) {
11281 SDValue N10 = N1.getOperand(0);
11282 if (isContractableFMUL(N10) &&
11283 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
11284 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11285 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11286 N10.getOperand(0)),
11287 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11288 N10.getOperand(1)), N0, Flags);
11292 // More folding opportunities when target permits.
11293 if (Aggressive) {
11294 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
11295 if (CanFuse &&
11296 N0.getOpcode() == PreferredFusedOpcode &&
11297 N0.getOperand(2).getOpcode() == ISD::FMUL &&
11298 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
11299 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11300 N0.getOperand(0), N0.getOperand(1),
11301 DAG.getNode(PreferredFusedOpcode, SL, VT,
11302 N0.getOperand(2).getOperand(0),
11303 N0.getOperand(2).getOperand(1),
11304 N1, Flags), Flags);
11307 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
11308 if (CanFuse &&
11309 N1->getOpcode() == PreferredFusedOpcode &&
11310 N1.getOperand(2).getOpcode() == ISD::FMUL &&
11311 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
11312 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11313 N1.getOperand(0), N1.getOperand(1),
11314 DAG.getNode(PreferredFusedOpcode, SL, VT,
11315 N1.getOperand(2).getOperand(0),
11316 N1.getOperand(2).getOperand(1),
11317 N0, Flags), Flags);
11321 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
11322 // -> (fma x, y, (fma (fpext u), (fpext v), z))
11323 auto FoldFAddFMAFPExtFMul = [&] (
11324 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
11325 SDNodeFlags Flags) {
11326 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
11327 DAG.getNode(PreferredFusedOpcode, SL, VT,
11328 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
11329 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
11330 Z, Flags), Flags);
11332 if (N0.getOpcode() == PreferredFusedOpcode) {
11333 SDValue N02 = N0.getOperand(2);
11334 if (N02.getOpcode() == ISD::FP_EXTEND) {
11335 SDValue N020 = N02.getOperand(0);
11336 if (isContractableFMUL(N020) &&
11337 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
11338 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
11339 N020.getOperand(0), N020.getOperand(1),
11340 N1, Flags);
11345 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
11346 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
11347 // FIXME: This turns two single-precision and one double-precision
11348 // operation into two double-precision operations, which might not be
11349 // interesting for all targets, especially GPUs.
11350 auto FoldFAddFPExtFMAFMul = [&] (
11351 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
11352 SDNodeFlags Flags) {
11353 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11354 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
11355 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
11356 DAG.getNode(PreferredFusedOpcode, SL, VT,
11357 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
11358 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
11359 Z, Flags), Flags);
11361 if (N0.getOpcode() == ISD::FP_EXTEND) {
11362 SDValue N00 = N0.getOperand(0);
11363 if (N00.getOpcode() == PreferredFusedOpcode) {
11364 SDValue N002 = N00.getOperand(2);
11365 if (isContractableFMUL(N002) &&
11366 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
11367 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
11368 N002.getOperand(0), N002.getOperand(1),
11369 N1, Flags);
11374 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
11375 // -> (fma y, z, (fma (fpext u), (fpext v), x))
11376 if (N1.getOpcode() == PreferredFusedOpcode) {
11377 SDValue N12 = N1.getOperand(2);
11378 if (N12.getOpcode() == ISD::FP_EXTEND) {
11379 SDValue N120 = N12.getOperand(0);
11380 if (isContractableFMUL(N120) &&
11381 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
11382 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
11383 N120.getOperand(0), N120.getOperand(1),
11384 N0, Flags);
11389 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
11390 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
11391 // FIXME: This turns two single-precision and one double-precision
11392 // operation into two double-precision operations, which might not be
11393 // interesting for all targets, especially GPUs.
11394 if (N1.getOpcode() == ISD::FP_EXTEND) {
11395 SDValue N10 = N1.getOperand(0);
11396 if (N10.getOpcode() == PreferredFusedOpcode) {
11397 SDValue N102 = N10.getOperand(2);
11398 if (isContractableFMUL(N102) &&
11399 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
11400 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
11401 N102.getOperand(0), N102.getOperand(1),
11402 N0, Flags);
11408 return SDValue();
11411 /// Try to perform FMA combining on a given FSUB node.
11412 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
11413 SDValue N0 = N->getOperand(0);
11414 SDValue N1 = N->getOperand(1);
11415 EVT VT = N->getValueType(0);
11416 SDLoc SL(N);
11418 const TargetOptions &Options = DAG.getTarget().Options;
11419 // Floating-point multiply-add with intermediate rounding.
11420 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
11422 // Floating-point multiply-add without intermediate rounding.
11423 bool HasFMA =
11424 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
11425 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
11427 // No valid opcode, do not combine.
11428 if (!HasFMAD && !HasFMA)
11429 return SDValue();
11431 const SDNodeFlags Flags = N->getFlags();
11432 bool CanFuse = Options.UnsafeFPMath || isContractable(N);
11433 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
11434 CanFuse || HasFMAD);
11436 // If the subtraction is not contractable, do not combine.
11437 if (!AllowFusionGlobally && !isContractable(N))
11438 return SDValue();
11440 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
11441 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
11442 return SDValue();
11444 // Always prefer FMAD to FMA for precision.
11445 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
11446 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
11448 // Is the node an FMUL and contractable either due to global flags or
11449 // SDNodeFlags.
11450 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
11451 if (N.getOpcode() != ISD::FMUL)
11452 return false;
11453 return AllowFusionGlobally || isContractable(N.getNode());
11456 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
11457 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
11458 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11459 N0.getOperand(0), N0.getOperand(1),
11460 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
11463 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
11464 // Note: Commutes FSUB operands.
11465 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
11466 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11467 DAG.getNode(ISD::FNEG, SL, VT,
11468 N1.getOperand(0)),
11469 N1.getOperand(1), N0, Flags);
11472 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
11473 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
11474 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
11475 SDValue N00 = N0.getOperand(0).getOperand(0);
11476 SDValue N01 = N0.getOperand(0).getOperand(1);
11477 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11478 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
11479 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
11482 // Look through FP_EXTEND nodes to do more combining.
11484 // fold (fsub (fpext (fmul x, y)), z)
11485 // -> (fma (fpext x), (fpext y), (fneg z))
11486 if (N0.getOpcode() == ISD::FP_EXTEND) {
11487 SDValue N00 = N0.getOperand(0);
11488 if (isContractableFMUL(N00) &&
11489 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
11490 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11491 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11492 N00.getOperand(0)),
11493 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11494 N00.getOperand(1)),
11495 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
11499 // fold (fsub x, (fpext (fmul y, z)))
11500 // -> (fma (fneg (fpext y)), (fpext z), x)
11501 // Note: Commutes FSUB operands.
11502 if (N1.getOpcode() == ISD::FP_EXTEND) {
11503 SDValue N10 = N1.getOperand(0);
11504 if (isContractableFMUL(N10) &&
11505 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
11506 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11507 DAG.getNode(ISD::FNEG, SL, VT,
11508 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11509 N10.getOperand(0))),
11510 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11511 N10.getOperand(1)),
11512 N0, Flags);
11516 // fold (fsub (fpext (fneg (fmul, x, y))), z)
11517 // -> (fneg (fma (fpext x), (fpext y), z))
11518 // Note: This could be removed with appropriate canonicalization of the
11519 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11520 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11521 // from implementing the canonicalization in visitFSUB.
11522 if (N0.getOpcode() == ISD::FP_EXTEND) {
11523 SDValue N00 = N0.getOperand(0);
11524 if (N00.getOpcode() == ISD::FNEG) {
11525 SDValue N000 = N00.getOperand(0);
11526 if (isContractableFMUL(N000) &&
11527 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
11528 return DAG.getNode(ISD::FNEG, SL, VT,
11529 DAG.getNode(PreferredFusedOpcode, SL, VT,
11530 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11531 N000.getOperand(0)),
11532 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11533 N000.getOperand(1)),
11534 N1, Flags));
11539 // fold (fsub (fneg (fpext (fmul, x, y))), z)
11540 // -> (fneg (fma (fpext x)), (fpext y), z)
11541 // Note: This could be removed with appropriate canonicalization of the
11542 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11543 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11544 // from implementing the canonicalization in visitFSUB.
11545 if (N0.getOpcode() == ISD::FNEG) {
11546 SDValue N00 = N0.getOperand(0);
11547 if (N00.getOpcode() == ISD::FP_EXTEND) {
11548 SDValue N000 = N00.getOperand(0);
11549 if (isContractableFMUL(N000) &&
11550 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
11551 return DAG.getNode(ISD::FNEG, SL, VT,
11552 DAG.getNode(PreferredFusedOpcode, SL, VT,
11553 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11554 N000.getOperand(0)),
11555 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11556 N000.getOperand(1)),
11557 N1, Flags));
11562 // More folding opportunities when target permits.
11563 if (Aggressive) {
11564 // fold (fsub (fma x, y, (fmul u, v)), z)
11565 // -> (fma x, y (fma u, v, (fneg z)))
11566 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode &&
11567 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
11568 N0.getOperand(2)->hasOneUse()) {
11569 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11570 N0.getOperand(0), N0.getOperand(1),
11571 DAG.getNode(PreferredFusedOpcode, SL, VT,
11572 N0.getOperand(2).getOperand(0),
11573 N0.getOperand(2).getOperand(1),
11574 DAG.getNode(ISD::FNEG, SL, VT,
11575 N1), Flags), Flags);
11578 // fold (fsub x, (fma y, z, (fmul u, v)))
11579 // -> (fma (fneg y), z, (fma (fneg u), v, x))
11580 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode &&
11581 isContractableFMUL(N1.getOperand(2))) {
11582 SDValue N20 = N1.getOperand(2).getOperand(0);
11583 SDValue N21 = N1.getOperand(2).getOperand(1);
11584 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11585 DAG.getNode(ISD::FNEG, SL, VT,
11586 N1.getOperand(0)),
11587 N1.getOperand(1),
11588 DAG.getNode(PreferredFusedOpcode, SL, VT,
11589 DAG.getNode(ISD::FNEG, SL, VT, N20),
11590 N21, N0, Flags), Flags);
11594 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
11595 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
11596 if (N0.getOpcode() == PreferredFusedOpcode) {
11597 SDValue N02 = N0.getOperand(2);
11598 if (N02.getOpcode() == ISD::FP_EXTEND) {
11599 SDValue N020 = N02.getOperand(0);
11600 if (isContractableFMUL(N020) &&
11601 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
11602 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11603 N0.getOperand(0), N0.getOperand(1),
11604 DAG.getNode(PreferredFusedOpcode, SL, VT,
11605 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11606 N020.getOperand(0)),
11607 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11608 N020.getOperand(1)),
11609 DAG.getNode(ISD::FNEG, SL, VT,
11610 N1), Flags), Flags);
11615 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
11616 // -> (fma (fpext x), (fpext y),
11617 // (fma (fpext u), (fpext v), (fneg z)))
11618 // FIXME: This turns two single-precision and one double-precision
11619 // operation into two double-precision operations, which might not be
11620 // interesting for all targets, especially GPUs.
11621 if (N0.getOpcode() == ISD::FP_EXTEND) {
11622 SDValue N00 = N0.getOperand(0);
11623 if (N00.getOpcode() == PreferredFusedOpcode) {
11624 SDValue N002 = N00.getOperand(2);
11625 if (isContractableFMUL(N002) &&
11626 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
11627 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11628 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11629 N00.getOperand(0)),
11630 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11631 N00.getOperand(1)),
11632 DAG.getNode(PreferredFusedOpcode, SL, VT,
11633 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11634 N002.getOperand(0)),
11635 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11636 N002.getOperand(1)),
11637 DAG.getNode(ISD::FNEG, SL, VT,
11638 N1), Flags), Flags);
11643 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
11644 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
11645 if (N1.getOpcode() == PreferredFusedOpcode &&
11646 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
11647 SDValue N120 = N1.getOperand(2).getOperand(0);
11648 if (isContractableFMUL(N120) &&
11649 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
11650 SDValue N1200 = N120.getOperand(0);
11651 SDValue N1201 = N120.getOperand(1);
11652 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11653 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
11654 N1.getOperand(1),
11655 DAG.getNode(PreferredFusedOpcode, SL, VT,
11656 DAG.getNode(ISD::FNEG, SL, VT,
11657 DAG.getNode(ISD::FP_EXTEND, SL,
11658 VT, N1200)),
11659 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11660 N1201),
11661 N0, Flags), Flags);
11665 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
11666 // -> (fma (fneg (fpext y)), (fpext z),
11667 // (fma (fneg (fpext u)), (fpext v), x))
11668 // FIXME: This turns two single-precision and one double-precision
11669 // operation into two double-precision operations, which might not be
11670 // interesting for all targets, especially GPUs.
11671 if (N1.getOpcode() == ISD::FP_EXTEND &&
11672 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
11673 SDValue CvtSrc = N1.getOperand(0);
11674 SDValue N100 = CvtSrc.getOperand(0);
11675 SDValue N101 = CvtSrc.getOperand(1);
11676 SDValue N102 = CvtSrc.getOperand(2);
11677 if (isContractableFMUL(N102) &&
11678 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
11679 SDValue N1020 = N102.getOperand(0);
11680 SDValue N1021 = N102.getOperand(1);
11681 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11682 DAG.getNode(ISD::FNEG, SL, VT,
11683 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11684 N100)),
11685 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
11686 DAG.getNode(PreferredFusedOpcode, SL, VT,
11687 DAG.getNode(ISD::FNEG, SL, VT,
11688 DAG.getNode(ISD::FP_EXTEND, SL,
11689 VT, N1020)),
11690 DAG.getNode(ISD::FP_EXTEND, SL, VT,
11691 N1021),
11692 N0, Flags), Flags);
11697 return SDValue();
11700 /// Try to perform FMA combining on a given FMUL node based on the distributive
11701 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
11702 /// subtraction instead of addition).
11703 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
11704 SDValue N0 = N->getOperand(0);
11705 SDValue N1 = N->getOperand(1);
11706 EVT VT = N->getValueType(0);
11707 SDLoc SL(N);
11708 const SDNodeFlags Flags = N->getFlags();
11710 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
11712 const TargetOptions &Options = DAG.getTarget().Options;
11714 // The transforms below are incorrect when x == 0 and y == inf, because the
11715 // intermediate multiplication produces a nan.
11716 if (!Options.NoInfsFPMath)
11717 return SDValue();
11719 // Floating-point multiply-add without intermediate rounding.
11720 bool HasFMA =
11721 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
11722 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
11723 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
11725 // Floating-point multiply-add with intermediate rounding. This can result
11726 // in a less precise result due to the changed rounding order.
11727 bool HasFMAD = Options.UnsafeFPMath &&
11728 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
11730 // No valid opcode, do not combine.
11731 if (!HasFMAD && !HasFMA)
11732 return SDValue();
11734 // Always prefer FMAD to FMA for precision.
11735 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
11736 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
11738 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
11739 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
11740 auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
11741 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
11742 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
11743 if (C->isExactlyValue(+1.0))
11744 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
11745 Y, Flags);
11746 if (C->isExactlyValue(-1.0))
11747 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
11748 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
11751 return SDValue();
11754 if (SDValue FMA = FuseFADD(N0, N1, Flags))
11755 return FMA;
11756 if (SDValue FMA = FuseFADD(N1, N0, Flags))
11757 return FMA;
11759 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
11760 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
11761 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
11762 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
11763 auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
11764 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
11765 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
11766 if (C0->isExactlyValue(+1.0))
11767 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11768 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
11769 Y, Flags);
11770 if (C0->isExactlyValue(-1.0))
11771 return DAG.getNode(PreferredFusedOpcode, SL, VT,
11772 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
11773 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
11775 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
11776 if (C1->isExactlyValue(+1.0))
11777 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
11778 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
11779 if (C1->isExactlyValue(-1.0))
11780 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
11781 Y, Flags);
11784 return SDValue();
11787 if (SDValue FMA = FuseFSUB(N0, N1, Flags))
11788 return FMA;
11789 if (SDValue FMA = FuseFSUB(N1, N0, Flags))
11790 return FMA;
11792 return SDValue();
11795 SDValue DAGCombiner::visitFADD(SDNode *N) {
11796 SDValue N0 = N->getOperand(0);
11797 SDValue N1 = N->getOperand(1);
11798 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
11799 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
11800 EVT VT = N->getValueType(0);
11801 SDLoc DL(N);
11802 const TargetOptions &Options = DAG.getTarget().Options;
11803 const SDNodeFlags Flags = N->getFlags();
11805 // fold vector ops
11806 if (VT.isVector())
11807 if (SDValue FoldedVOp = SimplifyVBinOp(N))
11808 return FoldedVOp;
11810 // fold (fadd c1, c2) -> c1 + c2
11811 if (N0CFP && N1CFP)
11812 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
11814 // canonicalize constant to RHS
11815 if (N0CFP && !N1CFP)
11816 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
11818 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
11819 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
11820 if (N1C && N1C->isZero())
11821 if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())
11822 return N0;
11824 if (SDValue NewSel = foldBinOpIntoSelect(N))
11825 return NewSel;
11827 // fold (fadd A, (fneg B)) -> (fsub A, B)
11828 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
11829 isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize) == 2)
11830 return DAG.getNode(ISD::FSUB, DL, VT, N0,
11831 GetNegatedExpression(N1, DAG, LegalOperations,
11832 ForCodeSize), Flags);
11834 // fold (fadd (fneg A), B) -> (fsub B, A)
11835 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
11836 isNegatibleForFree(N0, LegalOperations, TLI, &Options, ForCodeSize) == 2)
11837 return DAG.getNode(ISD::FSUB, DL, VT, N1,
11838 GetNegatedExpression(N0, DAG, LegalOperations,
11839 ForCodeSize), Flags);
11841 auto isFMulNegTwo = [](SDValue FMul) {
11842 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
11843 return false;
11844 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
11845 return C && C->isExactlyValue(-2.0);
11848 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
11849 if (isFMulNegTwo(N0)) {
11850 SDValue B = N0.getOperand(0);
11851 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags);
11852 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add, Flags);
11854 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
11855 if (isFMulNegTwo(N1)) {
11856 SDValue B = N1.getOperand(0);
11857 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags);
11858 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add, Flags);
11861 // No FP constant should be created after legalization as Instruction
11862 // Selection pass has a hard time dealing with FP constants.
11863 bool AllowNewConst = (Level < AfterLegalizeDAG);
11865 // If nnan is enabled, fold lots of things.
11866 if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) {
11867 // If allowed, fold (fadd (fneg x), x) -> 0.0
11868 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
11869 return DAG.getConstantFP(0.0, DL, VT);
11871 // If allowed, fold (fadd x, (fneg x)) -> 0.0
11872 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
11873 return DAG.getConstantFP(0.0, DL, VT);
11876 // If 'unsafe math' or reassoc and nsz, fold lots of things.
11877 // TODO: break out portions of the transformations below for which Unsafe is
11878 // considered and which do not require both nsz and reassoc
11879 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
11880 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
11881 AllowNewConst) {
11882 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
11883 if (N1CFP && N0.getOpcode() == ISD::FADD &&
11884 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
11885 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags);
11886 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags);
11889 // We can fold chains of FADD's of the same value into multiplications.
11890 // This transform is not safe in general because we are reducing the number
11891 // of rounding steps.
11892 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
11893 if (N0.getOpcode() == ISD::FMUL) {
11894 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
11895 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
11897 // (fadd (fmul x, c), x) -> (fmul x, c+1)
11898 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
11899 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
11900 DAG.getConstantFP(1.0, DL, VT), Flags);
11901 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
11904 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
11905 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
11906 N1.getOperand(0) == N1.getOperand(1) &&
11907 N0.getOperand(0) == N1.getOperand(0)) {
11908 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
11909 DAG.getConstantFP(2.0, DL, VT), Flags);
11910 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
11914 if (N1.getOpcode() == ISD::FMUL) {
11915 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
11916 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
11918 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
11919 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
11920 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
11921 DAG.getConstantFP(1.0, DL, VT), Flags);
11922 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
11925 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
11926 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
11927 N0.getOperand(0) == N0.getOperand(1) &&
11928 N1.getOperand(0) == N0.getOperand(0)) {
11929 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
11930 DAG.getConstantFP(2.0, DL, VT), Flags);
11931 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
11935 if (N0.getOpcode() == ISD::FADD) {
11936 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
11937 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
11938 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
11939 (N0.getOperand(0) == N1)) {
11940 return DAG.getNode(ISD::FMUL, DL, VT,
11941 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
11945 if (N1.getOpcode() == ISD::FADD) {
11946 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
11947 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
11948 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
11949 N1.getOperand(0) == N0) {
11950 return DAG.getNode(ISD::FMUL, DL, VT,
11951 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
11955 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
11956 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
11957 N0.getOperand(0) == N0.getOperand(1) &&
11958 N1.getOperand(0) == N1.getOperand(1) &&
11959 N0.getOperand(0) == N1.getOperand(0)) {
11960 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
11961 DAG.getConstantFP(4.0, DL, VT), Flags);
11964 } // enable-unsafe-fp-math
11966 // FADD -> FMA combines:
11967 if (SDValue Fused = visitFADDForFMACombine(N)) {
11968 AddToWorklist(Fused.getNode());
11969 return Fused;
11971 return SDValue();
11974 SDValue DAGCombiner::visitFSUB(SDNode *N) {
11975 SDValue N0 = N->getOperand(0);
11976 SDValue N1 = N->getOperand(1);
11977 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
11978 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
11979 EVT VT = N->getValueType(0);
11980 SDLoc DL(N);
11981 const TargetOptions &Options = DAG.getTarget().Options;
11982 const SDNodeFlags Flags = N->getFlags();
11984 // fold vector ops
11985 if (VT.isVector())
11986 if (SDValue FoldedVOp = SimplifyVBinOp(N))
11987 return FoldedVOp;
11989 // fold (fsub c1, c2) -> c1-c2
11990 if (N0CFP && N1CFP)
11991 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
11993 if (SDValue NewSel = foldBinOpIntoSelect(N))
11994 return NewSel;
11996 // (fsub A, 0) -> A
11997 if (N1CFP && N1CFP->isZero()) {
11998 if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath ||
11999 Flags.hasNoSignedZeros()) {
12000 return N0;
12004 if (N0 == N1) {
12005 // (fsub x, x) -> 0.0
12006 if (Options.NoNaNsFPMath || Flags.hasNoNaNs())
12007 return DAG.getConstantFP(0.0f, DL, VT);
12010 // (fsub -0.0, N1) -> -N1
12011 // NOTE: It is safe to transform an FSUB(-0.0,X) into an FNEG(X), since the
12012 // FSUB does not specify the sign bit of a NaN. Also note that for
12013 // the same reason, the inverse transform is not safe, unless fast math
12014 // flags are in play.
12015 if (N0CFP && N0CFP->isZero()) {
12016 if (N0CFP->isNegative() ||
12017 (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) {
12018 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize))
12019 return GetNegatedExpression(N1, DAG, LegalOperations, ForCodeSize);
12020 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
12021 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
12025 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
12026 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros()))
12027 && N1.getOpcode() == ISD::FADD) {
12028 // X - (X + Y) -> -Y
12029 if (N0 == N1->getOperand(0))
12030 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1), Flags);
12031 // X - (Y + X) -> -Y
12032 if (N0 == N1->getOperand(1))
12033 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0), Flags);
12036 // fold (fsub A, (fneg B)) -> (fadd A, B)
12037 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize))
12038 return DAG.getNode(ISD::FADD, DL, VT, N0,
12039 GetNegatedExpression(N1, DAG, LegalOperations,
12040 ForCodeSize), Flags);
12042 // FSUB -> FMA combines:
12043 if (SDValue Fused = visitFSUBForFMACombine(N)) {
12044 AddToWorklist(Fused.getNode());
12045 return Fused;
12048 return SDValue();
12051 SDValue DAGCombiner::visitFMUL(SDNode *N) {
12052 SDValue N0 = N->getOperand(0);
12053 SDValue N1 = N->getOperand(1);
12054 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
12055 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
12056 EVT VT = N->getValueType(0);
12057 SDLoc DL(N);
12058 const TargetOptions &Options = DAG.getTarget().Options;
12059 const SDNodeFlags Flags = N->getFlags();
12061 // fold vector ops
12062 if (VT.isVector()) {
12063 // This just handles C1 * C2 for vectors. Other vector folds are below.
12064 if (SDValue FoldedVOp = SimplifyVBinOp(N))
12065 return FoldedVOp;
12068 // fold (fmul c1, c2) -> c1*c2
12069 if (N0CFP && N1CFP)
12070 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
12072 // canonicalize constant to RHS
12073 if (isConstantFPBuildVectorOrConstantFP(N0) &&
12074 !isConstantFPBuildVectorOrConstantFP(N1))
12075 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
12077 if (SDValue NewSel = foldBinOpIntoSelect(N))
12078 return NewSel;
12080 if ((Options.NoNaNsFPMath && Options.NoSignedZerosFPMath) ||
12081 (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) {
12082 // fold (fmul A, 0) -> 0
12083 if (N1CFP && N1CFP->isZero())
12084 return N1;
12087 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) {
12088 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
12089 if (isConstantFPBuildVectorOrConstantFP(N1) &&
12090 N0.getOpcode() == ISD::FMUL) {
12091 SDValue N00 = N0.getOperand(0);
12092 SDValue N01 = N0.getOperand(1);
12093 // Avoid an infinite loop by making sure that N00 is not a constant
12094 // (the inner multiply has not been constant folded yet).
12095 if (isConstantFPBuildVectorOrConstantFP(N01) &&
12096 !isConstantFPBuildVectorOrConstantFP(N00)) {
12097 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
12098 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
12102 // Match a special-case: we convert X * 2.0 into fadd.
12103 // fmul (fadd X, X), C -> fmul X, 2.0 * C
12104 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
12105 N0.getOperand(0) == N0.getOperand(1)) {
12106 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
12107 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
12108 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
12112 // fold (fmul X, 2.0) -> (fadd X, X)
12113 if (N1CFP && N1CFP->isExactlyValue(+2.0))
12114 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
12116 // fold (fmul X, -1.0) -> (fneg X)
12117 if (N1CFP && N1CFP->isExactlyValue(-1.0))
12118 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
12119 return DAG.getNode(ISD::FNEG, DL, VT, N0);
12121 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
12122 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options,
12123 ForCodeSize)) {
12124 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options,
12125 ForCodeSize)) {
12126 // Both can be negated for free, check to see if at least one is cheaper
12127 // negated.
12128 if (LHSNeg == 2 || RHSNeg == 2)
12129 return DAG.getNode(ISD::FMUL, DL, VT,
12130 GetNegatedExpression(N0, DAG, LegalOperations,
12131 ForCodeSize),
12132 GetNegatedExpression(N1, DAG, LegalOperations,
12133 ForCodeSize),
12134 Flags);
12138 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
12139 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
12140 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
12141 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
12142 TLI.isOperationLegal(ISD::FABS, VT)) {
12143 SDValue Select = N0, X = N1;
12144 if (Select.getOpcode() != ISD::SELECT)
12145 std::swap(Select, X);
12147 SDValue Cond = Select.getOperand(0);
12148 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
12149 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
12151 if (TrueOpnd && FalseOpnd &&
12152 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
12153 isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
12154 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
12155 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12156 switch (CC) {
12157 default: break;
12158 case ISD::SETOLT:
12159 case ISD::SETULT:
12160 case ISD::SETOLE:
12161 case ISD::SETULE:
12162 case ISD::SETLT:
12163 case ISD::SETLE:
12164 std::swap(TrueOpnd, FalseOpnd);
12165 LLVM_FALLTHROUGH;
12166 case ISD::SETOGT:
12167 case ISD::SETUGT:
12168 case ISD::SETOGE:
12169 case ISD::SETUGE:
12170 case ISD::SETGT:
12171 case ISD::SETGE:
12172 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
12173 TLI.isOperationLegal(ISD::FNEG, VT))
12174 return DAG.getNode(ISD::FNEG, DL, VT,
12175 DAG.getNode(ISD::FABS, DL, VT, X));
12176 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
12177 return DAG.getNode(ISD::FABS, DL, VT, X);
12179 break;
12184 // FMUL -> FMA combines:
12185 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
12186 AddToWorklist(Fused.getNode());
12187 return Fused;
12190 return SDValue();
12193 SDValue DAGCombiner::visitFMA(SDNode *N) {
12194 SDValue N0 = N->getOperand(0);
12195 SDValue N1 = N->getOperand(1);
12196 SDValue N2 = N->getOperand(2);
12197 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12198 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
12199 EVT VT = N->getValueType(0);
12200 SDLoc DL(N);
12201 const TargetOptions &Options = DAG.getTarget().Options;
12203 // FMA nodes have flags that propagate to the created nodes.
12204 const SDNodeFlags Flags = N->getFlags();
12205 bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N);
12207 // Constant fold FMA.
12208 if (isa<ConstantFPSDNode>(N0) &&
12209 isa<ConstantFPSDNode>(N1) &&
12210 isa<ConstantFPSDNode>(N2)) {
12211 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
12214 if (UnsafeFPMath) {
12215 if (N0CFP && N0CFP->isZero())
12216 return N2;
12217 if (N1CFP && N1CFP->isZero())
12218 return N2;
12220 // TODO: The FMA node should have flags that propagate to these nodes.
12221 if (N0CFP && N0CFP->isExactlyValue(1.0))
12222 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
12223 if (N1CFP && N1CFP->isExactlyValue(1.0))
12224 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
12226 // Canonicalize (fma c, x, y) -> (fma x, c, y)
12227 if (isConstantFPBuildVectorOrConstantFP(N0) &&
12228 !isConstantFPBuildVectorOrConstantFP(N1))
12229 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
12231 if (UnsafeFPMath) {
12232 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
12233 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
12234 isConstantFPBuildVectorOrConstantFP(N1) &&
12235 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
12236 return DAG.getNode(ISD::FMUL, DL, VT, N0,
12237 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
12238 Flags), Flags);
12241 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
12242 if (N0.getOpcode() == ISD::FMUL &&
12243 isConstantFPBuildVectorOrConstantFP(N1) &&
12244 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
12245 return DAG.getNode(ISD::FMA, DL, VT,
12246 N0.getOperand(0),
12247 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
12248 Flags),
12249 N2);
12253 // (fma x, 1, y) -> (fadd x, y)
12254 // (fma x, -1, y) -> (fadd (fneg x), y)
12255 if (N1CFP) {
12256 if (N1CFP->isExactlyValue(1.0))
12257 // TODO: The FMA node should have flags that propagate to this node.
12258 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
12260 if (N1CFP->isExactlyValue(-1.0) &&
12261 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
12262 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
12263 AddToWorklist(RHSNeg.getNode());
12264 // TODO: The FMA node should have flags that propagate to this node.
12265 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
12268 // fma (fneg x), K, y -> fma x -K, y
12269 if (N0.getOpcode() == ISD::FNEG &&
12270 (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
12271 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT,
12272 ForCodeSize)))) {
12273 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
12274 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
12278 if (UnsafeFPMath) {
12279 // (fma x, c, x) -> (fmul x, (c+1))
12280 if (N1CFP && N0 == N2) {
12281 return DAG.getNode(ISD::FMUL, DL, VT, N0,
12282 DAG.getNode(ISD::FADD, DL, VT, N1,
12283 DAG.getConstantFP(1.0, DL, VT), Flags),
12284 Flags);
12287 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
12288 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
12289 return DAG.getNode(ISD::FMUL, DL, VT, N0,
12290 DAG.getNode(ISD::FADD, DL, VT, N1,
12291 DAG.getConstantFP(-1.0, DL, VT), Flags),
12292 Flags);
12296 return SDValue();
12299 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12300 // reciprocal.
12301 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
12302 // Notice that this is not always beneficial. One reason is different targets
12303 // may have different costs for FDIV and FMUL, so sometimes the cost of two
12304 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
12305 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
12306 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
12307 // TODO: Limit this transform based on optsize/minsize - it always creates at
12308 // least 1 extra instruction. But the perf win may be substantial enough
12309 // that only minsize should restrict this.
12310 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
12311 const SDNodeFlags Flags = N->getFlags();
12312 if (!UnsafeMath && !Flags.hasAllowReciprocal())
12313 return SDValue();
12315 // Skip if current node is a reciprocal/fneg-reciprocal.
12316 SDValue N0 = N->getOperand(0);
12317 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
12318 if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0)))
12319 return SDValue();
12321 // Exit early if the target does not want this transform or if there can't
12322 // possibly be enough uses of the divisor to make the transform worthwhile.
12323 SDValue N1 = N->getOperand(1);
12324 unsigned MinUses = TLI.combineRepeatedFPDivisors();
12326 // For splat vectors, scale the number of uses by the splat factor. If we can
12327 // convert the division into a scalar op, that will likely be much faster.
12328 unsigned NumElts = 1;
12329 EVT VT = N->getValueType(0);
12330 if (VT.isVector() && DAG.isSplatValue(N1))
12331 NumElts = VT.getVectorNumElements();
12333 if (!MinUses || (N1->use_size() * NumElts) < MinUses)
12334 return SDValue();
12336 // Find all FDIV users of the same divisor.
12337 // Use a set because duplicates may be present in the user list.
12338 SetVector<SDNode *> Users;
12339 for (auto *U : N1->uses()) {
12340 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
12341 // This division is eligible for optimization only if global unsafe math
12342 // is enabled or if this division allows reciprocal formation.
12343 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
12344 Users.insert(U);
12348 // Now that we have the actual number of divisor uses, make sure it meets
12349 // the minimum threshold specified by the target.
12350 if ((Users.size() * NumElts) < MinUses)
12351 return SDValue();
12353 SDLoc DL(N);
12354 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
12355 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
12357 // Dividend / Divisor -> Dividend * Reciprocal
12358 for (auto *U : Users) {
12359 SDValue Dividend = U->getOperand(0);
12360 if (Dividend != FPOne) {
12361 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
12362 Reciprocal, Flags);
12363 CombineTo(U, NewNode);
12364 } else if (U != Reciprocal.getNode()) {
12365 // In the absence of fast-math-flags, this user node is always the
12366 // same node as Reciprocal, but with FMF they may be different nodes.
12367 CombineTo(U, Reciprocal);
12370 return SDValue(N, 0); // N was replaced.
12373 SDValue DAGCombiner::visitFDIV(SDNode *N) {
12374 SDValue N0 = N->getOperand(0);
12375 SDValue N1 = N->getOperand(1);
12376 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12377 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
12378 EVT VT = N->getValueType(0);
12379 SDLoc DL(N);
12380 const TargetOptions &Options = DAG.getTarget().Options;
12381 SDNodeFlags Flags = N->getFlags();
12383 // fold vector ops
12384 if (VT.isVector())
12385 if (SDValue FoldedVOp = SimplifyVBinOp(N))
12386 return FoldedVOp;
12388 // fold (fdiv c1, c2) -> c1/c2
12389 if (N0CFP && N1CFP)
12390 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
12392 if (SDValue NewSel = foldBinOpIntoSelect(N))
12393 return NewSel;
12395 if (SDValue V = combineRepeatedFPDivisors(N))
12396 return V;
12398 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) {
12399 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
12400 if (N1CFP) {
12401 // Compute the reciprocal 1.0 / c2.
12402 const APFloat &N1APF = N1CFP->getValueAPF();
12403 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
12404 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
12405 // Only do the transform if the reciprocal is a legal fp immediate that
12406 // isn't too nasty (eg NaN, denormal, ...).
12407 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
12408 (!LegalOperations ||
12409 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
12410 // backend)... we should handle this gracefully after Legalize.
12411 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
12412 TLI.isOperationLegal(ISD::ConstantFP, VT) ||
12413 TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
12414 return DAG.getNode(ISD::FMUL, DL, VT, N0,
12415 DAG.getConstantFP(Recip, DL, VT), Flags);
12418 // If this FDIV is part of a reciprocal square root, it may be folded
12419 // into a target-specific square root estimate instruction.
12420 if (N1.getOpcode() == ISD::FSQRT) {
12421 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags))
12422 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
12423 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
12424 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
12425 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
12426 Flags)) {
12427 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
12428 AddToWorklist(RV.getNode());
12429 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
12431 } else if (N1.getOpcode() == ISD::FP_ROUND &&
12432 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
12433 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
12434 Flags)) {
12435 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
12436 AddToWorklist(RV.getNode());
12437 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
12439 } else if (N1.getOpcode() == ISD::FMUL) {
12440 // Look through an FMUL. Even though this won't remove the FDIV directly,
12441 // it's still worthwhile to get rid of the FSQRT if possible.
12442 SDValue SqrtOp;
12443 SDValue OtherOp;
12444 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
12445 SqrtOp = N1.getOperand(0);
12446 OtherOp = N1.getOperand(1);
12447 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
12448 SqrtOp = N1.getOperand(1);
12449 OtherOp = N1.getOperand(0);
12451 if (SqrtOp.getNode()) {
12452 // We found a FSQRT, so try to make this fold:
12453 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
12454 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
12455 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
12456 AddToWorklist(RV.getNode());
12457 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
12462 // Fold into a reciprocal estimate and multiply instead of a real divide.
12463 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
12464 AddToWorklist(RV.getNode());
12465 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
12469 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
12470 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options,
12471 ForCodeSize)) {
12472 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options,
12473 ForCodeSize)) {
12474 // Both can be negated for free, check to see if at least one is cheaper
12475 // negated.
12476 if (LHSNeg == 2 || RHSNeg == 2)
12477 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
12478 GetNegatedExpression(N0, DAG, LegalOperations,
12479 ForCodeSize),
12480 GetNegatedExpression(N1, DAG, LegalOperations,
12481 ForCodeSize),
12482 Flags);
12486 return SDValue();
12489 SDValue DAGCombiner::visitFREM(SDNode *N) {
12490 SDValue N0 = N->getOperand(0);
12491 SDValue N1 = N->getOperand(1);
12492 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12493 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
12494 EVT VT = N->getValueType(0);
12496 // fold (frem c1, c2) -> fmod(c1,c2)
12497 if (N0CFP && N1CFP)
12498 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
12500 if (SDValue NewSel = foldBinOpIntoSelect(N))
12501 return NewSel;
12503 return SDValue();
12506 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
12507 SDNodeFlags Flags = N->getFlags();
12508 if (!DAG.getTarget().Options.UnsafeFPMath &&
12509 !Flags.hasApproximateFuncs())
12510 return SDValue();
12512 SDValue N0 = N->getOperand(0);
12513 if (TLI.isFsqrtCheap(N0, DAG))
12514 return SDValue();
12516 // FSQRT nodes have flags that propagate to the created nodes.
12517 return buildSqrtEstimate(N0, Flags);
12520 /// copysign(x, fp_extend(y)) -> copysign(x, y)
12521 /// copysign(x, fp_round(y)) -> copysign(x, y)
12522 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
12523 SDValue N1 = N->getOperand(1);
12524 if ((N1.getOpcode() == ISD::FP_EXTEND ||
12525 N1.getOpcode() == ISD::FP_ROUND)) {
12526 // Do not optimize out type conversion of f128 type yet.
12527 // For some targets like x86_64, configuration is changed to keep one f128
12528 // value in one SSE register, but instruction selection cannot handle
12529 // FCOPYSIGN on SSE registers yet.
12530 EVT N1VT = N1->getValueType(0);
12531 EVT N1Op0VT = N1->getOperand(0).getValueType();
12532 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
12534 return false;
12537 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
12538 SDValue N0 = N->getOperand(0);
12539 SDValue N1 = N->getOperand(1);
12540 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
12541 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
12542 EVT VT = N->getValueType(0);
12544 if (N0CFP && N1CFP) // Constant fold
12545 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
12547 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) {
12548 const APFloat &V = N1C->getValueAPF();
12549 // copysign(x, c1) -> fabs(x) iff ispos(c1)
12550 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
12551 if (!V.isNegative()) {
12552 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
12553 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
12554 } else {
12555 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
12556 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
12557 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
12561 // copysign(fabs(x), y) -> copysign(x, y)
12562 // copysign(fneg(x), y) -> copysign(x, y)
12563 // copysign(copysign(x,z), y) -> copysign(x, y)
12564 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
12565 N0.getOpcode() == ISD::FCOPYSIGN)
12566 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
12568 // copysign(x, abs(y)) -> abs(x)
12569 if (N1.getOpcode() == ISD::FABS)
12570 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
12572 // copysign(x, copysign(y,z)) -> copysign(x, z)
12573 if (N1.getOpcode() == ISD::FCOPYSIGN)
12574 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
12576 // copysign(x, fp_extend(y)) -> copysign(x, y)
12577 // copysign(x, fp_round(y)) -> copysign(x, y)
12578 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
12579 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
12581 return SDValue();
12584 SDValue DAGCombiner::visitFPOW(SDNode *N) {
12585 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1));
12586 if (!ExponentC)
12587 return SDValue();
12589 // Try to convert x ** (1/3) into cube root.
12590 // TODO: Handle the various flavors of long double.
12591 // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
12592 // Some range near 1/3 should be fine.
12593 EVT VT = N->getValueType(0);
12594 if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) ||
12595 (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) {
12596 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
12597 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
12598 // pow(-val, 1/3) = nan; cbrt(-val) = -num.
12599 // For regular numbers, rounding may cause the results to differ.
12600 // Therefore, we require { nsz ninf nnan afn } for this transform.
12601 // TODO: We could select out the special cases if we don't have nsz/ninf.
12602 SDNodeFlags Flags = N->getFlags();
12603 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() ||
12604 !Flags.hasApproximateFuncs())
12605 return SDValue();
12607 // Do not create a cbrt() libcall if the target does not have it, and do not
12608 // turn a pow that has lowering support into a cbrt() libcall.
12609 if (!DAG.getLibInfo().has(LibFunc_cbrt) ||
12610 (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) &&
12611 DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT)))
12612 return SDValue();
12614 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0), Flags);
12617 // Try to convert x ** (1/4) and x ** (3/4) into square roots.
12618 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
12619 // TODO: This could be extended (using a target hook) to handle smaller
12620 // power-of-2 fractional exponents.
12621 bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25);
12622 bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75);
12623 if (ExponentIs025 || ExponentIs075) {
12624 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
12625 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
12626 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
12627 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
12628 // For regular numbers, rounding may cause the results to differ.
12629 // Therefore, we require { nsz ninf afn } for this transform.
12630 // TODO: We could select out the special cases if we don't have nsz/ninf.
12631 SDNodeFlags Flags = N->getFlags();
12633 // We only need no signed zeros for the 0.25 case.
12634 if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() ||
12635 !Flags.hasApproximateFuncs())
12636 return SDValue();
12638 // Don't double the number of libcalls. We are trying to inline fast code.
12639 if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT))
12640 return SDValue();
12642 // Assume that libcalls are the smallest code.
12643 // TODO: This restriction should probably be lifted for vectors.
12644 if (DAG.getMachineFunction().getFunction().hasOptSize())
12645 return SDValue();
12647 // pow(X, 0.25) --> sqrt(sqrt(X))
12648 SDLoc DL(N);
12649 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0), Flags);
12650 SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt, Flags);
12651 if (ExponentIs025)
12652 return SqrtSqrt;
12653 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
12654 return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt, Flags);
12657 return SDValue();
12660 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
12661 const TargetLowering &TLI) {
12662 // This optimization is guarded by a function attribute because it may produce
12663 // unexpected results. Ie, programs may be relying on the platform-specific
12664 // undefined behavior when the float-to-int conversion overflows.
12665 const Function &F = DAG.getMachineFunction().getFunction();
12666 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow");
12667 if (StrictOverflow.getValueAsString().equals("false"))
12668 return SDValue();
12670 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
12671 // replacing casts with a libcall. We also must be allowed to ignore -0.0
12672 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
12673 // conversions would return +0.0.
12674 // FIXME: We should be able to use node-level FMF here.
12675 // TODO: If strict math, should we use FABS (+ range check for signed cast)?
12676 EVT VT = N->getValueType(0);
12677 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) ||
12678 !DAG.getTarget().Options.NoSignedZerosFPMath)
12679 return SDValue();
12681 // fptosi/fptoui round towards zero, so converting from FP to integer and
12682 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
12683 SDValue N0 = N->getOperand(0);
12684 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
12685 N0.getOperand(0).getValueType() == VT)
12686 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
12688 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
12689 N0.getOperand(0).getValueType() == VT)
12690 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
12692 return SDValue();
12695 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
12696 SDValue N0 = N->getOperand(0);
12697 EVT VT = N->getValueType(0);
12698 EVT OpVT = N0.getValueType();
12700 // [us]itofp(undef) = 0, because the result value is bounded.
12701 if (N0.isUndef())
12702 return DAG.getConstantFP(0.0, SDLoc(N), VT);
12704 // fold (sint_to_fp c1) -> c1fp
12705 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
12706 // ...but only if the target supports immediate floating-point values
12707 (!LegalOperations ||
12708 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
12709 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
12711 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
12712 // but UINT_TO_FP is legal on this target, try to convert.
12713 if (!hasOperation(ISD::SINT_TO_FP, OpVT) &&
12714 hasOperation(ISD::UINT_TO_FP, OpVT)) {
12715 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
12716 if (DAG.SignBitIsZero(N0))
12717 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
12720 // The next optimizations are desirable only if SELECT_CC can be lowered.
12721 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
12722 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12723 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
12724 !VT.isVector() &&
12725 (!LegalOperations ||
12726 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
12727 SDLoc DL(N);
12728 SDValue Ops[] =
12729 { N0.getOperand(0), N0.getOperand(1),
12730 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
12731 N0.getOperand(2) };
12732 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
12735 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
12736 // (select_cc x, y, 1.0, 0.0,, cc)
12737 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
12738 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
12739 (!LegalOperations ||
12740 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
12741 SDLoc DL(N);
12742 SDValue Ops[] =
12743 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
12744 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
12745 N0.getOperand(0).getOperand(2) };
12746 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
12750 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
12751 return FTrunc;
12753 return SDValue();
12756 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
12757 SDValue N0 = N->getOperand(0);
12758 EVT VT = N->getValueType(0);
12759 EVT OpVT = N0.getValueType();
12761 // [us]itofp(undef) = 0, because the result value is bounded.
12762 if (N0.isUndef())
12763 return DAG.getConstantFP(0.0, SDLoc(N), VT);
12765 // fold (uint_to_fp c1) -> c1fp
12766 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
12767 // ...but only if the target supports immediate floating-point values
12768 (!LegalOperations ||
12769 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
12770 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
12772 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
12773 // but SINT_TO_FP is legal on this target, try to convert.
12774 if (!hasOperation(ISD::UINT_TO_FP, OpVT) &&
12775 hasOperation(ISD::SINT_TO_FP, OpVT)) {
12776 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
12777 if (DAG.SignBitIsZero(N0))
12778 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
12781 // The next optimizations are desirable only if SELECT_CC can be lowered.
12782 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
12783 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12784 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
12785 (!LegalOperations ||
12786 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
12787 SDLoc DL(N);
12788 SDValue Ops[] =
12789 { N0.getOperand(0), N0.getOperand(1),
12790 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
12791 N0.getOperand(2) };
12792 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
12796 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
12797 return FTrunc;
12799 return SDValue();
12802 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
12803 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
12804 SDValue N0 = N->getOperand(0);
12805 EVT VT = N->getValueType(0);
12807 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
12808 return SDValue();
12810 SDValue Src = N0.getOperand(0);
12811 EVT SrcVT = Src.getValueType();
12812 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
12813 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
12815 // We can safely assume the conversion won't overflow the output range,
12816 // because (for example) (uint8_t)18293.f is undefined behavior.
12818 // Since we can assume the conversion won't overflow, our decision as to
12819 // whether the input will fit in the float should depend on the minimum
12820 // of the input range and output range.
12822 // This means this is also safe for a signed input and unsigned output, since
12823 // a negative input would lead to undefined behavior.
12824 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
12825 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
12826 unsigned ActualSize = std::min(InputSize, OutputSize);
12827 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
12829 // We can only fold away the float conversion if the input range can be
12830 // represented exactly in the float range.
12831 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
12832 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
12833 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
12834 : ISD::ZERO_EXTEND;
12835 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
12837 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
12838 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
12839 return DAG.getBitcast(VT, Src);
12841 return SDValue();
12844 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
12845 SDValue N0 = N->getOperand(0);
12846 EVT VT = N->getValueType(0);
12848 // fold (fp_to_sint undef) -> undef
12849 if (N0.isUndef())
12850 return DAG.getUNDEF(VT);
12852 // fold (fp_to_sint c1fp) -> c1
12853 if (isConstantFPBuildVectorOrConstantFP(N0))
12854 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
12856 return FoldIntToFPToInt(N, DAG);
12859 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
12860 SDValue N0 = N->getOperand(0);
12861 EVT VT = N->getValueType(0);
12863 // fold (fp_to_uint undef) -> undef
12864 if (N0.isUndef())
12865 return DAG.getUNDEF(VT);
12867 // fold (fp_to_uint c1fp) -> c1
12868 if (isConstantFPBuildVectorOrConstantFP(N0))
12869 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
12871 return FoldIntToFPToInt(N, DAG);
12874 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
12875 SDValue N0 = N->getOperand(0);
12876 SDValue N1 = N->getOperand(1);
12877 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12878 EVT VT = N->getValueType(0);
12880 // fold (fp_round c1fp) -> c1fp
12881 if (N0CFP)
12882 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
12884 // fold (fp_round (fp_extend x)) -> x
12885 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
12886 return N0.getOperand(0);
12888 // fold (fp_round (fp_round x)) -> (fp_round x)
12889 if (N0.getOpcode() == ISD::FP_ROUND) {
12890 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
12891 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
12893 // Skip this folding if it results in an fp_round from f80 to f16.
12895 // f80 to f16 always generates an expensive (and as yet, unimplemented)
12896 // libcall to __truncxfhf2 instead of selecting native f16 conversion
12897 // instructions from f32 or f64. Moreover, the first (value-preserving)
12898 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
12899 // x86.
12900 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
12901 return SDValue();
12903 // If the first fp_round isn't a value preserving truncation, it might
12904 // introduce a tie in the second fp_round, that wouldn't occur in the
12905 // single-step fp_round we want to fold to.
12906 // In other words, double rounding isn't the same as rounding.
12907 // Also, this is a value preserving truncation iff both fp_round's are.
12908 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
12909 SDLoc DL(N);
12910 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
12911 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
12915 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
12916 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
12917 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
12918 N0.getOperand(0), N1);
12919 AddToWorklist(Tmp.getNode());
12920 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
12921 Tmp, N0.getOperand(1));
12924 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
12925 return NewVSel;
12927 return SDValue();
12930 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
12931 SDValue N0 = N->getOperand(0);
12932 EVT VT = N->getValueType(0);
12933 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12936 // fold (fp_round_inreg c1fp) -> c1fp
12937 if (N0CFP && isTypeLegal(EVT)) {
12938 SDLoc DL(N);
12939 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
12940 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
12943 return SDValue();
12946 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
12947 SDValue N0 = N->getOperand(0);
12948 EVT VT = N->getValueType(0);
12950 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
12951 if (N->hasOneUse() &&
12952 N->use_begin()->getOpcode() == ISD::FP_ROUND)
12953 return SDValue();
12955 // fold (fp_extend c1fp) -> c1fp
12956 if (isConstantFPBuildVectorOrConstantFP(N0))
12957 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
12959 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
12960 if (N0.getOpcode() == ISD::FP16_TO_FP &&
12961 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
12962 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
12964 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
12965 // value of X.
12966 if (N0.getOpcode() == ISD::FP_ROUND
12967 && N0.getConstantOperandVal(1) == 1) {
12968 SDValue In = N0.getOperand(0);
12969 if (In.getValueType() == VT) return In;
12970 if (VT.bitsLT(In.getValueType()))
12971 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
12972 In, N0.getOperand(1));
12973 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
12976 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
12977 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12978 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
12979 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
12980 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
12981 LN0->getChain(),
12982 LN0->getBasePtr(), N0.getValueType(),
12983 LN0->getMemOperand());
12984 CombineTo(N, ExtLoad);
12985 CombineTo(N0.getNode(),
12986 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
12987 N0.getValueType(), ExtLoad,
12988 DAG.getIntPtrConstant(1, SDLoc(N0))),
12989 ExtLoad.getValue(1));
12990 return SDValue(N, 0); // Return N so it doesn't get rechecked!
12993 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
12994 return NewVSel;
12996 return SDValue();
12999 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
13000 SDValue N0 = N->getOperand(0);
13001 EVT VT = N->getValueType(0);
13003 // fold (fceil c1) -> fceil(c1)
13004 if (isConstantFPBuildVectorOrConstantFP(N0))
13005 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
13007 return SDValue();
13010 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
13011 SDValue N0 = N->getOperand(0);
13012 EVT VT = N->getValueType(0);
13014 // fold (ftrunc c1) -> ftrunc(c1)
13015 if (isConstantFPBuildVectorOrConstantFP(N0))
13016 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
13018 // fold ftrunc (known rounded int x) -> x
13019 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
13020 // likely to be generated to extract integer from a rounded floating value.
13021 switch (N0.getOpcode()) {
13022 default: break;
13023 case ISD::FRINT:
13024 case ISD::FTRUNC:
13025 case ISD::FNEARBYINT:
13026 case ISD::FFLOOR:
13027 case ISD::FCEIL:
13028 return N0;
13031 return SDValue();
13034 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
13035 SDValue N0 = N->getOperand(0);
13036 EVT VT = N->getValueType(0);
13038 // fold (ffloor c1) -> ffloor(c1)
13039 if (isConstantFPBuildVectorOrConstantFP(N0))
13040 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
13042 return SDValue();
13045 // FIXME: FNEG and FABS have a lot in common; refactor.
13046 SDValue DAGCombiner::visitFNEG(SDNode *N) {
13047 SDValue N0 = N->getOperand(0);
13048 EVT VT = N->getValueType(0);
13050 // Constant fold FNEG.
13051 if (isConstantFPBuildVectorOrConstantFP(N0))
13052 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
13054 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
13055 &DAG.getTarget().Options, ForCodeSize))
13056 return GetNegatedExpression(N0, DAG, LegalOperations, ForCodeSize);
13058 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
13059 // constant pool values.
13060 if (!TLI.isFNegFree(VT) &&
13061 N0.getOpcode() == ISD::BITCAST &&
13062 N0.getNode()->hasOneUse()) {
13063 SDValue Int = N0.getOperand(0);
13064 EVT IntVT = Int.getValueType();
13065 if (IntVT.isInteger() && !IntVT.isVector()) {
13066 APInt SignMask;
13067 if (N0.getValueType().isVector()) {
13068 // For a vector, get a mask such as 0x80... per scalar element
13069 // and splat it.
13070 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
13071 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
13072 } else {
13073 // For a scalar, just generate 0x80...
13074 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
13076 SDLoc DL0(N0);
13077 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
13078 DAG.getConstant(SignMask, DL0, IntVT));
13079 AddToWorklist(Int.getNode());
13080 return DAG.getBitcast(VT, Int);
13084 // (fneg (fmul c, x)) -> (fmul -c, x)
13085 if (N0.getOpcode() == ISD::FMUL &&
13086 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
13087 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
13088 if (CFP1) {
13089 APFloat CVal = CFP1->getValueAPF();
13090 CVal.changeSign();
13091 if (Level >= AfterLegalizeDAG &&
13092 (TLI.isFPImmLegal(CVal, VT, ForCodeSize) ||
13093 TLI.isOperationLegal(ISD::ConstantFP, VT)))
13094 return DAG.getNode(
13095 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
13096 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
13097 N0->getFlags());
13101 return SDValue();
13104 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N,
13105 APFloat (*Op)(const APFloat &, const APFloat &)) {
13106 SDValue N0 = N->getOperand(0);
13107 SDValue N1 = N->getOperand(1);
13108 EVT VT = N->getValueType(0);
13109 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
13110 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
13112 if (N0CFP && N1CFP) {
13113 const APFloat &C0 = N0CFP->getValueAPF();
13114 const APFloat &C1 = N1CFP->getValueAPF();
13115 return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT);
13118 // Canonicalize to constant on RHS.
13119 if (isConstantFPBuildVectorOrConstantFP(N0) &&
13120 !isConstantFPBuildVectorOrConstantFP(N1))
13121 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
13123 return SDValue();
13126 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
13127 return visitFMinMax(DAG, N, minnum);
13130 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
13131 return visitFMinMax(DAG, N, maxnum);
13134 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) {
13135 return visitFMinMax(DAG, N, minimum);
13138 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) {
13139 return visitFMinMax(DAG, N, maximum);
13142 SDValue DAGCombiner::visitFABS(SDNode *N) {
13143 SDValue N0 = N->getOperand(0);
13144 EVT VT = N->getValueType(0);
13146 // fold (fabs c1) -> fabs(c1)
13147 if (isConstantFPBuildVectorOrConstantFP(N0))
13148 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
13150 // fold (fabs (fabs x)) -> (fabs x)
13151 if (N0.getOpcode() == ISD::FABS)
13152 return N->getOperand(0);
13154 // fold (fabs (fneg x)) -> (fabs x)
13155 // fold (fabs (fcopysign x, y)) -> (fabs x)
13156 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
13157 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
13159 // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads.
13160 if (!TLI.isFAbsFree(VT) && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
13161 SDValue Int = N0.getOperand(0);
13162 EVT IntVT = Int.getValueType();
13163 if (IntVT.isInteger() && !IntVT.isVector()) {
13164 APInt SignMask;
13165 if (N0.getValueType().isVector()) {
13166 // For a vector, get a mask such as 0x7f... per scalar element
13167 // and splat it.
13168 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
13169 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
13170 } else {
13171 // For a scalar, just generate 0x7f...
13172 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
13174 SDLoc DL(N0);
13175 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
13176 DAG.getConstant(SignMask, DL, IntVT));
13177 AddToWorklist(Int.getNode());
13178 return DAG.getBitcast(N->getValueType(0), Int);
13182 return SDValue();
13185 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
13186 SDValue Chain = N->getOperand(0);
13187 SDValue N1 = N->getOperand(1);
13188 SDValue N2 = N->getOperand(2);
13190 // If N is a constant we could fold this into a fallthrough or unconditional
13191 // branch. However that doesn't happen very often in normal code, because
13192 // Instcombine/SimplifyCFG should have handled the available opportunities.
13193 // If we did this folding here, it would be necessary to update the
13194 // MachineBasicBlock CFG, which is awkward.
13196 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
13197 // on the target.
13198 if (N1.getOpcode() == ISD::SETCC &&
13199 TLI.isOperationLegalOrCustom(ISD::BR_CC,
13200 N1.getOperand(0).getValueType())) {
13201 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
13202 Chain, N1.getOperand(2),
13203 N1.getOperand(0), N1.getOperand(1), N2);
13206 if (N1.hasOneUse()) {
13207 if (SDValue NewN1 = rebuildSetCC(N1))
13208 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2);
13211 return SDValue();
13214 SDValue DAGCombiner::rebuildSetCC(SDValue N) {
13215 if (N.getOpcode() == ISD::SRL ||
13216 (N.getOpcode() == ISD::TRUNCATE &&
13217 (N.getOperand(0).hasOneUse() &&
13218 N.getOperand(0).getOpcode() == ISD::SRL))) {
13219 // Look pass the truncate.
13220 if (N.getOpcode() == ISD::TRUNCATE)
13221 N = N.getOperand(0);
13223 // Match this pattern so that we can generate simpler code:
13225 // %a = ...
13226 // %b = and i32 %a, 2
13227 // %c = srl i32 %b, 1
13228 // brcond i32 %c ...
13230 // into
13232 // %a = ...
13233 // %b = and i32 %a, 2
13234 // %c = setcc eq %b, 0
13235 // brcond %c ...
13237 // This applies only when the AND constant value has one bit set and the
13238 // SRL constant is equal to the log2 of the AND constant. The back-end is
13239 // smart enough to convert the result into a TEST/JMP sequence.
13240 SDValue Op0 = N.getOperand(0);
13241 SDValue Op1 = N.getOperand(1);
13243 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
13244 SDValue AndOp1 = Op0.getOperand(1);
13246 if (AndOp1.getOpcode() == ISD::Constant) {
13247 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
13249 if (AndConst.isPowerOf2() &&
13250 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
13251 SDLoc DL(N);
13252 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
13253 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
13254 ISD::SETNE);
13260 // Transform br(xor(x, y)) -> br(x != y)
13261 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
13262 if (N.getOpcode() == ISD::XOR) {
13263 // Because we may call this on a speculatively constructed
13264 // SimplifiedSetCC Node, we need to simplify this node first.
13265 // Ideally this should be folded into SimplifySetCC and not
13266 // here. For now, grab a handle to N so we don't lose it from
13267 // replacements interal to the visit.
13268 HandleSDNode XORHandle(N);
13269 while (N.getOpcode() == ISD::XOR) {
13270 SDValue Tmp = visitXOR(N.getNode());
13271 // No simplification done.
13272 if (!Tmp.getNode())
13273 break;
13274 // Returning N is form in-visit replacement that may invalidated
13275 // N. Grab value from Handle.
13276 if (Tmp.getNode() == N.getNode())
13277 N = XORHandle.getValue();
13278 else // Node simplified. Try simplifying again.
13279 N = Tmp;
13282 if (N.getOpcode() != ISD::XOR)
13283 return N;
13285 SDNode *TheXor = N.getNode();
13287 SDValue Op0 = TheXor->getOperand(0);
13288 SDValue Op1 = TheXor->getOperand(1);
13290 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
13291 bool Equal = false;
13292 if (isOneConstant(Op0) && Op0.hasOneUse() &&
13293 Op0.getOpcode() == ISD::XOR) {
13294 TheXor = Op0.getNode();
13295 Equal = true;
13298 EVT SetCCVT = N.getValueType();
13299 if (LegalTypes)
13300 SetCCVT = getSetCCResultType(SetCCVT);
13301 // Replace the uses of XOR with SETCC
13302 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1,
13303 Equal ? ISD::SETEQ : ISD::SETNE);
13307 return SDValue();
13310 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
13312 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
13313 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
13314 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
13316 // If N is a constant we could fold this into a fallthrough or unconditional
13317 // branch. However that doesn't happen very often in normal code, because
13318 // Instcombine/SimplifyCFG should have handled the available opportunities.
13319 // If we did this folding here, it would be necessary to update the
13320 // MachineBasicBlock CFG, which is awkward.
13322 // Use SimplifySetCC to simplify SETCC's.
13323 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
13324 CondLHS, CondRHS, CC->get(), SDLoc(N),
13325 false);
13326 if (Simp.getNode()) AddToWorklist(Simp.getNode());
13328 // fold to a simpler setcc
13329 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
13330 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
13331 N->getOperand(0), Simp.getOperand(2),
13332 Simp.getOperand(0), Simp.getOperand(1),
13333 N->getOperand(4));
13335 return SDValue();
13338 /// Return true if 'Use' is a load or a store that uses N as its base pointer
13339 /// and that N may be folded in the load / store addressing mode.
13340 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
13341 SelectionDAG &DAG,
13342 const TargetLowering &TLI) {
13343 EVT VT;
13344 unsigned AS;
13346 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
13347 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
13348 return false;
13349 VT = LD->getMemoryVT();
13350 AS = LD->getAddressSpace();
13351 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
13352 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
13353 return false;
13354 VT = ST->getMemoryVT();
13355 AS = ST->getAddressSpace();
13356 } else
13357 return false;
13359 TargetLowering::AddrMode AM;
13360 if (N->getOpcode() == ISD::ADD) {
13361 AM.HasBaseReg = true;
13362 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
13363 if (Offset)
13364 // [reg +/- imm]
13365 AM.BaseOffs = Offset->getSExtValue();
13366 else
13367 // [reg +/- reg]
13368 AM.Scale = 1;
13369 } else if (N->getOpcode() == ISD::SUB) {
13370 AM.HasBaseReg = true;
13371 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
13372 if (Offset)
13373 // [reg +/- imm]
13374 AM.BaseOffs = -Offset->getSExtValue();
13375 else
13376 // [reg +/- reg]
13377 AM.Scale = 1;
13378 } else
13379 return false;
13381 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
13382 VT.getTypeForEVT(*DAG.getContext()), AS);
13385 /// Try turning a load/store into a pre-indexed load/store when the base
13386 /// pointer is an add or subtract and it has other uses besides the load/store.
13387 /// After the transformation, the new indexed load/store has effectively folded
13388 /// the add/subtract in and all of its other uses are redirected to the
13389 /// new load/store.
13390 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
13391 if (Level < AfterLegalizeDAG)
13392 return false;
13394 bool isLoad = true;
13395 SDValue Ptr;
13396 EVT VT;
13397 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13398 if (LD->isIndexed())
13399 return false;
13400 VT = LD->getMemoryVT();
13401 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
13402 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
13403 return false;
13404 Ptr = LD->getBasePtr();
13405 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13406 if (ST->isIndexed())
13407 return false;
13408 VT = ST->getMemoryVT();
13409 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
13410 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
13411 return false;
13412 Ptr = ST->getBasePtr();
13413 isLoad = false;
13414 } else {
13415 return false;
13418 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
13419 // out. There is no reason to make this a preinc/predec.
13420 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
13421 Ptr.getNode()->hasOneUse())
13422 return false;
13424 // Ask the target to do addressing mode selection.
13425 SDValue BasePtr;
13426 SDValue Offset;
13427 ISD::MemIndexedMode AM = ISD::UNINDEXED;
13428 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
13429 return false;
13431 // Backends without true r+i pre-indexed forms may need to pass a
13432 // constant base with a variable offset so that constant coercion
13433 // will work with the patterns in canonical form.
13434 bool Swapped = false;
13435 if (isa<ConstantSDNode>(BasePtr)) {
13436 std::swap(BasePtr, Offset);
13437 Swapped = true;
13440 // Don't create a indexed load / store with zero offset.
13441 if (isNullConstant(Offset))
13442 return false;
13444 // Try turning it into a pre-indexed load / store except when:
13445 // 1) The new base ptr is a frame index.
13446 // 2) If N is a store and the new base ptr is either the same as or is a
13447 // predecessor of the value being stored.
13448 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
13449 // that would create a cycle.
13450 // 4) All uses are load / store ops that use it as old base ptr.
13452 // Check #1. Preinc'ing a frame index would require copying the stack pointer
13453 // (plus the implicit offset) to a register to preinc anyway.
13454 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
13455 return false;
13457 // Check #2.
13458 if (!isLoad) {
13459 SDValue Val = cast<StoreSDNode>(N)->getValue();
13461 // Would require a copy.
13462 if (Val == BasePtr)
13463 return false;
13465 // Would create a cycle.
13466 if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode()))
13467 return false;
13470 // Caches for hasPredecessorHelper.
13471 SmallPtrSet<const SDNode *, 32> Visited;
13472 SmallVector<const SDNode *, 16> Worklist;
13473 Worklist.push_back(N);
13475 // If the offset is a constant, there may be other adds of constants that
13476 // can be folded with this one. We should do this to avoid having to keep
13477 // a copy of the original base pointer.
13478 SmallVector<SDNode *, 16> OtherUses;
13479 if (isa<ConstantSDNode>(Offset))
13480 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
13481 UE = BasePtr.getNode()->use_end();
13482 UI != UE; ++UI) {
13483 SDUse &Use = UI.getUse();
13484 // Skip the use that is Ptr and uses of other results from BasePtr's
13485 // node (important for nodes that return multiple results).
13486 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
13487 continue;
13489 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
13490 continue;
13492 if (Use.getUser()->getOpcode() != ISD::ADD &&
13493 Use.getUser()->getOpcode() != ISD::SUB) {
13494 OtherUses.clear();
13495 break;
13498 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
13499 if (!isa<ConstantSDNode>(Op1)) {
13500 OtherUses.clear();
13501 break;
13504 // FIXME: In some cases, we can be smarter about this.
13505 if (Op1.getValueType() != Offset.getValueType()) {
13506 OtherUses.clear();
13507 break;
13510 OtherUses.push_back(Use.getUser());
13513 if (Swapped)
13514 std::swap(BasePtr, Offset);
13516 // Now check for #3 and #4.
13517 bool RealUse = false;
13519 for (SDNode *Use : Ptr.getNode()->uses()) {
13520 if (Use == N)
13521 continue;
13522 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
13523 return false;
13525 // If Ptr may be folded in addressing mode of other use, then it's
13526 // not profitable to do this transformation.
13527 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
13528 RealUse = true;
13531 if (!RealUse)
13532 return false;
13534 SDValue Result;
13535 if (isLoad)
13536 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
13537 BasePtr, Offset, AM);
13538 else
13539 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
13540 BasePtr, Offset, AM);
13541 ++PreIndexedNodes;
13542 ++NodesCombined;
13543 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
13544 Result.getNode()->dump(&DAG); dbgs() << '\n');
13545 WorklistRemover DeadNodes(*this);
13546 if (isLoad) {
13547 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
13548 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
13549 } else {
13550 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
13553 // Finally, since the node is now dead, remove it from the graph.
13554 deleteAndRecombine(N);
13556 if (Swapped)
13557 std::swap(BasePtr, Offset);
13559 // Replace other uses of BasePtr that can be updated to use Ptr
13560 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
13561 unsigned OffsetIdx = 1;
13562 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
13563 OffsetIdx = 0;
13564 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
13565 BasePtr.getNode() && "Expected BasePtr operand");
13567 // We need to replace ptr0 in the following expression:
13568 // x0 * offset0 + y0 * ptr0 = t0
13569 // knowing that
13570 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
13572 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
13573 // indexed load/store and the expression that needs to be re-written.
13575 // Therefore, we have:
13576 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
13578 ConstantSDNode *CN =
13579 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
13580 int X0, X1, Y0, Y1;
13581 const APInt &Offset0 = CN->getAPIntValue();
13582 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
13584 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
13585 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
13586 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
13587 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
13589 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
13591 APInt CNV = Offset0;
13592 if (X0 < 0) CNV = -CNV;
13593 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
13594 else CNV = CNV - Offset1;
13596 SDLoc DL(OtherUses[i]);
13598 // We can now generate the new expression.
13599 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
13600 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
13602 SDValue NewUse = DAG.getNode(Opcode,
13604 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
13605 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
13606 deleteAndRecombine(OtherUses[i]);
13609 // Replace the uses of Ptr with uses of the updated base value.
13610 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
13611 deleteAndRecombine(Ptr.getNode());
13612 AddToWorklist(Result.getNode());
13614 return true;
13617 /// Try to combine a load/store with a add/sub of the base pointer node into a
13618 /// post-indexed load/store. The transformation folded the add/subtract into the
13619 /// new indexed load/store effectively and all of its uses are redirected to the
13620 /// new load/store.
13621 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
13622 if (Level < AfterLegalizeDAG)
13623 return false;
13625 bool isLoad = true;
13626 SDValue Ptr;
13627 EVT VT;
13628 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13629 if (LD->isIndexed())
13630 return false;
13631 VT = LD->getMemoryVT();
13632 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
13633 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
13634 return false;
13635 Ptr = LD->getBasePtr();
13636 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13637 if (ST->isIndexed())
13638 return false;
13639 VT = ST->getMemoryVT();
13640 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
13641 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
13642 return false;
13643 Ptr = ST->getBasePtr();
13644 isLoad = false;
13645 } else {
13646 return false;
13649 if (Ptr.getNode()->hasOneUse())
13650 return false;
13652 for (SDNode *Op : Ptr.getNode()->uses()) {
13653 if (Op == N ||
13654 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
13655 continue;
13657 SDValue BasePtr;
13658 SDValue Offset;
13659 ISD::MemIndexedMode AM = ISD::UNINDEXED;
13660 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
13661 // Don't create a indexed load / store with zero offset.
13662 if (isNullConstant(Offset))
13663 continue;
13665 // Try turning it into a post-indexed load / store except when
13666 // 1) All uses are load / store ops that use it as base ptr (and
13667 // it may be folded as addressing mmode).
13668 // 2) Op must be independent of N, i.e. Op is neither a predecessor
13669 // nor a successor of N. Otherwise, if Op is folded that would
13670 // create a cycle.
13672 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
13673 continue;
13675 // Check for #1.
13676 bool TryNext = false;
13677 for (SDNode *Use : BasePtr.getNode()->uses()) {
13678 if (Use == Ptr.getNode())
13679 continue;
13681 // If all the uses are load / store addresses, then don't do the
13682 // transformation.
13683 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
13684 bool RealUse = false;
13685 for (SDNode *UseUse : Use->uses()) {
13686 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
13687 RealUse = true;
13690 if (!RealUse) {
13691 TryNext = true;
13692 break;
13697 if (TryNext)
13698 continue;
13700 // Check for #2.
13701 SmallPtrSet<const SDNode *, 32> Visited;
13702 SmallVector<const SDNode *, 8> Worklist;
13703 // Ptr is predecessor to both N and Op.
13704 Visited.insert(Ptr.getNode());
13705 Worklist.push_back(N);
13706 Worklist.push_back(Op);
13707 if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) &&
13708 !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) {
13709 SDValue Result = isLoad
13710 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
13711 BasePtr, Offset, AM)
13712 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
13713 BasePtr, Offset, AM);
13714 ++PostIndexedNodes;
13715 ++NodesCombined;
13716 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);
13717 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);
13718 dbgs() << '\n');
13719 WorklistRemover DeadNodes(*this);
13720 if (isLoad) {
13721 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
13722 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
13723 } else {
13724 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
13727 // Finally, since the node is now dead, remove it from the graph.
13728 deleteAndRecombine(N);
13730 // Replace the uses of Use with uses of the updated base value.
13731 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
13732 Result.getValue(isLoad ? 1 : 0));
13733 deleteAndRecombine(Op);
13734 return true;
13739 return false;
13742 /// Return the base-pointer arithmetic from an indexed \p LD.
13743 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
13744 ISD::MemIndexedMode AM = LD->getAddressingMode();
13745 assert(AM != ISD::UNINDEXED);
13746 SDValue BP = LD->getOperand(1);
13747 SDValue Inc = LD->getOperand(2);
13749 // Some backends use TargetConstants for load offsets, but don't expect
13750 // TargetConstants in general ADD nodes. We can convert these constants into
13751 // regular Constants (if the constant is not opaque).
13752 assert((Inc.getOpcode() != ISD::TargetConstant ||
13753 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
13754 "Cannot split out indexing using opaque target constants");
13755 if (Inc.getOpcode() == ISD::TargetConstant) {
13756 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
13757 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
13758 ConstInc->getValueType(0));
13761 unsigned Opc =
13762 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
13763 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
13766 static inline int numVectorEltsOrZero(EVT T) {
13767 return T.isVector() ? T.getVectorNumElements() : 0;
13770 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) {
13771 Val = ST->getValue();
13772 EVT STType = Val.getValueType();
13773 EVT STMemType = ST->getMemoryVT();
13774 if (STType == STMemType)
13775 return true;
13776 if (isTypeLegal(STMemType))
13777 return false; // fail.
13778 if (STType.isFloatingPoint() && STMemType.isFloatingPoint() &&
13779 TLI.isOperationLegal(ISD::FTRUNC, STMemType)) {
13780 Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val);
13781 return true;
13783 if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) &&
13784 STType.isInteger() && STMemType.isInteger()) {
13785 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val);
13786 return true;
13788 if (STType.getSizeInBits() == STMemType.getSizeInBits()) {
13789 Val = DAG.getBitcast(STMemType, Val);
13790 return true;
13792 return false; // fail.
13795 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) {
13796 EVT LDMemType = LD->getMemoryVT();
13797 EVT LDType = LD->getValueType(0);
13798 assert(Val.getValueType() == LDMemType &&
13799 "Attempting to extend value of non-matching type");
13800 if (LDType == LDMemType)
13801 return true;
13802 if (LDMemType.isInteger() && LDType.isInteger()) {
13803 switch (LD->getExtensionType()) {
13804 case ISD::NON_EXTLOAD:
13805 Val = DAG.getBitcast(LDType, Val);
13806 return true;
13807 case ISD::EXTLOAD:
13808 Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val);
13809 return true;
13810 case ISD::SEXTLOAD:
13811 Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val);
13812 return true;
13813 case ISD::ZEXTLOAD:
13814 Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val);
13815 return true;
13818 return false;
13821 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) {
13822 if (OptLevel == CodeGenOpt::None || LD->isVolatile())
13823 return SDValue();
13824 SDValue Chain = LD->getOperand(0);
13825 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode());
13826 if (!ST || ST->isVolatile())
13827 return SDValue();
13829 EVT LDType = LD->getValueType(0);
13830 EVT LDMemType = LD->getMemoryVT();
13831 EVT STMemType = ST->getMemoryVT();
13832 EVT STType = ST->getValue().getValueType();
13834 BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG);
13835 BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG);
13836 int64_t Offset;
13837 if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset))
13838 return SDValue();
13840 // Normalize for Endianness. After this Offset=0 will denote that the least
13841 // significant bit in the loaded value maps to the least significant bit in
13842 // the stored value). With Offset=n (for n > 0) the loaded value starts at the
13843 // n:th least significant byte of the stored value.
13844 if (DAG.getDataLayout().isBigEndian())
13845 Offset = (STMemType.getStoreSizeInBits() -
13846 LDMemType.getStoreSizeInBits()) / 8 - Offset;
13848 // Check that the stored value cover all bits that are loaded.
13849 bool STCoversLD =
13850 (Offset >= 0) &&
13851 (Offset * 8 + LDMemType.getSizeInBits() <= STMemType.getSizeInBits());
13853 auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue {
13854 if (LD->isIndexed()) {
13855 bool IsSub = (LD->getAddressingMode() == ISD::PRE_DEC ||
13856 LD->getAddressingMode() == ISD::POST_DEC);
13857 unsigned Opc = IsSub ? ISD::SUB : ISD::ADD;
13858 SDValue Idx = DAG.getNode(Opc, SDLoc(LD), LD->getOperand(1).getValueType(),
13859 LD->getOperand(1), LD->getOperand(2));
13860 SDValue Ops[] = {Val, Idx, Chain};
13861 return CombineTo(LD, Ops, 3);
13863 return CombineTo(LD, Val, Chain);
13866 if (!STCoversLD)
13867 return SDValue();
13869 // Memory as copy space (potentially masked).
13870 if (Offset == 0 && LDType == STType && STMemType == LDMemType) {
13871 // Simple case: Direct non-truncating forwarding
13872 if (LDType.getSizeInBits() == LDMemType.getSizeInBits())
13873 return ReplaceLd(LD, ST->getValue(), Chain);
13874 // Can we model the truncate and extension with an and mask?
13875 if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() &&
13876 !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) {
13877 // Mask to size of LDMemType
13878 auto Mask =
13879 DAG.getConstant(APInt::getLowBitsSet(STType.getSizeInBits(),
13880 STMemType.getSizeInBits()),
13881 SDLoc(ST), STType);
13882 auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask);
13883 return ReplaceLd(LD, Val, Chain);
13887 // TODO: Deal with nonzero offset.
13888 if (LD->getBasePtr().isUndef() || Offset != 0)
13889 return SDValue();
13890 // Model necessary truncations / extenstions.
13891 SDValue Val;
13892 // Truncate Value To Stored Memory Size.
13893 do {
13894 if (!getTruncatedStoreValue(ST, Val))
13895 continue;
13896 if (!isTypeLegal(LDMemType))
13897 continue;
13898 if (STMemType != LDMemType) {
13899 // TODO: Support vectors? This requires extract_subvector/bitcast.
13900 if (!STMemType.isVector() && !LDMemType.isVector() &&
13901 STMemType.isInteger() && LDMemType.isInteger())
13902 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val);
13903 else
13904 continue;
13906 if (!extendLoadedValueToExtension(LD, Val))
13907 continue;
13908 return ReplaceLd(LD, Val, Chain);
13909 } while (false);
13911 // On failure, cleanup dead nodes we may have created.
13912 if (Val->use_empty())
13913 deleteAndRecombine(Val.getNode());
13914 return SDValue();
13917 SDValue DAGCombiner::visitLOAD(SDNode *N) {
13918 LoadSDNode *LD = cast<LoadSDNode>(N);
13919 SDValue Chain = LD->getChain();
13920 SDValue Ptr = LD->getBasePtr();
13922 // If load is not volatile and there are no uses of the loaded value (and
13923 // the updated indexed value in case of indexed loads), change uses of the
13924 // chain value into uses of the chain input (i.e. delete the dead load).
13925 if (!LD->isVolatile()) {
13926 if (N->getValueType(1) == MVT::Other) {
13927 // Unindexed loads.
13928 if (!N->hasAnyUseOfValue(0)) {
13929 // It's not safe to use the two value CombineTo variant here. e.g.
13930 // v1, chain2 = load chain1, loc
13931 // v2, chain3 = load chain2, loc
13932 // v3 = add v2, c
13933 // Now we replace use of chain2 with chain1. This makes the second load
13934 // isomorphic to the one we are deleting, and thus makes this load live.
13935 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
13936 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);
13937 dbgs() << "\n");
13938 WorklistRemover DeadNodes(*this);
13939 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
13940 AddUsersToWorklist(Chain.getNode());
13941 if (N->use_empty())
13942 deleteAndRecombine(N);
13944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
13946 } else {
13947 // Indexed loads.
13948 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
13950 // If this load has an opaque TargetConstant offset, then we cannot split
13951 // the indexing into an add/sub directly (that TargetConstant may not be
13952 // valid for a different type of node, and we cannot convert an opaque
13953 // target constant into a regular constant).
13954 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
13955 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
13957 if (!N->hasAnyUseOfValue(0) &&
13958 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
13959 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
13960 SDValue Index;
13961 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
13962 Index = SplitIndexingFromLoad(LD);
13963 // Try to fold the base pointer arithmetic into subsequent loads and
13964 // stores.
13965 AddUsersToWorklist(N);
13966 } else
13967 Index = DAG.getUNDEF(N->getValueType(1));
13968 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
13969 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);
13970 dbgs() << " and 2 other values\n");
13971 WorklistRemover DeadNodes(*this);
13972 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
13973 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
13974 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
13975 deleteAndRecombine(N);
13976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
13981 // If this load is directly stored, replace the load value with the stored
13982 // value.
13983 if (auto V = ForwardStoreValueToDirectLoad(LD))
13984 return V;
13986 // Try to infer better alignment information than the load already has.
13987 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
13988 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13989 if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) {
13990 SDValue NewLoad = DAG.getExtLoad(
13991 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
13992 LD->getPointerInfo(), LD->getMemoryVT(), Align,
13993 LD->getMemOperand()->getFlags(), LD->getAAInfo());
13994 // NewLoad will always be N as we are only refining the alignment
13995 assert(NewLoad.getNode() == N);
13996 (void)NewLoad;
14001 if (LD->isUnindexed()) {
14002 // Walk up chain skipping non-aliasing memory nodes.
14003 SDValue BetterChain = FindBetterChain(LD, Chain);
14005 // If there is a better chain.
14006 if (Chain != BetterChain) {
14007 SDValue ReplLoad;
14009 // Replace the chain to void dependency.
14010 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
14011 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
14012 BetterChain, Ptr, LD->getMemOperand());
14013 } else {
14014 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
14015 LD->getValueType(0),
14016 BetterChain, Ptr, LD->getMemoryVT(),
14017 LD->getMemOperand());
14020 // Create token factor to keep old chain connected.
14021 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
14022 MVT::Other, Chain, ReplLoad.getValue(1));
14024 // Replace uses with load result and token factor
14025 return CombineTo(N, ReplLoad.getValue(0), Token);
14029 // Try transforming N to an indexed load.
14030 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14031 return SDValue(N, 0);
14033 // Try to slice up N to more direct loads if the slices are mapped to
14034 // different register banks or pairing can take place.
14035 if (SliceUpLoad(N))
14036 return SDValue(N, 0);
14038 return SDValue();
14041 namespace {
14043 /// Helper structure used to slice a load in smaller loads.
14044 /// Basically a slice is obtained from the following sequence:
14045 /// Origin = load Ty1, Base
14046 /// Shift = srl Ty1 Origin, CstTy Amount
14047 /// Inst = trunc Shift to Ty2
14049 /// Then, it will be rewritten into:
14050 /// Slice = load SliceTy, Base + SliceOffset
14051 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
14053 /// SliceTy is deduced from the number of bits that are actually used to
14054 /// build Inst.
14055 struct LoadedSlice {
14056 /// Helper structure used to compute the cost of a slice.
14057 struct Cost {
14058 /// Are we optimizing for code size.
14059 bool ForCodeSize;
14061 /// Various cost.
14062 unsigned Loads = 0;
14063 unsigned Truncates = 0;
14064 unsigned CrossRegisterBanksCopies = 0;
14065 unsigned ZExts = 0;
14066 unsigned Shift = 0;
14068 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
14070 /// Get the cost of one isolated slice.
14071 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
14072 : ForCodeSize(ForCodeSize), Loads(1) {
14073 EVT TruncType = LS.Inst->getValueType(0);
14074 EVT LoadedType = LS.getLoadedType();
14075 if (TruncType != LoadedType &&
14076 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
14077 ZExts = 1;
14080 /// Account for slicing gain in the current cost.
14081 /// Slicing provide a few gains like removing a shift or a
14082 /// truncate. This method allows to grow the cost of the original
14083 /// load with the gain from this slice.
14084 void addSliceGain(const LoadedSlice &LS) {
14085 // Each slice saves a truncate.
14086 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
14087 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
14088 LS.Inst->getValueType(0)))
14089 ++Truncates;
14090 // If there is a shift amount, this slice gets rid of it.
14091 if (LS.Shift)
14092 ++Shift;
14093 // If this slice can merge a cross register bank copy, account for it.
14094 if (LS.canMergeExpensiveCrossRegisterBankCopy())
14095 ++CrossRegisterBanksCopies;
14098 Cost &operator+=(const Cost &RHS) {
14099 Loads += RHS.Loads;
14100 Truncates += RHS.Truncates;
14101 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
14102 ZExts += RHS.ZExts;
14103 Shift += RHS.Shift;
14104 return *this;
14107 bool operator==(const Cost &RHS) const {
14108 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
14109 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
14110 ZExts == RHS.ZExts && Shift == RHS.Shift;
14113 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
14115 bool operator<(const Cost &RHS) const {
14116 // Assume cross register banks copies are as expensive as loads.
14117 // FIXME: Do we want some more target hooks?
14118 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
14119 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
14120 // Unless we are optimizing for code size, consider the
14121 // expensive operation first.
14122 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
14123 return ExpensiveOpsLHS < ExpensiveOpsRHS;
14124 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
14125 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
14128 bool operator>(const Cost &RHS) const { return RHS < *this; }
14130 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
14132 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
14135 // The last instruction that represent the slice. This should be a
14136 // truncate instruction.
14137 SDNode *Inst;
14139 // The original load instruction.
14140 LoadSDNode *Origin;
14142 // The right shift amount in bits from the original load.
14143 unsigned Shift;
14145 // The DAG from which Origin came from.
14146 // This is used to get some contextual information about legal types, etc.
14147 SelectionDAG *DAG;
14149 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
14150 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
14151 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
14153 /// Get the bits used in a chunk of bits \p BitWidth large.
14154 /// \return Result is \p BitWidth and has used bits set to 1 and
14155 /// not used bits set to 0.
14156 APInt getUsedBits() const {
14157 // Reproduce the trunc(lshr) sequence:
14158 // - Start from the truncated value.
14159 // - Zero extend to the desired bit width.
14160 // - Shift left.
14161 assert(Origin && "No original load to compare against.");
14162 unsigned BitWidth = Origin->getValueSizeInBits(0);
14163 assert(Inst && "This slice is not bound to an instruction");
14164 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
14165 "Extracted slice is bigger than the whole type!");
14166 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
14167 UsedBits.setAllBits();
14168 UsedBits = UsedBits.zext(BitWidth);
14169 UsedBits <<= Shift;
14170 return UsedBits;
14173 /// Get the size of the slice to be loaded in bytes.
14174 unsigned getLoadedSize() const {
14175 unsigned SliceSize = getUsedBits().countPopulation();
14176 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
14177 return SliceSize / 8;
14180 /// Get the type that will be loaded for this slice.
14181 /// Note: This may not be the final type for the slice.
14182 EVT getLoadedType() const {
14183 assert(DAG && "Missing context");
14184 LLVMContext &Ctxt = *DAG->getContext();
14185 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
14188 /// Get the alignment of the load used for this slice.
14189 unsigned getAlignment() const {
14190 unsigned Alignment = Origin->getAlignment();
14191 uint64_t Offset = getOffsetFromBase();
14192 if (Offset != 0)
14193 Alignment = MinAlign(Alignment, Alignment + Offset);
14194 return Alignment;
14197 /// Check if this slice can be rewritten with legal operations.
14198 bool isLegal() const {
14199 // An invalid slice is not legal.
14200 if (!Origin || !Inst || !DAG)
14201 return false;
14203 // Offsets are for indexed load only, we do not handle that.
14204 if (!Origin->getOffset().isUndef())
14205 return false;
14207 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
14209 // Check that the type is legal.
14210 EVT SliceType = getLoadedType();
14211 if (!TLI.isTypeLegal(SliceType))
14212 return false;
14214 // Check that the load is legal for this type.
14215 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
14216 return false;
14218 // Check that the offset can be computed.
14219 // 1. Check its type.
14220 EVT PtrType = Origin->getBasePtr().getValueType();
14221 if (PtrType == MVT::Untyped || PtrType.isExtended())
14222 return false;
14224 // 2. Check that it fits in the immediate.
14225 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
14226 return false;
14228 // 3. Check that the computation is legal.
14229 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
14230 return false;
14232 // Check that the zext is legal if it needs one.
14233 EVT TruncateType = Inst->getValueType(0);
14234 if (TruncateType != SliceType &&
14235 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
14236 return false;
14238 return true;
14241 /// Get the offset in bytes of this slice in the original chunk of
14242 /// bits.
14243 /// \pre DAG != nullptr.
14244 uint64_t getOffsetFromBase() const {
14245 assert(DAG && "Missing context.");
14246 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
14247 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
14248 uint64_t Offset = Shift / 8;
14249 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
14250 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
14251 "The size of the original loaded type is not a multiple of a"
14252 " byte.");
14253 // If Offset is bigger than TySizeInBytes, it means we are loading all
14254 // zeros. This should have been optimized before in the process.
14255 assert(TySizeInBytes > Offset &&
14256 "Invalid shift amount for given loaded size");
14257 if (IsBigEndian)
14258 Offset = TySizeInBytes - Offset - getLoadedSize();
14259 return Offset;
14262 /// Generate the sequence of instructions to load the slice
14263 /// represented by this object and redirect the uses of this slice to
14264 /// this new sequence of instructions.
14265 /// \pre this->Inst && this->Origin are valid Instructions and this
14266 /// object passed the legal check: LoadedSlice::isLegal returned true.
14267 /// \return The last instruction of the sequence used to load the slice.
14268 SDValue loadSlice() const {
14269 assert(Inst && Origin && "Unable to replace a non-existing slice.");
14270 const SDValue &OldBaseAddr = Origin->getBasePtr();
14271 SDValue BaseAddr = OldBaseAddr;
14272 // Get the offset in that chunk of bytes w.r.t. the endianness.
14273 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
14274 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
14275 if (Offset) {
14276 // BaseAddr = BaseAddr + Offset.
14277 EVT ArithType = BaseAddr.getValueType();
14278 SDLoc DL(Origin);
14279 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
14280 DAG->getConstant(Offset, DL, ArithType));
14283 // Create the type of the loaded slice according to its size.
14284 EVT SliceType = getLoadedType();
14286 // Create the load for the slice.
14287 SDValue LastInst =
14288 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
14289 Origin->getPointerInfo().getWithOffset(Offset),
14290 getAlignment(), Origin->getMemOperand()->getFlags());
14291 // If the final type is not the same as the loaded type, this means that
14292 // we have to pad with zero. Create a zero extend for that.
14293 EVT FinalType = Inst->getValueType(0);
14294 if (SliceType != FinalType)
14295 LastInst =
14296 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
14297 return LastInst;
14300 /// Check if this slice can be merged with an expensive cross register
14301 /// bank copy. E.g.,
14302 /// i = load i32
14303 /// f = bitcast i32 i to float
14304 bool canMergeExpensiveCrossRegisterBankCopy() const {
14305 if (!Inst || !Inst->hasOneUse())
14306 return false;
14307 SDNode *Use = *Inst->use_begin();
14308 if (Use->getOpcode() != ISD::BITCAST)
14309 return false;
14310 assert(DAG && "Missing context");
14311 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
14312 EVT ResVT = Use->getValueType(0);
14313 const TargetRegisterClass *ResRC =
14314 TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent());
14315 const TargetRegisterClass *ArgRC =
14316 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(),
14317 Use->getOperand(0)->isDivergent());
14318 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
14319 return false;
14321 // At this point, we know that we perform a cross-register-bank copy.
14322 // Check if it is expensive.
14323 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
14324 // Assume bitcasts are cheap, unless both register classes do not
14325 // explicitly share a common sub class.
14326 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
14327 return false;
14329 // Check if it will be merged with the load.
14330 // 1. Check the alignment constraint.
14331 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
14332 ResVT.getTypeForEVT(*DAG->getContext()));
14334 if (RequiredAlignment > getAlignment())
14335 return false;
14337 // 2. Check that the load is a legal operation for that type.
14338 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
14339 return false;
14341 // 3. Check that we do not have a zext in the way.
14342 if (Inst->getValueType(0) != getLoadedType())
14343 return false;
14345 return true;
14349 } // end anonymous namespace
14351 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
14352 /// \p UsedBits looks like 0..0 1..1 0..0.
14353 static bool areUsedBitsDense(const APInt &UsedBits) {
14354 // If all the bits are one, this is dense!
14355 if (UsedBits.isAllOnesValue())
14356 return true;
14358 // Get rid of the unused bits on the right.
14359 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
14360 // Get rid of the unused bits on the left.
14361 if (NarrowedUsedBits.countLeadingZeros())
14362 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
14363 // Check that the chunk of bits is completely used.
14364 return NarrowedUsedBits.isAllOnesValue();
14367 /// Check whether or not \p First and \p Second are next to each other
14368 /// in memory. This means that there is no hole between the bits loaded
14369 /// by \p First and the bits loaded by \p Second.
14370 static bool areSlicesNextToEachOther(const LoadedSlice &First,
14371 const LoadedSlice &Second) {
14372 assert(First.Origin == Second.Origin && First.Origin &&
14373 "Unable to match different memory origins.");
14374 APInt UsedBits = First.getUsedBits();
14375 assert((UsedBits & Second.getUsedBits()) == 0 &&
14376 "Slices are not supposed to overlap.");
14377 UsedBits |= Second.getUsedBits();
14378 return areUsedBitsDense(UsedBits);
14381 /// Adjust the \p GlobalLSCost according to the target
14382 /// paring capabilities and the layout of the slices.
14383 /// \pre \p GlobalLSCost should account for at least as many loads as
14384 /// there is in the slices in \p LoadedSlices.
14385 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
14386 LoadedSlice::Cost &GlobalLSCost) {
14387 unsigned NumberOfSlices = LoadedSlices.size();
14388 // If there is less than 2 elements, no pairing is possible.
14389 if (NumberOfSlices < 2)
14390 return;
14392 // Sort the slices so that elements that are likely to be next to each
14393 // other in memory are next to each other in the list.
14394 llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
14395 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
14396 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
14398 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
14399 // First (resp. Second) is the first (resp. Second) potentially candidate
14400 // to be placed in a paired load.
14401 const LoadedSlice *First = nullptr;
14402 const LoadedSlice *Second = nullptr;
14403 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
14404 // Set the beginning of the pair.
14405 First = Second) {
14406 Second = &LoadedSlices[CurrSlice];
14408 // If First is NULL, it means we start a new pair.
14409 // Get to the next slice.
14410 if (!First)
14411 continue;
14413 EVT LoadedType = First->getLoadedType();
14415 // If the types of the slices are different, we cannot pair them.
14416 if (LoadedType != Second->getLoadedType())
14417 continue;
14419 // Check if the target supplies paired loads for this type.
14420 unsigned RequiredAlignment = 0;
14421 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
14422 // move to the next pair, this type is hopeless.
14423 Second = nullptr;
14424 continue;
14426 // Check if we meet the alignment requirement.
14427 if (RequiredAlignment > First->getAlignment())
14428 continue;
14430 // Check that both loads are next to each other in memory.
14431 if (!areSlicesNextToEachOther(*First, *Second))
14432 continue;
14434 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
14435 --GlobalLSCost.Loads;
14436 // Move to the next pair.
14437 Second = nullptr;
14441 /// Check the profitability of all involved LoadedSlice.
14442 /// Currently, it is considered profitable if there is exactly two
14443 /// involved slices (1) which are (2) next to each other in memory, and
14444 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
14446 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
14447 /// the elements themselves.
14449 /// FIXME: When the cost model will be mature enough, we can relax
14450 /// constraints (1) and (2).
14451 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
14452 const APInt &UsedBits, bool ForCodeSize) {
14453 unsigned NumberOfSlices = LoadedSlices.size();
14454 if (StressLoadSlicing)
14455 return NumberOfSlices > 1;
14457 // Check (1).
14458 if (NumberOfSlices != 2)
14459 return false;
14461 // Check (2).
14462 if (!areUsedBitsDense(UsedBits))
14463 return false;
14465 // Check (3).
14466 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
14467 // The original code has one big load.
14468 OrigCost.Loads = 1;
14469 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
14470 const LoadedSlice &LS = LoadedSlices[CurrSlice];
14471 // Accumulate the cost of all the slices.
14472 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
14473 GlobalSlicingCost += SliceCost;
14475 // Account as cost in the original configuration the gain obtained
14476 // with the current slices.
14477 OrigCost.addSliceGain(LS);
14480 // If the target supports paired load, adjust the cost accordingly.
14481 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
14482 return OrigCost > GlobalSlicingCost;
14485 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
14486 /// operations, split it in the various pieces being extracted.
14488 /// This sort of thing is introduced by SROA.
14489 /// This slicing takes care not to insert overlapping loads.
14490 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
14491 bool DAGCombiner::SliceUpLoad(SDNode *N) {
14492 if (Level < AfterLegalizeDAG)
14493 return false;
14495 LoadSDNode *LD = cast<LoadSDNode>(N);
14496 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
14497 !LD->getValueType(0).isInteger())
14498 return false;
14500 // Keep track of already used bits to detect overlapping values.
14501 // In that case, we will just abort the transformation.
14502 APInt UsedBits(LD->getValueSizeInBits(0), 0);
14504 SmallVector<LoadedSlice, 4> LoadedSlices;
14506 // Check if this load is used as several smaller chunks of bits.
14507 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
14508 // of computation for each trunc.
14509 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
14510 UI != UIEnd; ++UI) {
14511 // Skip the uses of the chain.
14512 if (UI.getUse().getResNo() != 0)
14513 continue;
14515 SDNode *User = *UI;
14516 unsigned Shift = 0;
14518 // Check if this is a trunc(lshr).
14519 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
14520 isa<ConstantSDNode>(User->getOperand(1))) {
14521 Shift = User->getConstantOperandVal(1);
14522 User = *User->use_begin();
14525 // At this point, User is a Truncate, iff we encountered, trunc or
14526 // trunc(lshr).
14527 if (User->getOpcode() != ISD::TRUNCATE)
14528 return false;
14530 // The width of the type must be a power of 2 and greater than 8-bits.
14531 // Otherwise the load cannot be represented in LLVM IR.
14532 // Moreover, if we shifted with a non-8-bits multiple, the slice
14533 // will be across several bytes. We do not support that.
14534 unsigned Width = User->getValueSizeInBits(0);
14535 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
14536 return false;
14538 // Build the slice for this chain of computations.
14539 LoadedSlice LS(User, LD, Shift, &DAG);
14540 APInt CurrentUsedBits = LS.getUsedBits();
14542 // Check if this slice overlaps with another.
14543 if ((CurrentUsedBits & UsedBits) != 0)
14544 return false;
14545 // Update the bits used globally.
14546 UsedBits |= CurrentUsedBits;
14548 // Check if the new slice would be legal.
14549 if (!LS.isLegal())
14550 return false;
14552 // Record the slice.
14553 LoadedSlices.push_back(LS);
14556 // Abort slicing if it does not seem to be profitable.
14557 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
14558 return false;
14560 ++SlicedLoads;
14562 // Rewrite each chain to use an independent load.
14563 // By construction, each chain can be represented by a unique load.
14565 // Prepare the argument for the new token factor for all the slices.
14566 SmallVector<SDValue, 8> ArgChains;
14567 for (SmallVectorImpl<LoadedSlice>::const_iterator
14568 LSIt = LoadedSlices.begin(),
14569 LSItEnd = LoadedSlices.end();
14570 LSIt != LSItEnd; ++LSIt) {
14571 SDValue SliceInst = LSIt->loadSlice();
14572 CombineTo(LSIt->Inst, SliceInst, true);
14573 if (SliceInst.getOpcode() != ISD::LOAD)
14574 SliceInst = SliceInst.getOperand(0);
14575 assert(SliceInst->getOpcode() == ISD::LOAD &&
14576 "It takes more than a zext to get to the loaded slice!!");
14577 ArgChains.push_back(SliceInst.getValue(1));
14580 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
14581 ArgChains);
14582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
14583 AddToWorklist(Chain.getNode());
14584 return true;
14587 /// Check to see if V is (and load (ptr), imm), where the load is having
14588 /// specific bytes cleared out. If so, return the byte size being masked out
14589 /// and the shift amount.
14590 static std::pair<unsigned, unsigned>
14591 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
14592 std::pair<unsigned, unsigned> Result(0, 0);
14594 // Check for the structure we're looking for.
14595 if (V->getOpcode() != ISD::AND ||
14596 !isa<ConstantSDNode>(V->getOperand(1)) ||
14597 !ISD::isNormalLoad(V->getOperand(0).getNode()))
14598 return Result;
14600 // Check the chain and pointer.
14601 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
14602 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
14604 // This only handles simple types.
14605 if (V.getValueType() != MVT::i16 &&
14606 V.getValueType() != MVT::i32 &&
14607 V.getValueType() != MVT::i64)
14608 return Result;
14610 // Check the constant mask. Invert it so that the bits being masked out are
14611 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
14612 // follow the sign bit for uniformity.
14613 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
14614 unsigned NotMaskLZ = countLeadingZeros(NotMask);
14615 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
14616 unsigned NotMaskTZ = countTrailingZeros(NotMask);
14617 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
14618 if (NotMaskLZ == 64) return Result; // All zero mask.
14620 // See if we have a continuous run of bits. If so, we have 0*1+0*
14621 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
14622 return Result;
14624 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
14625 if (V.getValueType() != MVT::i64 && NotMaskLZ)
14626 NotMaskLZ -= 64-V.getValueSizeInBits();
14628 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
14629 switch (MaskedBytes) {
14630 case 1:
14631 case 2:
14632 case 4: break;
14633 default: return Result; // All one mask, or 5-byte mask.
14636 // Verify that the first bit starts at a multiple of mask so that the access
14637 // is aligned the same as the access width.
14638 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
14640 // For narrowing to be valid, it must be the case that the load the
14641 // immediately preceding memory operation before the store.
14642 if (LD == Chain.getNode())
14643 ; // ok.
14644 else if (Chain->getOpcode() == ISD::TokenFactor &&
14645 SDValue(LD, 1).hasOneUse()) {
14646 // LD has only 1 chain use so they are no indirect dependencies.
14647 if (!LD->isOperandOf(Chain.getNode()))
14648 return Result;
14649 } else
14650 return Result; // Fail.
14652 Result.first = MaskedBytes;
14653 Result.second = NotMaskTZ/8;
14654 return Result;
14657 /// Check to see if IVal is something that provides a value as specified by
14658 /// MaskInfo. If so, replace the specified store with a narrower store of
14659 /// truncated IVal.
14660 static SDValue
14661 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
14662 SDValue IVal, StoreSDNode *St,
14663 DAGCombiner *DC) {
14664 unsigned NumBytes = MaskInfo.first;
14665 unsigned ByteShift = MaskInfo.second;
14666 SelectionDAG &DAG = DC->getDAG();
14668 // Check to see if IVal is all zeros in the part being masked in by the 'or'
14669 // that uses this. If not, this is not a replacement.
14670 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
14671 ByteShift*8, (ByteShift+NumBytes)*8);
14672 if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue();
14674 // Check that it is legal on the target to do this. It is legal if the new
14675 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
14676 // legalization.
14677 MVT VT = MVT::getIntegerVT(NumBytes*8);
14678 if (!DC->isTypeLegal(VT))
14679 return SDValue();
14681 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
14682 // shifted by ByteShift and truncated down to NumBytes.
14683 if (ByteShift) {
14684 SDLoc DL(IVal);
14685 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
14686 DAG.getConstant(ByteShift*8, DL,
14687 DC->getShiftAmountTy(IVal.getValueType())));
14690 // Figure out the offset for the store and the alignment of the access.
14691 unsigned StOffset;
14692 unsigned NewAlign = St->getAlignment();
14694 if (DAG.getDataLayout().isLittleEndian())
14695 StOffset = ByteShift;
14696 else
14697 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
14699 SDValue Ptr = St->getBasePtr();
14700 if (StOffset) {
14701 SDLoc DL(IVal);
14702 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
14703 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
14704 NewAlign = MinAlign(NewAlign, StOffset);
14707 // Truncate down to the new size.
14708 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
14710 ++OpsNarrowed;
14711 return DAG
14712 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
14713 St->getPointerInfo().getWithOffset(StOffset), NewAlign);
14716 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
14717 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
14718 /// narrowing the load and store if it would end up being a win for performance
14719 /// or code size.
14720 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
14721 StoreSDNode *ST = cast<StoreSDNode>(N);
14722 if (ST->isVolatile())
14723 return SDValue();
14725 SDValue Chain = ST->getChain();
14726 SDValue Value = ST->getValue();
14727 SDValue Ptr = ST->getBasePtr();
14728 EVT VT = Value.getValueType();
14730 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
14731 return SDValue();
14733 unsigned Opc = Value.getOpcode();
14735 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
14736 // is a byte mask indicating a consecutive number of bytes, check to see if
14737 // Y is known to provide just those bytes. If so, we try to replace the
14738 // load + replace + store sequence with a single (narrower) store, which makes
14739 // the load dead.
14740 if (Opc == ISD::OR) {
14741 std::pair<unsigned, unsigned> MaskedLoad;
14742 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
14743 if (MaskedLoad.first)
14744 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
14745 Value.getOperand(1), ST,this))
14746 return NewST;
14748 // Or is commutative, so try swapping X and Y.
14749 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
14750 if (MaskedLoad.first)
14751 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
14752 Value.getOperand(0), ST,this))
14753 return NewST;
14756 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
14757 Value.getOperand(1).getOpcode() != ISD::Constant)
14758 return SDValue();
14760 SDValue N0 = Value.getOperand(0);
14761 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
14762 Chain == SDValue(N0.getNode(), 1)) {
14763 LoadSDNode *LD = cast<LoadSDNode>(N0);
14764 if (LD->getBasePtr() != Ptr ||
14765 LD->getPointerInfo().getAddrSpace() !=
14766 ST->getPointerInfo().getAddrSpace())
14767 return SDValue();
14769 // Find the type to narrow it the load / op / store to.
14770 SDValue N1 = Value.getOperand(1);
14771 unsigned BitWidth = N1.getValueSizeInBits();
14772 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
14773 if (Opc == ISD::AND)
14774 Imm ^= APInt::getAllOnesValue(BitWidth);
14775 if (Imm == 0 || Imm.isAllOnesValue())
14776 return SDValue();
14777 unsigned ShAmt = Imm.countTrailingZeros();
14778 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
14779 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
14780 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
14781 // The narrowing should be profitable, the load/store operation should be
14782 // legal (or custom) and the store size should be equal to the NewVT width.
14783 while (NewBW < BitWidth &&
14784 (NewVT.getStoreSizeInBits() != NewBW ||
14785 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
14786 !TLI.isNarrowingProfitable(VT, NewVT))) {
14787 NewBW = NextPowerOf2(NewBW);
14788 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
14790 if (NewBW >= BitWidth)
14791 return SDValue();
14793 // If the lsb changed does not start at the type bitwidth boundary,
14794 // start at the previous one.
14795 if (ShAmt % NewBW)
14796 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
14797 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
14798 std::min(BitWidth, ShAmt + NewBW));
14799 if ((Imm & Mask) == Imm) {
14800 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
14801 if (Opc == ISD::AND)
14802 NewImm ^= APInt::getAllOnesValue(NewBW);
14803 uint64_t PtrOff = ShAmt / 8;
14804 // For big endian targets, we need to adjust the offset to the pointer to
14805 // load the correct bytes.
14806 if (DAG.getDataLayout().isBigEndian())
14807 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
14809 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
14810 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
14811 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
14812 return SDValue();
14814 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
14815 Ptr.getValueType(), Ptr,
14816 DAG.getConstant(PtrOff, SDLoc(LD),
14817 Ptr.getValueType()));
14818 SDValue NewLD =
14819 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
14820 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
14821 LD->getMemOperand()->getFlags(), LD->getAAInfo());
14822 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
14823 DAG.getConstant(NewImm, SDLoc(Value),
14824 NewVT));
14825 SDValue NewST =
14826 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
14827 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
14829 AddToWorklist(NewPtr.getNode());
14830 AddToWorklist(NewLD.getNode());
14831 AddToWorklist(NewVal.getNode());
14832 WorklistRemover DeadNodes(*this);
14833 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
14834 ++OpsNarrowed;
14835 return NewST;
14839 return SDValue();
14842 /// For a given floating point load / store pair, if the load value isn't used
14843 /// by any other operations, then consider transforming the pair to integer
14844 /// load / store operations if the target deems the transformation profitable.
14845 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
14846 StoreSDNode *ST = cast<StoreSDNode>(N);
14847 SDValue Value = ST->getValue();
14848 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
14849 Value.hasOneUse()) {
14850 LoadSDNode *LD = cast<LoadSDNode>(Value);
14851 EVT VT = LD->getMemoryVT();
14852 if (!VT.isFloatingPoint() ||
14853 VT != ST->getMemoryVT() ||
14854 LD->isNonTemporal() ||
14855 ST->isNonTemporal() ||
14856 LD->getPointerInfo().getAddrSpace() != 0 ||
14857 ST->getPointerInfo().getAddrSpace() != 0)
14858 return SDValue();
14860 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
14861 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
14862 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
14863 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
14864 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
14865 return SDValue();
14867 unsigned LDAlign = LD->getAlignment();
14868 unsigned STAlign = ST->getAlignment();
14869 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
14870 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
14871 if (LDAlign < ABIAlign || STAlign < ABIAlign)
14872 return SDValue();
14874 SDValue NewLD =
14875 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
14876 LD->getPointerInfo(), LDAlign);
14878 SDValue NewST =
14879 DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(),
14880 ST->getPointerInfo(), STAlign);
14882 AddToWorklist(NewLD.getNode());
14883 AddToWorklist(NewST.getNode());
14884 WorklistRemover DeadNodes(*this);
14885 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
14886 ++LdStFP2Int;
14887 return NewST;
14890 return SDValue();
14893 // This is a helper function for visitMUL to check the profitability
14894 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
14895 // MulNode is the original multiply, AddNode is (add x, c1),
14896 // and ConstNode is c2.
14898 // If the (add x, c1) has multiple uses, we could increase
14899 // the number of adds if we make this transformation.
14900 // It would only be worth doing this if we can remove a
14901 // multiply in the process. Check for that here.
14902 // To illustrate:
14903 // (A + c1) * c3
14904 // (A + c2) * c3
14905 // We're checking for cases where we have common "c3 * A" expressions.
14906 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
14907 SDValue &AddNode,
14908 SDValue &ConstNode) {
14909 APInt Val;
14911 // If the add only has one use, this would be OK to do.
14912 if (AddNode.getNode()->hasOneUse())
14913 return true;
14915 // Walk all the users of the constant with which we're multiplying.
14916 for (SDNode *Use : ConstNode->uses()) {
14917 if (Use == MulNode) // This use is the one we're on right now. Skip it.
14918 continue;
14920 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
14921 SDNode *OtherOp;
14922 SDNode *MulVar = AddNode.getOperand(0).getNode();
14924 // OtherOp is what we're multiplying against the constant.
14925 if (Use->getOperand(0) == ConstNode)
14926 OtherOp = Use->getOperand(1).getNode();
14927 else
14928 OtherOp = Use->getOperand(0).getNode();
14930 // Check to see if multiply is with the same operand of our "add".
14932 // ConstNode = CONST
14933 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
14934 // ...
14935 // AddNode = (A + c1) <-- MulVar is A.
14936 // = AddNode * ConstNode <-- current visiting instruction.
14938 // If we make this transformation, we will have a common
14939 // multiply (ConstNode * A) that we can save.
14940 if (OtherOp == MulVar)
14941 return true;
14943 // Now check to see if a future expansion will give us a common
14944 // multiply.
14946 // ConstNode = CONST
14947 // AddNode = (A + c1)
14948 // ... = AddNode * ConstNode <-- current visiting instruction.
14949 // ...
14950 // OtherOp = (A + c2)
14951 // Use = OtherOp * ConstNode <-- visiting Use.
14953 // If we make this transformation, we will have a common
14954 // multiply (CONST * A) after we also do the same transformation
14955 // to the "t2" instruction.
14956 if (OtherOp->getOpcode() == ISD::ADD &&
14957 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
14958 OtherOp->getOperand(0).getNode() == MulVar)
14959 return true;
14963 // Didn't find a case where this would be profitable.
14964 return false;
14967 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
14968 unsigned NumStores) {
14969 SmallVector<SDValue, 8> Chains;
14970 SmallPtrSet<const SDNode *, 8> Visited;
14971 SDLoc StoreDL(StoreNodes[0].MemNode);
14973 for (unsigned i = 0; i < NumStores; ++i) {
14974 Visited.insert(StoreNodes[i].MemNode);
14977 // don't include nodes that are children or repeated nodes.
14978 for (unsigned i = 0; i < NumStores; ++i) {
14979 if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second)
14980 Chains.push_back(StoreNodes[i].MemNode->getChain());
14983 assert(Chains.size() > 0 && "Chain should have generated a chain");
14984 return DAG.getTokenFactor(StoreDL, Chains);
14987 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
14988 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
14989 bool IsConstantSrc, bool UseVector, bool UseTrunc) {
14990 // Make sure we have something to merge.
14991 if (NumStores < 2)
14992 return false;
14994 // The latest Node in the DAG.
14995 SDLoc DL(StoreNodes[0].MemNode);
14997 int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
14998 unsigned SizeInBits = NumStores * ElementSizeBits;
14999 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
15001 EVT StoreTy;
15002 if (UseVector) {
15003 unsigned Elts = NumStores * NumMemElts;
15004 // Get the type for the merged vector store.
15005 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
15006 } else
15007 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
15009 SDValue StoredVal;
15010 if (UseVector) {
15011 if (IsConstantSrc) {
15012 SmallVector<SDValue, 8> BuildVector;
15013 for (unsigned I = 0; I != NumStores; ++I) {
15014 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
15015 SDValue Val = St->getValue();
15016 // If constant is of the wrong type, convert it now.
15017 if (MemVT != Val.getValueType()) {
15018 Val = peekThroughBitcasts(Val);
15019 // Deal with constants of wrong size.
15020 if (ElementSizeBits != Val.getValueSizeInBits()) {
15021 EVT IntMemVT =
15022 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
15023 if (isa<ConstantFPSDNode>(Val)) {
15024 // Not clear how to truncate FP values.
15025 return false;
15026 } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
15027 Val = DAG.getConstant(C->getAPIntValue()
15028 .zextOrTrunc(Val.getValueSizeInBits())
15029 .zextOrTrunc(ElementSizeBits),
15030 SDLoc(C), IntMemVT);
15032 // Make sure correctly size type is the correct type.
15033 Val = DAG.getBitcast(MemVT, Val);
15035 BuildVector.push_back(Val);
15037 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
15038 : ISD::BUILD_VECTOR,
15039 DL, StoreTy, BuildVector);
15040 } else {
15041 SmallVector<SDValue, 8> Ops;
15042 for (unsigned i = 0; i < NumStores; ++i) {
15043 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
15044 SDValue Val = peekThroughBitcasts(St->getValue());
15045 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
15046 // type MemVT. If the underlying value is not the correct
15047 // type, but it is an extraction of an appropriate vector we
15048 // can recast Val to be of the correct type. This may require
15049 // converting between EXTRACT_VECTOR_ELT and
15050 // EXTRACT_SUBVECTOR.
15051 if ((MemVT != Val.getValueType()) &&
15052 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
15053 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
15054 EVT MemVTScalarTy = MemVT.getScalarType();
15055 // We may need to add a bitcast here to get types to line up.
15056 if (MemVTScalarTy != Val.getValueType().getScalarType()) {
15057 Val = DAG.getBitcast(MemVT, Val);
15058 } else {
15059 unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR
15060 : ISD::EXTRACT_VECTOR_ELT;
15061 SDValue Vec = Val.getOperand(0);
15062 SDValue Idx = Val.getOperand(1);
15063 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx);
15066 Ops.push_back(Val);
15069 // Build the extracted vector elements back into a vector.
15070 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
15071 : ISD::BUILD_VECTOR,
15072 DL, StoreTy, Ops);
15074 } else {
15075 // We should always use a vector store when merging extracted vector
15076 // elements, so this path implies a store of constants.
15077 assert(IsConstantSrc && "Merged vector elements should use vector store");
15079 APInt StoreInt(SizeInBits, 0);
15081 // Construct a single integer constant which is made of the smaller
15082 // constant inputs.
15083 bool IsLE = DAG.getDataLayout().isLittleEndian();
15084 for (unsigned i = 0; i < NumStores; ++i) {
15085 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
15086 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
15088 SDValue Val = St->getValue();
15089 Val = peekThroughBitcasts(Val);
15090 StoreInt <<= ElementSizeBits;
15091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
15092 StoreInt |= C->getAPIntValue()
15093 .zextOrTrunc(ElementSizeBits)
15094 .zextOrTrunc(SizeInBits);
15095 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
15096 StoreInt |= C->getValueAPF()
15097 .bitcastToAPInt()
15098 .zextOrTrunc(ElementSizeBits)
15099 .zextOrTrunc(SizeInBits);
15100 // If fp truncation is necessary give up for now.
15101 if (MemVT.getSizeInBits() != ElementSizeBits)
15102 return false;
15103 } else {
15104 llvm_unreachable("Invalid constant element type");
15108 // Create the new Load and Store operations.
15109 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
15112 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
15113 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
15115 // make sure we use trunc store if it's necessary to be legal.
15116 SDValue NewStore;
15117 if (!UseTrunc) {
15118 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
15119 FirstInChain->getPointerInfo(),
15120 FirstInChain->getAlignment());
15121 } else { // Must be realized as a trunc store
15122 EVT LegalizedStoredValTy =
15123 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
15124 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits();
15125 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
15126 SDValue ExtendedStoreVal =
15127 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
15128 LegalizedStoredValTy);
15129 NewStore = DAG.getTruncStore(
15130 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
15131 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
15132 FirstInChain->getAlignment(),
15133 FirstInChain->getMemOperand()->getFlags());
15136 // Replace all merged stores with the new store.
15137 for (unsigned i = 0; i < NumStores; ++i)
15138 CombineTo(StoreNodes[i].MemNode, NewStore);
15140 AddToWorklist(NewChain.getNode());
15141 return true;
15144 void DAGCombiner::getStoreMergeCandidates(
15145 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
15146 SDNode *&RootNode) {
15147 // This holds the base pointer, index, and the offset in bytes from the base
15148 // pointer.
15149 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
15150 EVT MemVT = St->getMemoryVT();
15152 SDValue Val = peekThroughBitcasts(St->getValue());
15153 // We must have a base and an offset.
15154 if (!BasePtr.getBase().getNode())
15155 return;
15157 // Do not handle stores to undef base pointers.
15158 if (BasePtr.getBase().isUndef())
15159 return;
15161 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
15162 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
15163 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
15164 bool IsLoadSrc = isa<LoadSDNode>(Val);
15165 BaseIndexOffset LBasePtr;
15166 // Match on loadbaseptr if relevant.
15167 EVT LoadVT;
15168 if (IsLoadSrc) {
15169 auto *Ld = cast<LoadSDNode>(Val);
15170 LBasePtr = BaseIndexOffset::match(Ld, DAG);
15171 LoadVT = Ld->getMemoryVT();
15172 // Load and store should be the same type.
15173 if (MemVT != LoadVT)
15174 return;
15175 // Loads must only have one use.
15176 if (!Ld->hasNUsesOfValue(1, 0))
15177 return;
15178 // The memory operands must not be volatile/indexed.
15179 if (Ld->isVolatile() || Ld->isIndexed())
15180 return;
15182 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
15183 int64_t &Offset) -> bool {
15184 // The memory operands must not be volatile/indexed.
15185 if (Other->isVolatile() || Other->isIndexed())
15186 return false;
15187 // Don't mix temporal stores with non-temporal stores.
15188 if (St->isNonTemporal() != Other->isNonTemporal())
15189 return false;
15190 SDValue OtherBC = peekThroughBitcasts(Other->getValue());
15191 // Allow merging constants of different types as integers.
15192 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
15193 : Other->getMemoryVT() != MemVT;
15194 if (IsLoadSrc) {
15195 if (NoTypeMatch)
15196 return false;
15197 // The Load's Base Ptr must also match
15198 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(OtherBC)) {
15199 BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG);
15200 if (LoadVT != OtherLd->getMemoryVT())
15201 return false;
15202 // Loads must only have one use.
15203 if (!OtherLd->hasNUsesOfValue(1, 0))
15204 return false;
15205 // The memory operands must not be volatile/indexed.
15206 if (OtherLd->isVolatile() || OtherLd->isIndexed())
15207 return false;
15208 // Don't mix temporal loads with non-temporal loads.
15209 if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal())
15210 return false;
15211 if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
15212 return false;
15213 } else
15214 return false;
15216 if (IsConstantSrc) {
15217 if (NoTypeMatch)
15218 return false;
15219 if (!(isa<ConstantSDNode>(OtherBC) || isa<ConstantFPSDNode>(OtherBC)))
15220 return false;
15222 if (IsExtractVecSrc) {
15223 // Do not merge truncated stores here.
15224 if (Other->isTruncatingStore())
15225 return false;
15226 if (!MemVT.bitsEq(OtherBC.getValueType()))
15227 return false;
15228 if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
15229 OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15230 return false;
15232 Ptr = BaseIndexOffset::match(Other, DAG);
15233 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
15236 // Check if the pair of StoreNode and the RootNode already bail out many
15237 // times which is over the limit in dependence check.
15238 auto OverLimitInDependenceCheck = [&](SDNode *StoreNode,
15239 SDNode *RootNode) -> bool {
15240 auto RootCount = StoreRootCountMap.find(StoreNode);
15241 if (RootCount != StoreRootCountMap.end() &&
15242 RootCount->second.first == RootNode &&
15243 RootCount->second.second > StoreMergeDependenceLimit)
15244 return true;
15245 return false;
15248 // We looking for a root node which is an ancestor to all mergable
15249 // stores. We search up through a load, to our root and then down
15250 // through all children. For instance we will find Store{1,2,3} if
15251 // St is Store1, Store2. or Store3 where the root is not a load
15252 // which always true for nonvolatile ops. TODO: Expand
15253 // the search to find all valid candidates through multiple layers of loads.
15255 // Root
15256 // |-------|-------|
15257 // Load Load Store3
15258 // | |
15259 // Store1 Store2
15261 // FIXME: We should be able to climb and
15262 // descend TokenFactors to find candidates as well.
15264 RootNode = St->getChain().getNode();
15266 unsigned NumNodesExplored = 0;
15267 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
15268 RootNode = Ldn->getChain().getNode();
15269 for (auto I = RootNode->use_begin(), E = RootNode->use_end();
15270 I != E && NumNodesExplored < 1024; ++I, ++NumNodesExplored)
15271 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
15272 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
15273 if (I2.getOperandNo() == 0)
15274 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
15275 BaseIndexOffset Ptr;
15276 int64_t PtrDiff;
15277 if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15278 !OverLimitInDependenceCheck(OtherST, RootNode))
15279 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
15281 } else
15282 for (auto I = RootNode->use_begin(), E = RootNode->use_end();
15283 I != E && NumNodesExplored < 1024; ++I, ++NumNodesExplored)
15284 if (I.getOperandNo() == 0)
15285 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
15286 BaseIndexOffset Ptr;
15287 int64_t PtrDiff;
15288 if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15289 !OverLimitInDependenceCheck(OtherST, RootNode))
15290 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
15294 // We need to check that merging these stores does not cause a loop in
15295 // the DAG. Any store candidate may depend on another candidate
15296 // indirectly through its operand (we already consider dependencies
15297 // through the chain). Check in parallel by searching up from
15298 // non-chain operands of candidates.
15299 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
15300 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
15301 SDNode *RootNode) {
15302 // FIXME: We should be able to truncate a full search of
15303 // predecessors by doing a BFS and keeping tabs the originating
15304 // stores from which worklist nodes come from in a similar way to
15305 // TokenFactor simplfication.
15307 SmallPtrSet<const SDNode *, 32> Visited;
15308 SmallVector<const SDNode *, 8> Worklist;
15310 // RootNode is a predecessor to all candidates so we need not search
15311 // past it. Add RootNode (peeking through TokenFactors). Do not count
15312 // these towards size check.
15314 Worklist.push_back(RootNode);
15315 while (!Worklist.empty()) {
15316 auto N = Worklist.pop_back_val();
15317 if (!Visited.insert(N).second)
15318 continue; // Already present in Visited.
15319 if (N->getOpcode() == ISD::TokenFactor) {
15320 for (SDValue Op : N->ops())
15321 Worklist.push_back(Op.getNode());
15325 // Don't count pruning nodes towards max.
15326 unsigned int Max = 1024 + Visited.size();
15327 // Search Ops of store candidates.
15328 for (unsigned i = 0; i < NumStores; ++i) {
15329 SDNode *N = StoreNodes[i].MemNode;
15330 // Of the 4 Store Operands:
15331 // * Chain (Op 0) -> We have already considered these
15332 // in candidate selection and can be
15333 // safely ignored
15334 // * Value (Op 1) -> Cycles may happen (e.g. through load chains)
15335 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
15336 // but aren't necessarily fromt the same base node, so
15337 // cycles possible (e.g. via indexed store).
15338 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for
15339 // non-indexed stores). Not constant on all targets (e.g. ARM)
15340 // and so can participate in a cycle.
15341 for (unsigned j = 1; j < N->getNumOperands(); ++j)
15342 Worklist.push_back(N->getOperand(j).getNode());
15344 // Search through DAG. We can stop early if we find a store node.
15345 for (unsigned i = 0; i < NumStores; ++i)
15346 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
15347 Max)) {
15348 // If the searching bail out, record the StoreNode and RootNode in the
15349 // StoreRootCountMap. If we have seen the pair many times over a limit,
15350 // we won't add the StoreNode into StoreNodes set again.
15351 if (Visited.size() >= Max) {
15352 auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode];
15353 if (RootCount.first == RootNode)
15354 RootCount.second++;
15355 else
15356 RootCount = {RootNode, 1};
15358 return false;
15360 return true;
15363 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
15364 if (OptLevel == CodeGenOpt::None || !EnableStoreMerging)
15365 return false;
15367 EVT MemVT = St->getMemoryVT();
15368 int64_t ElementSizeBytes = MemVT.getStoreSize();
15369 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
15371 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
15372 return false;
15374 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
15375 Attribute::NoImplicitFloat);
15377 // This function cannot currently deal with non-byte-sized memory sizes.
15378 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
15379 return false;
15381 if (!MemVT.isSimple())
15382 return false;
15384 // Perform an early exit check. Do not bother looking at stored values that
15385 // are not constants, loads, or extracted vector elements.
15386 SDValue StoredVal = peekThroughBitcasts(St->getValue());
15387 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
15388 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
15389 isa<ConstantFPSDNode>(StoredVal);
15390 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
15391 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
15392 bool IsNonTemporalStore = St->isNonTemporal();
15393 bool IsNonTemporalLoad =
15394 IsLoadSrc && cast<LoadSDNode>(StoredVal)->isNonTemporal();
15396 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
15397 return false;
15399 SmallVector<MemOpLink, 8> StoreNodes;
15400 SDNode *RootNode;
15401 // Find potential store merge candidates by searching through chain sub-DAG
15402 getStoreMergeCandidates(St, StoreNodes, RootNode);
15404 // Check if there is anything to merge.
15405 if (StoreNodes.size() < 2)
15406 return false;
15408 // Sort the memory operands according to their distance from the
15409 // base pointer.
15410 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) {
15411 return LHS.OffsetFromBase < RHS.OffsetFromBase;
15414 // Store Merge attempts to merge the lowest stores. This generally
15415 // works out as if successful, as the remaining stores are checked
15416 // after the first collection of stores is merged. However, in the
15417 // case that a non-mergeable store is found first, e.g., {p[-2],
15418 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
15419 // mergeable cases. To prevent this, we prune such stores from the
15420 // front of StoreNodes here.
15422 bool RV = false;
15423 while (StoreNodes.size() > 1) {
15424 size_t StartIdx = 0;
15425 while ((StartIdx + 1 < StoreNodes.size()) &&
15426 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
15427 StoreNodes[StartIdx + 1].OffsetFromBase)
15428 ++StartIdx;
15430 // Bail if we don't have enough candidates to merge.
15431 if (StartIdx + 1 >= StoreNodes.size())
15432 return RV;
15434 if (StartIdx)
15435 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
15437 // Scan the memory operations on the chain and find the first
15438 // non-consecutive store memory address.
15439 unsigned NumConsecutiveStores = 1;
15440 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
15441 // Check that the addresses are consecutive starting from the second
15442 // element in the list of stores.
15443 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
15444 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
15445 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
15446 break;
15447 NumConsecutiveStores = i + 1;
15450 if (NumConsecutiveStores < 2) {
15451 StoreNodes.erase(StoreNodes.begin(),
15452 StoreNodes.begin() + NumConsecutiveStores);
15453 continue;
15456 // The node with the lowest store address.
15457 LLVMContext &Context = *DAG.getContext();
15458 const DataLayout &DL = DAG.getDataLayout();
15460 // Store the constants into memory as one consecutive store.
15461 if (IsConstantSrc) {
15462 while (NumConsecutiveStores >= 2) {
15463 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
15464 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
15465 unsigned FirstStoreAlign = FirstInChain->getAlignment();
15466 unsigned LastLegalType = 1;
15467 unsigned LastLegalVectorType = 1;
15468 bool LastIntegerTrunc = false;
15469 bool NonZero = false;
15470 unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
15471 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
15472 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
15473 SDValue StoredVal = ST->getValue();
15474 bool IsElementZero = false;
15475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
15476 IsElementZero = C->isNullValue();
15477 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
15478 IsElementZero = C->getConstantFPValue()->isNullValue();
15479 if (IsElementZero) {
15480 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
15481 FirstZeroAfterNonZero = i;
15483 NonZero |= !IsElementZero;
15485 // Find a legal type for the constant store.
15486 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
15487 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
15488 bool IsFast = false;
15490 // Break early when size is too large to be legal.
15491 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
15492 break;
15494 if (TLI.isTypeLegal(StoreTy) &&
15495 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
15496 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15497 *FirstInChain->getMemOperand(), &IsFast) &&
15498 IsFast) {
15499 LastIntegerTrunc = false;
15500 LastLegalType = i + 1;
15501 // Or check whether a truncstore is legal.
15502 } else if (TLI.getTypeAction(Context, StoreTy) ==
15503 TargetLowering::TypePromoteInteger) {
15504 EVT LegalizedStoredValTy =
15505 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
15506 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
15507 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
15508 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15509 *FirstInChain->getMemOperand(),
15510 &IsFast) &&
15511 IsFast) {
15512 LastIntegerTrunc = true;
15513 LastLegalType = i + 1;
15517 // We only use vectors if the constant is known to be zero or the
15518 // target allows it and the function is not marked with the
15519 // noimplicitfloat attribute.
15520 if ((!NonZero ||
15521 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
15522 !NoVectors) {
15523 // Find a legal type for the vector store.
15524 unsigned Elts = (i + 1) * NumMemElts;
15525 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
15526 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
15527 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
15528 TLI.allowsMemoryAccess(
15529 Context, DL, Ty, *FirstInChain->getMemOperand(), &IsFast) &&
15530 IsFast)
15531 LastLegalVectorType = i + 1;
15535 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
15536 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
15538 // Check if we found a legal integer type that creates a meaningful
15539 // merge.
15540 if (NumElem < 2) {
15541 // We know that candidate stores are in order and of correct
15542 // shape. While there is no mergeable sequence from the
15543 // beginning one may start later in the sequence. The only
15544 // reason a merge of size N could have failed where another of
15545 // the same size would not have, is if the alignment has
15546 // improved or we've dropped a non-zero value. Drop as many
15547 // candidates as we can here.
15548 unsigned NumSkip = 1;
15549 while (
15550 (NumSkip < NumConsecutiveStores) &&
15551 (NumSkip < FirstZeroAfterNonZero) &&
15552 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
15553 NumSkip++;
15555 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
15556 NumConsecutiveStores -= NumSkip;
15557 continue;
15560 // Check that we can merge these candidates without causing a cycle.
15561 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
15562 RootNode)) {
15563 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
15564 NumConsecutiveStores -= NumElem;
15565 continue;
15568 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true,
15569 UseVector, LastIntegerTrunc);
15571 // Remove merged stores for next iteration.
15572 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
15573 NumConsecutiveStores -= NumElem;
15575 continue;
15578 // When extracting multiple vector elements, try to store them
15579 // in one vector store rather than a sequence of scalar stores.
15580 if (IsExtractVecSrc) {
15581 // Loop on Consecutive Stores on success.
15582 while (NumConsecutiveStores >= 2) {
15583 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
15584 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
15585 unsigned FirstStoreAlign = FirstInChain->getAlignment();
15586 unsigned NumStoresToMerge = 1;
15587 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
15588 // Find a legal type for the vector store.
15589 unsigned Elts = (i + 1) * NumMemElts;
15590 EVT Ty =
15591 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
15592 bool IsFast;
15594 // Break early when size is too large to be legal.
15595 if (Ty.getSizeInBits() > MaximumLegalStoreInBits)
15596 break;
15598 if (TLI.isTypeLegal(Ty) &&
15599 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
15600 TLI.allowsMemoryAccess(Context, DL, Ty,
15601 *FirstInChain->getMemOperand(), &IsFast) &&
15602 IsFast)
15603 NumStoresToMerge = i + 1;
15606 // Check if we found a legal integer type creating a meaningful
15607 // merge.
15608 if (NumStoresToMerge < 2) {
15609 // We know that candidate stores are in order and of correct
15610 // shape. While there is no mergeable sequence from the
15611 // beginning one may start later in the sequence. The only
15612 // reason a merge of size N could have failed where another of
15613 // the same size would not have, is if the alignment has
15614 // improved. Drop as many candidates as we can here.
15615 unsigned NumSkip = 1;
15616 while (
15617 (NumSkip < NumConsecutiveStores) &&
15618 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
15619 NumSkip++;
15621 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
15622 NumConsecutiveStores -= NumSkip;
15623 continue;
15626 // Check that we can merge these candidates without causing a cycle.
15627 if (!checkMergeStoreCandidatesForDependencies(
15628 StoreNodes, NumStoresToMerge, RootNode)) {
15629 StoreNodes.erase(StoreNodes.begin(),
15630 StoreNodes.begin() + NumStoresToMerge);
15631 NumConsecutiveStores -= NumStoresToMerge;
15632 continue;
15635 RV |= MergeStoresOfConstantsOrVecElts(
15636 StoreNodes, MemVT, NumStoresToMerge, false, true, false);
15638 StoreNodes.erase(StoreNodes.begin(),
15639 StoreNodes.begin() + NumStoresToMerge);
15640 NumConsecutiveStores -= NumStoresToMerge;
15642 continue;
15645 // Below we handle the case of multiple consecutive stores that
15646 // come from multiple consecutive loads. We merge them into a single
15647 // wide load and a single wide store.
15649 // Look for load nodes which are used by the stored values.
15650 SmallVector<MemOpLink, 8> LoadNodes;
15652 // Find acceptable loads. Loads need to have the same chain (token factor),
15653 // must not be zext, volatile, indexed, and they must be consecutive.
15654 BaseIndexOffset LdBasePtr;
15656 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
15657 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
15658 SDValue Val = peekThroughBitcasts(St->getValue());
15659 LoadSDNode *Ld = cast<LoadSDNode>(Val);
15661 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
15662 // If this is not the first ptr that we check.
15663 int64_t LdOffset = 0;
15664 if (LdBasePtr.getBase().getNode()) {
15665 // The base ptr must be the same.
15666 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
15667 break;
15668 } else {
15669 // Check that all other base pointers are the same as this one.
15670 LdBasePtr = LdPtr;
15673 // We found a potential memory operand to merge.
15674 LoadNodes.push_back(MemOpLink(Ld, LdOffset));
15677 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) {
15678 // If we have load/store pair instructions and we only have two values,
15679 // don't bother merging.
15680 unsigned RequiredAlignment;
15681 if (LoadNodes.size() == 2 &&
15682 TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
15683 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
15684 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
15685 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2);
15686 break;
15688 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
15689 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
15690 unsigned FirstStoreAlign = FirstInChain->getAlignment();
15691 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
15692 unsigned FirstLoadAlign = FirstLoad->getAlignment();
15694 // Scan the memory operations on the chain and find the first
15695 // non-consecutive load memory address. These variables hold the index in
15696 // the store node array.
15698 unsigned LastConsecutiveLoad = 1;
15700 // This variable refers to the size and not index in the array.
15701 unsigned LastLegalVectorType = 1;
15702 unsigned LastLegalIntegerType = 1;
15703 bool isDereferenceable = true;
15704 bool DoIntegerTruncate = false;
15705 StartAddress = LoadNodes[0].OffsetFromBase;
15706 SDValue FirstChain = FirstLoad->getChain();
15707 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
15708 // All loads must share the same chain.
15709 if (LoadNodes[i].MemNode->getChain() != FirstChain)
15710 break;
15712 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
15713 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
15714 break;
15715 LastConsecutiveLoad = i;
15717 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
15718 isDereferenceable = false;
15720 // Find a legal type for the vector store.
15721 unsigned Elts = (i + 1) * NumMemElts;
15722 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
15724 // Break early when size is too large to be legal.
15725 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
15726 break;
15728 bool IsFastSt, IsFastLd;
15729 if (TLI.isTypeLegal(StoreTy) &&
15730 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
15731 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15732 *FirstInChain->getMemOperand(), &IsFastSt) &&
15733 IsFastSt &&
15734 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15735 *FirstLoad->getMemOperand(), &IsFastLd) &&
15736 IsFastLd) {
15737 LastLegalVectorType = i + 1;
15740 // Find a legal type for the integer store.
15741 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
15742 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
15743 if (TLI.isTypeLegal(StoreTy) &&
15744 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
15745 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15746 *FirstInChain->getMemOperand(), &IsFastSt) &&
15747 IsFastSt &&
15748 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15749 *FirstLoad->getMemOperand(), &IsFastLd) &&
15750 IsFastLd) {
15751 LastLegalIntegerType = i + 1;
15752 DoIntegerTruncate = false;
15753 // Or check whether a truncstore and extload is legal.
15754 } else if (TLI.getTypeAction(Context, StoreTy) ==
15755 TargetLowering::TypePromoteInteger) {
15756 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy);
15757 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
15758 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
15759 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy,
15760 StoreTy) &&
15761 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy,
15762 StoreTy) &&
15763 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) &&
15764 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15765 *FirstInChain->getMemOperand(),
15766 &IsFastSt) &&
15767 IsFastSt &&
15768 TLI.allowsMemoryAccess(Context, DL, StoreTy,
15769 *FirstLoad->getMemOperand(), &IsFastLd) &&
15770 IsFastLd) {
15771 LastLegalIntegerType = i + 1;
15772 DoIntegerTruncate = true;
15777 // Only use vector types if the vector type is larger than the integer
15778 // type. If they are the same, use integers.
15779 bool UseVectorTy =
15780 LastLegalVectorType > LastLegalIntegerType && !NoVectors;
15781 unsigned LastLegalType =
15782 std::max(LastLegalVectorType, LastLegalIntegerType);
15784 // We add +1 here because the LastXXX variables refer to location while
15785 // the NumElem refers to array/index size.
15786 unsigned NumElem =
15787 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
15788 NumElem = std::min(LastLegalType, NumElem);
15790 if (NumElem < 2) {
15791 // We know that candidate stores are in order and of correct
15792 // shape. While there is no mergeable sequence from the
15793 // beginning one may start later in the sequence. The only
15794 // reason a merge of size N could have failed where another of
15795 // the same size would not have is if the alignment or either
15796 // the load or store has improved. Drop as many candidates as we
15797 // can here.
15798 unsigned NumSkip = 1;
15799 while ((NumSkip < LoadNodes.size()) &&
15800 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
15801 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
15802 NumSkip++;
15803 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
15804 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip);
15805 NumConsecutiveStores -= NumSkip;
15806 continue;
15809 // Check that we can merge these candidates without causing a cycle.
15810 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
15811 RootNode)) {
15812 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
15813 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
15814 NumConsecutiveStores -= NumElem;
15815 continue;
15818 // Find if it is better to use vectors or integers to load and store
15819 // to memory.
15820 EVT JointMemOpVT;
15821 if (UseVectorTy) {
15822 // Find a legal type for the vector store.
15823 unsigned Elts = NumElem * NumMemElts;
15824 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
15825 } else {
15826 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
15827 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
15830 SDLoc LoadDL(LoadNodes[0].MemNode);
15831 SDLoc StoreDL(StoreNodes[0].MemNode);
15833 // The merged loads are required to have the same incoming chain, so
15834 // using the first's chain is acceptable.
15836 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
15837 AddToWorklist(NewStoreChain.getNode());
15839 MachineMemOperand::Flags LdMMOFlags =
15840 isDereferenceable ? MachineMemOperand::MODereferenceable
15841 : MachineMemOperand::MONone;
15842 if (IsNonTemporalLoad)
15843 LdMMOFlags |= MachineMemOperand::MONonTemporal;
15845 MachineMemOperand::Flags StMMOFlags =
15846 IsNonTemporalStore ? MachineMemOperand::MONonTemporal
15847 : MachineMemOperand::MONone;
15849 SDValue NewLoad, NewStore;
15850 if (UseVectorTy || !DoIntegerTruncate) {
15851 NewLoad =
15852 DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
15853 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
15854 FirstLoadAlign, LdMMOFlags);
15855 NewStore = DAG.getStore(
15856 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
15857 FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags);
15858 } else { // This must be the truncstore/extload case
15859 EVT ExtendedTy =
15860 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
15861 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy,
15862 FirstLoad->getChain(), FirstLoad->getBasePtr(),
15863 FirstLoad->getPointerInfo(), JointMemOpVT,
15864 FirstLoadAlign, LdMMOFlags);
15865 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
15866 FirstInChain->getBasePtr(),
15867 FirstInChain->getPointerInfo(),
15868 JointMemOpVT, FirstInChain->getAlignment(),
15869 FirstInChain->getMemOperand()->getFlags());
15872 // Transfer chain users from old loads to the new load.
15873 for (unsigned i = 0; i < NumElem; ++i) {
15874 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
15875 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
15876 SDValue(NewLoad.getNode(), 1));
15879 // Replace the all stores with the new store. Recursively remove
15880 // corresponding value if its no longer used.
15881 for (unsigned i = 0; i < NumElem; ++i) {
15882 SDValue Val = StoreNodes[i].MemNode->getOperand(1);
15883 CombineTo(StoreNodes[i].MemNode, NewStore);
15884 if (Val.getNode()->use_empty())
15885 recursivelyDeleteUnusedNodes(Val.getNode());
15888 RV = true;
15889 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
15890 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
15891 NumConsecutiveStores -= NumElem;
15894 return RV;
15897 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
15898 SDLoc SL(ST);
15899 SDValue ReplStore;
15901 // Replace the chain to avoid dependency.
15902 if (ST->isTruncatingStore()) {
15903 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
15904 ST->getBasePtr(), ST->getMemoryVT(),
15905 ST->getMemOperand());
15906 } else {
15907 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
15908 ST->getMemOperand());
15911 // Create token to keep both nodes around.
15912 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
15913 MVT::Other, ST->getChain(), ReplStore);
15915 // Make sure the new and old chains are cleaned up.
15916 AddToWorklist(Token.getNode());
15918 // Don't add users to work list.
15919 return CombineTo(ST, Token, false);
15922 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
15923 SDValue Value = ST->getValue();
15924 if (Value.getOpcode() == ISD::TargetConstantFP)
15925 return SDValue();
15927 SDLoc DL(ST);
15929 SDValue Chain = ST->getChain();
15930 SDValue Ptr = ST->getBasePtr();
15932 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
15934 // NOTE: If the original store is volatile, this transform must not increase
15935 // the number of stores. For example, on x86-32 an f64 can be stored in one
15936 // processor operation but an i64 (which is not legal) requires two. So the
15937 // transform should not be done in this case.
15939 SDValue Tmp;
15940 switch (CFP->getSimpleValueType(0).SimpleTy) {
15941 default:
15942 llvm_unreachable("Unknown FP type");
15943 case MVT::f16: // We don't do this for these yet.
15944 case MVT::f80:
15945 case MVT::f128:
15946 case MVT::ppcf128:
15947 return SDValue();
15948 case MVT::f32:
15949 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
15950 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
15952 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
15953 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
15954 MVT::i32);
15955 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
15958 return SDValue();
15959 case MVT::f64:
15960 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
15961 !ST->isVolatile()) ||
15962 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
15964 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
15965 getZExtValue(), SDLoc(CFP), MVT::i64);
15966 return DAG.getStore(Chain, DL, Tmp,
15967 Ptr, ST->getMemOperand());
15970 if (!ST->isVolatile() &&
15971 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
15972 // Many FP stores are not made apparent until after legalize, e.g. for
15973 // argument passing. Since this is so common, custom legalize the
15974 // 64-bit integer store into two 32-bit stores.
15975 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
15976 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
15977 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
15978 if (DAG.getDataLayout().isBigEndian())
15979 std::swap(Lo, Hi);
15981 unsigned Alignment = ST->getAlignment();
15982 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
15983 AAMDNodes AAInfo = ST->getAAInfo();
15985 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
15986 ST->getAlignment(), MMOFlags, AAInfo);
15987 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
15988 DAG.getConstant(4, DL, Ptr.getValueType()));
15989 Alignment = MinAlign(Alignment, 4U);
15990 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
15991 ST->getPointerInfo().getWithOffset(4),
15992 Alignment, MMOFlags, AAInfo);
15993 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
15994 St0, St1);
15997 return SDValue();
16001 SDValue DAGCombiner::visitSTORE(SDNode *N) {
16002 StoreSDNode *ST = cast<StoreSDNode>(N);
16003 SDValue Chain = ST->getChain();
16004 SDValue Value = ST->getValue();
16005 SDValue Ptr = ST->getBasePtr();
16007 // If this is a store of a bit convert, store the input value if the
16008 // resultant store does not need a higher alignment than the original.
16009 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
16010 ST->isUnindexed()) {
16011 EVT SVT = Value.getOperand(0).getValueType();
16012 // If the store is volatile, we only want to change the store type if the
16013 // resulting store is legal. Otherwise we might increase the number of
16014 // memory accesses. We don't care if the original type was legal or not
16015 // as we assume software couldn't rely on the number of accesses of an
16016 // illegal type.
16017 if (((!LegalOperations && !ST->isVolatile()) ||
16018 TLI.isOperationLegal(ISD::STORE, SVT)) &&
16019 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT,
16020 DAG, *ST->getMemOperand())) {
16021 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
16022 ST->getPointerInfo(), ST->getAlignment(),
16023 ST->getMemOperand()->getFlags(), ST->getAAInfo());
16027 // Turn 'store undef, Ptr' -> nothing.
16028 if (Value.isUndef() && ST->isUnindexed())
16029 return Chain;
16031 // Try to infer better alignment information than the store already has.
16032 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
16033 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
16034 if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) {
16035 SDValue NewStore =
16036 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
16037 ST->getMemoryVT(), Align,
16038 ST->getMemOperand()->getFlags(), ST->getAAInfo());
16039 // NewStore will always be N as we are only refining the alignment
16040 assert(NewStore.getNode() == N);
16041 (void)NewStore;
16046 // Try transforming a pair floating point load / store ops to integer
16047 // load / store ops.
16048 if (SDValue NewST = TransformFPLoadStorePair(N))
16049 return NewST;
16051 // Try transforming several stores into STORE (BSWAP).
16052 if (SDValue Store = MatchStoreCombine(ST))
16053 return Store;
16055 if (ST->isUnindexed()) {
16056 // Walk up chain skipping non-aliasing memory nodes, on this store and any
16057 // adjacent stores.
16058 if (findBetterNeighborChains(ST)) {
16059 // replaceStoreChain uses CombineTo, which handled all of the worklist
16060 // manipulation. Return the original node to not do anything else.
16061 return SDValue(ST, 0);
16063 Chain = ST->getChain();
16066 // FIXME: is there such a thing as a truncating indexed store?
16067 if (ST->isTruncatingStore() && ST->isUnindexed() &&
16068 Value.getValueType().isInteger() &&
16069 (!isa<ConstantSDNode>(Value) ||
16070 !cast<ConstantSDNode>(Value)->isOpaque())) {
16071 APInt TruncDemandedBits =
16072 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
16073 ST->getMemoryVT().getScalarSizeInBits());
16075 // See if we can simplify the input to this truncstore with knowledge that
16076 // only the low bits are being used. For example:
16077 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
16078 AddToWorklist(Value.getNode());
16079 if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits))
16080 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(),
16081 ST->getMemOperand());
16083 // Otherwise, see if we can simplify the operation with
16084 // SimplifyDemandedBits, which only works if the value has a single use.
16085 if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
16086 // Re-visit the store if anything changed and the store hasn't been merged
16087 // with another node (N is deleted) SimplifyDemandedBits will add Value's
16088 // node back to the worklist if necessary, but we also need to re-visit
16089 // the Store node itself.
16090 if (N->getOpcode() != ISD::DELETED_NODE)
16091 AddToWorklist(N);
16092 return SDValue(N, 0);
16096 // If this is a load followed by a store to the same location, then the store
16097 // is dead/noop.
16098 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
16099 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
16100 ST->isUnindexed() && !ST->isVolatile() &&
16101 // There can't be any side effects between the load and store, such as
16102 // a call or store.
16103 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
16104 // The store is dead, remove it.
16105 return Chain;
16109 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
16110 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
16111 !ST1->isVolatile()) {
16112 if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value &&
16113 ST->getMemoryVT() == ST1->getMemoryVT()) {
16114 // If this is a store followed by a store with the same value to the
16115 // same location, then the store is dead/noop.
16116 return Chain;
16119 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
16120 !ST1->getBasePtr().isUndef()) {
16121 const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG);
16122 const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG);
16123 unsigned STBitSize = ST->getMemoryVT().getSizeInBits();
16124 unsigned ChainBitSize = ST1->getMemoryVT().getSizeInBits();
16125 // If this is a store who's preceding store to a subset of the current
16126 // location and no one other node is chained to that store we can
16127 // effectively drop the store. Do not remove stores to undef as they may
16128 // be used as data sinks.
16129 if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) {
16130 CombineTo(ST1, ST1->getChain());
16131 return SDValue();
16134 // If ST stores to a subset of preceding store's write set, we may be
16135 // able to fold ST's value into the preceding stored value. As we know
16136 // the other uses of ST1's chain are unconcerned with ST, this folding
16137 // will not affect those nodes.
16138 int64_t BitOffset;
16139 if (ChainBase.contains(DAG, ChainBitSize, STBase, STBitSize,
16140 BitOffset)) {
16141 SDValue ChainValue = ST1->getValue();
16142 if (auto *C1 = dyn_cast<ConstantSDNode>(ChainValue)) {
16143 if (auto *C = dyn_cast<ConstantSDNode>(Value)) {
16144 APInt Val = C1->getAPIntValue();
16145 APInt InsertVal = C->getAPIntValue().zextOrTrunc(STBitSize);
16146 // FIXME: Handle Big-endian mode.
16147 if (!DAG.getDataLayout().isBigEndian()) {
16148 Val.insertBits(InsertVal, BitOffset);
16149 SDValue NewSDVal =
16150 DAG.getConstant(Val, SDLoc(C), ChainValue.getValueType(),
16151 C1->isTargetOpcode(), C1->isOpaque());
16152 SDNode *NewST1 = DAG.UpdateNodeOperands(
16153 ST1, ST1->getChain(), NewSDVal, ST1->getOperand(2),
16154 ST1->getOperand(3));
16155 return CombineTo(ST, SDValue(NewST1, 0));
16159 } // End ST subset of ST1 case.
16164 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
16165 // truncating store. We can do this even if this is already a truncstore.
16166 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
16167 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
16168 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
16169 ST->getMemoryVT())) {
16170 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
16171 Ptr, ST->getMemoryVT(), ST->getMemOperand());
16174 // Always perform this optimization before types are legal. If the target
16175 // prefers, also try this after legalization to catch stores that were created
16176 // by intrinsics or other nodes.
16177 if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) {
16178 while (true) {
16179 // There can be multiple store sequences on the same chain.
16180 // Keep trying to merge store sequences until we are unable to do so
16181 // or until we merge the last store on the chain.
16182 bool Changed = MergeConsecutiveStores(ST);
16183 if (!Changed) break;
16184 // Return N as merge only uses CombineTo and no worklist clean
16185 // up is necessary.
16186 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
16187 return SDValue(N, 0);
16191 // Try transforming N to an indexed store.
16192 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
16193 return SDValue(N, 0);
16195 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
16197 // Make sure to do this only after attempting to merge stores in order to
16198 // avoid changing the types of some subset of stores due to visit order,
16199 // preventing their merging.
16200 if (isa<ConstantFPSDNode>(ST->getValue())) {
16201 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
16202 return NewSt;
16205 if (SDValue NewSt = splitMergedValStore(ST))
16206 return NewSt;
16208 return ReduceLoadOpStoreWidth(N);
16211 SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) {
16212 const auto *LifetimeEnd = cast<LifetimeSDNode>(N);
16213 if (!LifetimeEnd->hasOffset())
16214 return SDValue();
16216 const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(),
16217 LifetimeEnd->getOffset(), false);
16219 // We walk up the chains to find stores.
16220 SmallVector<SDValue, 8> Chains = {N->getOperand(0)};
16221 while (!Chains.empty()) {
16222 SDValue Chain = Chains.back();
16223 Chains.pop_back();
16224 if (!Chain.hasOneUse())
16225 continue;
16226 switch (Chain.getOpcode()) {
16227 case ISD::TokenFactor:
16228 for (unsigned Nops = Chain.getNumOperands(); Nops;)
16229 Chains.push_back(Chain.getOperand(--Nops));
16230 break;
16231 case ISD::LIFETIME_START:
16232 case ISD::LIFETIME_END:
16233 // We can forward past any lifetime start/end that can be proven not to
16234 // alias the node.
16235 if (!isAlias(Chain.getNode(), N))
16236 Chains.push_back(Chain.getOperand(0));
16237 break;
16238 case ISD::STORE: {
16239 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain);
16240 if (ST->isVolatile() || ST->isIndexed())
16241 continue;
16242 const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG);
16243 // If we store purely within object bounds just before its lifetime ends,
16244 // we can remove the store.
16245 if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase,
16246 ST->getMemoryVT().getStoreSizeInBits())) {
16247 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump();
16248 dbgs() << "\nwithin LIFETIME_END of : ";
16249 LifetimeEndBase.dump(); dbgs() << "\n");
16250 CombineTo(ST, ST->getChain());
16251 return SDValue(N, 0);
16256 return SDValue();
16259 /// For the instruction sequence of store below, F and I values
16260 /// are bundled together as an i64 value before being stored into memory.
16261 /// Sometimes it is more efficent to generate separate stores for F and I,
16262 /// which can remove the bitwise instructions or sink them to colder places.
16264 /// (store (or (zext (bitcast F to i32) to i64),
16265 /// (shl (zext I to i64), 32)), addr) -->
16266 /// (store F, addr) and (store I, addr+4)
16268 /// Similarly, splitting for other merged store can also be beneficial, like:
16269 /// For pair of {i32, i32}, i64 store --> two i32 stores.
16270 /// For pair of {i32, i16}, i64 store --> two i32 stores.
16271 /// For pair of {i16, i16}, i32 store --> two i16 stores.
16272 /// For pair of {i16, i8}, i32 store --> two i16 stores.
16273 /// For pair of {i8, i8}, i16 store --> two i8 stores.
16275 /// We allow each target to determine specifically which kind of splitting is
16276 /// supported.
16278 /// The store patterns are commonly seen from the simple code snippet below
16279 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
16280 /// void goo(const std::pair<int, float> &);
16281 /// hoo() {
16282 /// ...
16283 /// goo(std::make_pair(tmp, ftmp));
16284 /// ...
16285 /// }
16287 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
16288 if (OptLevel == CodeGenOpt::None)
16289 return SDValue();
16291 SDValue Val = ST->getValue();
16292 SDLoc DL(ST);
16294 // Match OR operand.
16295 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
16296 return SDValue();
16298 // Match SHL operand and get Lower and Higher parts of Val.
16299 SDValue Op1 = Val.getOperand(0);
16300 SDValue Op2 = Val.getOperand(1);
16301 SDValue Lo, Hi;
16302 if (Op1.getOpcode() != ISD::SHL) {
16303 std::swap(Op1, Op2);
16304 if (Op1.getOpcode() != ISD::SHL)
16305 return SDValue();
16307 Lo = Op2;
16308 Hi = Op1.getOperand(0);
16309 if (!Op1.hasOneUse())
16310 return SDValue();
16312 // Match shift amount to HalfValBitSize.
16313 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
16314 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
16315 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
16316 return SDValue();
16318 // Lo and Hi are zero-extended from int with size less equal than 32
16319 // to i64.
16320 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
16321 !Lo.getOperand(0).getValueType().isScalarInteger() ||
16322 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
16323 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
16324 !Hi.getOperand(0).getValueType().isScalarInteger() ||
16325 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
16326 return SDValue();
16328 // Use the EVT of low and high parts before bitcast as the input
16329 // of target query.
16330 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
16331 ? Lo.getOperand(0).getValueType()
16332 : Lo.getValueType();
16333 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
16334 ? Hi.getOperand(0).getValueType()
16335 : Hi.getValueType();
16336 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
16337 return SDValue();
16339 // Start to split store.
16340 unsigned Alignment = ST->getAlignment();
16341 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
16342 AAMDNodes AAInfo = ST->getAAInfo();
16344 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
16345 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
16346 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
16347 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
16349 SDValue Chain = ST->getChain();
16350 SDValue Ptr = ST->getBasePtr();
16351 // Lower value store.
16352 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
16353 ST->getAlignment(), MMOFlags, AAInfo);
16354 Ptr =
16355 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
16356 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
16357 // Higher value store.
16358 SDValue St1 =
16359 DAG.getStore(St0, DL, Hi, Ptr,
16360 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
16361 Alignment / 2, MMOFlags, AAInfo);
16362 return St1;
16365 /// Convert a disguised subvector insertion into a shuffle:
16366 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
16367 /// bitcast(shuffle (bitcast V), (extended X), Mask)
16368 /// Note: We do not use an insert_subvector node because that requires a legal
16369 /// subvector type.
16370 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
16371 SDValue InsertVal = N->getOperand(1);
16372 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
16373 !InsertVal.getOperand(0).getValueType().isVector())
16374 return SDValue();
16376 SDValue SubVec = InsertVal.getOperand(0);
16377 SDValue DestVec = N->getOperand(0);
16378 EVT SubVecVT = SubVec.getValueType();
16379 EVT VT = DestVec.getValueType();
16380 unsigned NumSrcElts = SubVecVT.getVectorNumElements();
16381 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
16382 unsigned NumMaskVals = ExtendRatio * NumSrcElts;
16384 // Step 1: Create a shuffle mask that implements this insert operation. The
16385 // vector that we are inserting into will be operand 0 of the shuffle, so
16386 // those elements are just 'i'. The inserted subvector is in the first
16387 // positions of operand 1 of the shuffle. Example:
16388 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
16389 SmallVector<int, 16> Mask(NumMaskVals);
16390 for (unsigned i = 0; i != NumMaskVals; ++i) {
16391 if (i / NumSrcElts == InsIndex)
16392 Mask[i] = (i % NumSrcElts) + NumMaskVals;
16393 else
16394 Mask[i] = i;
16397 // Bail out if the target can not handle the shuffle we want to create.
16398 EVT SubVecEltVT = SubVecVT.getVectorElementType();
16399 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
16400 if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
16401 return SDValue();
16403 // Step 2: Create a wide vector from the inserted source vector by appending
16404 // undefined elements. This is the same size as our destination vector.
16405 SDLoc DL(N);
16406 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
16407 ConcatOps[0] = SubVec;
16408 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
16410 // Step 3: Shuffle in the padded subvector.
16411 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
16412 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
16413 AddToWorklist(PaddedSubV.getNode());
16414 AddToWorklist(DestVecBC.getNode());
16415 AddToWorklist(Shuf.getNode());
16416 return DAG.getBitcast(VT, Shuf);
16419 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
16420 SDValue InVec = N->getOperand(0);
16421 SDValue InVal = N->getOperand(1);
16422 SDValue EltNo = N->getOperand(2);
16423 SDLoc DL(N);
16425 // If the inserted element is an UNDEF, just use the input vector.
16426 if (InVal.isUndef())
16427 return InVec;
16429 EVT VT = InVec.getValueType();
16430 unsigned NumElts = VT.getVectorNumElements();
16432 // Remove redundant insertions:
16433 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
16434 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
16435 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
16436 return InVec;
16438 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
16439 if (!IndexC) {
16440 // If this is variable insert to undef vector, it might be better to splat:
16441 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
16442 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) {
16443 SmallVector<SDValue, 8> Ops(NumElts, InVal);
16444 return DAG.getBuildVector(VT, DL, Ops);
16446 return SDValue();
16449 // We must know which element is being inserted for folds below here.
16450 unsigned Elt = IndexC->getZExtValue();
16451 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
16452 return Shuf;
16454 // Canonicalize insert_vector_elt dag nodes.
16455 // Example:
16456 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
16457 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
16459 // Do this only if the child insert_vector node has one use; also
16460 // do this only if indices are both constants and Idx1 < Idx0.
16461 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
16462 && isa<ConstantSDNode>(InVec.getOperand(2))) {
16463 unsigned OtherElt = InVec.getConstantOperandVal(2);
16464 if (Elt < OtherElt) {
16465 // Swap nodes.
16466 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
16467 InVec.getOperand(0), InVal, EltNo);
16468 AddToWorklist(NewOp.getNode());
16469 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
16470 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
16474 // If we can't generate a legal BUILD_VECTOR, exit
16475 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
16476 return SDValue();
16478 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
16479 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
16480 // vector elements.
16481 SmallVector<SDValue, 8> Ops;
16482 // Do not combine these two vectors if the output vector will not replace
16483 // the input vector.
16484 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
16485 Ops.append(InVec.getNode()->op_begin(),
16486 InVec.getNode()->op_end());
16487 } else if (InVec.isUndef()) {
16488 Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType()));
16489 } else {
16490 return SDValue();
16492 assert(Ops.size() == NumElts && "Unexpected vector size");
16494 // Insert the element
16495 if (Elt < Ops.size()) {
16496 // All the operands of BUILD_VECTOR must have the same type;
16497 // we enforce that here.
16498 EVT OpVT = Ops[0].getValueType();
16499 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
16502 // Return the new vector
16503 return DAG.getBuildVector(VT, DL, Ops);
16506 SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
16507 SDValue EltNo,
16508 LoadSDNode *OriginalLoad) {
16509 assert(!OriginalLoad->isVolatile());
16511 EVT ResultVT = EVE->getValueType(0);
16512 EVT VecEltVT = InVecVT.getVectorElementType();
16513 unsigned Align = OriginalLoad->getAlignment();
16514 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
16515 VecEltVT.getTypeForEVT(*DAG.getContext()));
16517 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
16518 return SDValue();
16520 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
16521 ISD::NON_EXTLOAD : ISD::EXTLOAD;
16522 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
16523 return SDValue();
16525 Align = NewAlign;
16527 SDValue NewPtr = OriginalLoad->getBasePtr();
16528 SDValue Offset;
16529 EVT PtrType = NewPtr.getValueType();
16530 MachinePointerInfo MPI;
16531 SDLoc DL(EVE);
16532 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
16533 int Elt = ConstEltNo->getZExtValue();
16534 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
16535 Offset = DAG.getConstant(PtrOff, DL, PtrType);
16536 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
16537 } else {
16538 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
16539 Offset = DAG.getNode(
16540 ISD::MUL, DL, PtrType, Offset,
16541 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
16542 // Discard the pointer info except the address space because the memory
16543 // operand can't represent this new access since the offset is variable.
16544 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
16546 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
16548 // The replacement we need to do here is a little tricky: we need to
16549 // replace an extractelement of a load with a load.
16550 // Use ReplaceAllUsesOfValuesWith to do the replacement.
16551 // Note that this replacement assumes that the extractvalue is the only
16552 // use of the load; that's okay because we don't want to perform this
16553 // transformation in other cases anyway.
16554 SDValue Load;
16555 SDValue Chain;
16556 if (ResultVT.bitsGT(VecEltVT)) {
16557 // If the result type of vextract is wider than the load, then issue an
16558 // extending load instead.
16559 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
16560 VecEltVT)
16561 ? ISD::ZEXTLOAD
16562 : ISD::EXTLOAD;
16563 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
16564 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
16565 Align, OriginalLoad->getMemOperand()->getFlags(),
16566 OriginalLoad->getAAInfo());
16567 Chain = Load.getValue(1);
16568 } else {
16569 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
16570 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
16571 OriginalLoad->getAAInfo());
16572 Chain = Load.getValue(1);
16573 if (ResultVT.bitsLT(VecEltVT))
16574 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
16575 else
16576 Load = DAG.getBitcast(ResultVT, Load);
16578 WorklistRemover DeadNodes(*this);
16579 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
16580 SDValue To[] = { Load, Chain };
16581 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
16582 // Since we're explicitly calling ReplaceAllUses, add the new node to the
16583 // worklist explicitly as well.
16584 AddToWorklist(Load.getNode());
16585 AddUsersToWorklist(Load.getNode()); // Add users too
16586 // Make sure to revisit this node to clean it up; it will usually be dead.
16587 AddToWorklist(EVE);
16588 ++OpsNarrowed;
16589 return SDValue(EVE, 0);
16592 /// Transform a vector binary operation into a scalar binary operation by moving
16593 /// the math/logic after an extract element of a vector.
16594 static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG,
16595 bool LegalOperations) {
16596 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16597 SDValue Vec = ExtElt->getOperand(0);
16598 SDValue Index = ExtElt->getOperand(1);
16599 auto *IndexC = dyn_cast<ConstantSDNode>(Index);
16600 if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() ||
16601 Vec.getNode()->getNumValues() != 1)
16602 return SDValue();
16604 // Targets may want to avoid this to prevent an expensive register transfer.
16605 if (!TLI.shouldScalarizeBinop(Vec))
16606 return SDValue();
16608 // Extracting an element of a vector constant is constant-folded, so this
16609 // transform is just replacing a vector op with a scalar op while moving the
16610 // extract.
16611 SDValue Op0 = Vec.getOperand(0);
16612 SDValue Op1 = Vec.getOperand(1);
16613 if (isAnyConstantBuildVector(Op0, true) ||
16614 isAnyConstantBuildVector(Op1, true)) {
16615 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
16616 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
16617 SDLoc DL(ExtElt);
16618 EVT VT = ExtElt->getValueType(0);
16619 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index);
16620 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index);
16621 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1);
16624 return SDValue();
16627 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
16628 SDValue VecOp = N->getOperand(0);
16629 SDValue Index = N->getOperand(1);
16630 EVT ScalarVT = N->getValueType(0);
16631 EVT VecVT = VecOp.getValueType();
16632 if (VecOp.isUndef())
16633 return DAG.getUNDEF(ScalarVT);
16635 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
16637 // This only really matters if the index is non-constant since other combines
16638 // on the constant elements already work.
16639 SDLoc DL(N);
16640 if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT &&
16641 Index == VecOp.getOperand(2)) {
16642 SDValue Elt = VecOp.getOperand(1);
16643 return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt;
16646 // (vextract (scalar_to_vector val, 0) -> val
16647 if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) {
16648 // Check if the result type doesn't match the inserted element type. A
16649 // SCALAR_TO_VECTOR may truncate the inserted element and the
16650 // EXTRACT_VECTOR_ELT may widen the extracted vector.
16651 SDValue InOp = VecOp.getOperand(0);
16652 if (InOp.getValueType() != ScalarVT) {
16653 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
16654 return DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
16656 return InOp;
16659 // extract_vector_elt of out-of-bounds element -> UNDEF
16660 auto *IndexC = dyn_cast<ConstantSDNode>(Index);
16661 unsigned NumElts = VecVT.getVectorNumElements();
16662 if (IndexC && IndexC->getAPIntValue().uge(NumElts))
16663 return DAG.getUNDEF(ScalarVT);
16665 // extract_vector_elt (build_vector x, y), 1 -> y
16666 if (IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR &&
16667 TLI.isTypeLegal(VecVT) &&
16668 (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) {
16669 SDValue Elt = VecOp.getOperand(IndexC->getZExtValue());
16670 EVT InEltVT = Elt.getValueType();
16672 // Sometimes build_vector's scalar input types do not match result type.
16673 if (ScalarVT == InEltVT)
16674 return Elt;
16676 // TODO: It may be useful to truncate if free if the build_vector implicitly
16677 // converts.
16680 // TODO: These transforms should not require the 'hasOneUse' restriction, but
16681 // there are regressions on multiple targets without it. We can end up with a
16682 // mess of scalar and vector code if we reduce only part of the DAG to scalar.
16683 if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() &&
16684 VecOp.hasOneUse()) {
16685 // The vector index of the LSBs of the source depend on the endian-ness.
16686 bool IsLE = DAG.getDataLayout().isLittleEndian();
16687 unsigned ExtractIndex = IndexC->getZExtValue();
16688 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
16689 unsigned BCTruncElt = IsLE ? 0 : NumElts - 1;
16690 SDValue BCSrc = VecOp.getOperand(0);
16691 if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger())
16692 return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc);
16694 if (LegalTypes && BCSrc.getValueType().isInteger() &&
16695 BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) {
16696 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
16697 // trunc i64 X to i32
16698 SDValue X = BCSrc.getOperand(0);
16699 assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() &&
16700 "Extract element and scalar to vector can't change element type "
16701 "from FP to integer.");
16702 unsigned XBitWidth = X.getValueSizeInBits();
16703 unsigned VecEltBitWidth = VecVT.getScalarSizeInBits();
16704 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1;
16706 // An extract element return value type can be wider than its vector
16707 // operand element type. In that case, the high bits are undefined, so
16708 // it's possible that we may need to extend rather than truncate.
16709 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) {
16710 assert(XBitWidth % VecEltBitWidth == 0 &&
16711 "Scalar bitwidth must be a multiple of vector element bitwidth");
16712 return DAG.getAnyExtOrTrunc(X, DL, ScalarVT);
16717 if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations))
16718 return BO;
16720 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
16721 // We only perform this optimization before the op legalization phase because
16722 // we may introduce new vector instructions which are not backed by TD
16723 // patterns. For example on AVX, extracting elements from a wide vector
16724 // without using extract_subvector. However, if we can find an underlying
16725 // scalar value, then we can always use that.
16726 if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
16727 auto *Shuf = cast<ShuffleVectorSDNode>(VecOp);
16728 // Find the new index to extract from.
16729 int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue());
16731 // Extracting an undef index is undef.
16732 if (OrigElt == -1)
16733 return DAG.getUNDEF(ScalarVT);
16735 // Select the right vector half to extract from.
16736 SDValue SVInVec;
16737 if (OrigElt < (int)NumElts) {
16738 SVInVec = VecOp.getOperand(0);
16739 } else {
16740 SVInVec = VecOp.getOperand(1);
16741 OrigElt -= NumElts;
16744 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
16745 SDValue InOp = SVInVec.getOperand(OrigElt);
16746 if (InOp.getValueType() != ScalarVT) {
16747 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
16748 InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
16751 return InOp;
16754 // FIXME: We should handle recursing on other vector shuffles and
16755 // scalar_to_vector here as well.
16757 if (!LegalOperations ||
16758 // FIXME: Should really be just isOperationLegalOrCustom.
16759 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) ||
16760 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) {
16761 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16762 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec,
16763 DAG.getConstant(OrigElt, DL, IndexTy));
16767 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
16768 // simplify it based on the (valid) extraction indices.
16769 if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) {
16770 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
16771 Use->getOperand(0) == VecOp &&
16772 isa<ConstantSDNode>(Use->getOperand(1));
16773 })) {
16774 APInt DemandedElts = APInt::getNullValue(NumElts);
16775 for (SDNode *Use : VecOp->uses()) {
16776 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1));
16777 if (CstElt->getAPIntValue().ult(NumElts))
16778 DemandedElts.setBit(CstElt->getZExtValue());
16780 if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) {
16781 // We simplified the vector operand of this extract element. If this
16782 // extract is not dead, visit it again so it is folded properly.
16783 if (N->getOpcode() != ISD::DELETED_NODE)
16784 AddToWorklist(N);
16785 return SDValue(N, 0);
16789 // Everything under here is trying to match an extract of a loaded value.
16790 // If the result of load has to be truncated, then it's not necessarily
16791 // profitable.
16792 bool BCNumEltsChanged = false;
16793 EVT ExtVT = VecVT.getVectorElementType();
16794 EVT LVT = ExtVT;
16795 if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT))
16796 return SDValue();
16798 if (VecOp.getOpcode() == ISD::BITCAST) {
16799 // Don't duplicate a load with other uses.
16800 if (!VecOp.hasOneUse())
16801 return SDValue();
16803 EVT BCVT = VecOp.getOperand(0).getValueType();
16804 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
16805 return SDValue();
16806 if (NumElts != BCVT.getVectorNumElements())
16807 BCNumEltsChanged = true;
16808 VecOp = VecOp.getOperand(0);
16809 ExtVT = BCVT.getVectorElementType();
16812 // extract (vector load $addr), i --> load $addr + i * size
16813 if (!LegalOperations && !IndexC && VecOp.hasOneUse() &&
16814 ISD::isNormalLoad(VecOp.getNode()) &&
16815 !Index->hasPredecessor(VecOp.getNode())) {
16816 auto *VecLoad = dyn_cast<LoadSDNode>(VecOp);
16817 if (VecLoad && !VecLoad->isVolatile())
16818 return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad);
16821 // Perform only after legalization to ensure build_vector / vector_shuffle
16822 // optimizations have already been done.
16823 if (!LegalOperations || !IndexC)
16824 return SDValue();
16826 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
16827 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
16828 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
16829 int Elt = IndexC->getZExtValue();
16830 LoadSDNode *LN0 = nullptr;
16831 if (ISD::isNormalLoad(VecOp.getNode())) {
16832 LN0 = cast<LoadSDNode>(VecOp);
16833 } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
16834 VecOp.getOperand(0).getValueType() == ExtVT &&
16835 ISD::isNormalLoad(VecOp.getOperand(0).getNode())) {
16836 // Don't duplicate a load with other uses.
16837 if (!VecOp.hasOneUse())
16838 return SDValue();
16840 LN0 = cast<LoadSDNode>(VecOp.getOperand(0));
16842 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) {
16843 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
16844 // =>
16845 // (load $addr+1*size)
16847 // Don't duplicate a load with other uses.
16848 if (!VecOp.hasOneUse())
16849 return SDValue();
16851 // If the bit convert changed the number of elements, it is unsafe
16852 // to examine the mask.
16853 if (BCNumEltsChanged)
16854 return SDValue();
16856 // Select the input vector, guarding against out of range extract vector.
16857 int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt);
16858 VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1);
16860 if (VecOp.getOpcode() == ISD::BITCAST) {
16861 // Don't duplicate a load with other uses.
16862 if (!VecOp.hasOneUse())
16863 return SDValue();
16865 VecOp = VecOp.getOperand(0);
16867 if (ISD::isNormalLoad(VecOp.getNode())) {
16868 LN0 = cast<LoadSDNode>(VecOp);
16869 Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts;
16870 Index = DAG.getConstant(Elt, DL, Index.getValueType());
16874 // Make sure we found a non-volatile load and the extractelement is
16875 // the only use.
16876 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
16877 return SDValue();
16879 // If Idx was -1 above, Elt is going to be -1, so just return undef.
16880 if (Elt == -1)
16881 return DAG.getUNDEF(LVT);
16883 return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0);
16886 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
16887 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
16888 // We perform this optimization post type-legalization because
16889 // the type-legalizer often scalarizes integer-promoted vectors.
16890 // Performing this optimization before may create bit-casts which
16891 // will be type-legalized to complex code sequences.
16892 // We perform this optimization only before the operation legalizer because we
16893 // may introduce illegal operations.
16894 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
16895 return SDValue();
16897 unsigned NumInScalars = N->getNumOperands();
16898 SDLoc DL(N);
16899 EVT VT = N->getValueType(0);
16901 // Check to see if this is a BUILD_VECTOR of a bunch of values
16902 // which come from any_extend or zero_extend nodes. If so, we can create
16903 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
16904 // optimizations. We do not handle sign-extend because we can't fill the sign
16905 // using shuffles.
16906 EVT SourceType = MVT::Other;
16907 bool AllAnyExt = true;
16909 for (unsigned i = 0; i != NumInScalars; ++i) {
16910 SDValue In = N->getOperand(i);
16911 // Ignore undef inputs.
16912 if (In.isUndef()) continue;
16914 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
16915 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
16917 // Abort if the element is not an extension.
16918 if (!ZeroExt && !AnyExt) {
16919 SourceType = MVT::Other;
16920 break;
16923 // The input is a ZeroExt or AnyExt. Check the original type.
16924 EVT InTy = In.getOperand(0).getValueType();
16926 // Check that all of the widened source types are the same.
16927 if (SourceType == MVT::Other)
16928 // First time.
16929 SourceType = InTy;
16930 else if (InTy != SourceType) {
16931 // Multiple income types. Abort.
16932 SourceType = MVT::Other;
16933 break;
16936 // Check if all of the extends are ANY_EXTENDs.
16937 AllAnyExt &= AnyExt;
16940 // In order to have valid types, all of the inputs must be extended from the
16941 // same source type and all of the inputs must be any or zero extend.
16942 // Scalar sizes must be a power of two.
16943 EVT OutScalarTy = VT.getScalarType();
16944 bool ValidTypes = SourceType != MVT::Other &&
16945 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
16946 isPowerOf2_32(SourceType.getSizeInBits());
16948 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
16949 // turn into a single shuffle instruction.
16950 if (!ValidTypes)
16951 return SDValue();
16953 bool isLE = DAG.getDataLayout().isLittleEndian();
16954 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
16955 assert(ElemRatio > 1 && "Invalid element size ratio");
16956 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
16957 DAG.getConstant(0, DL, SourceType);
16959 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
16960 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
16962 // Populate the new build_vector
16963 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16964 SDValue Cast = N->getOperand(i);
16965 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
16966 Cast.getOpcode() == ISD::ZERO_EXTEND ||
16967 Cast.isUndef()) && "Invalid cast opcode");
16968 SDValue In;
16969 if (Cast.isUndef())
16970 In = DAG.getUNDEF(SourceType);
16971 else
16972 In = Cast->getOperand(0);
16973 unsigned Index = isLE ? (i * ElemRatio) :
16974 (i * ElemRatio + (ElemRatio - 1));
16976 assert(Index < Ops.size() && "Invalid index");
16977 Ops[Index] = In;
16980 // The type of the new BUILD_VECTOR node.
16981 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
16982 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
16983 "Invalid vector size");
16984 // Check if the new vector type is legal.
16985 if (!isTypeLegal(VecVT) ||
16986 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) &&
16987 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)))
16988 return SDValue();
16990 // Make the new BUILD_VECTOR.
16991 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
16993 // The new BUILD_VECTOR node has the potential to be further optimized.
16994 AddToWorklist(BV.getNode());
16995 // Bitcast to the desired type.
16996 return DAG.getBitcast(VT, BV);
16999 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
17000 ArrayRef<int> VectorMask,
17001 SDValue VecIn1, SDValue VecIn2,
17002 unsigned LeftIdx, bool DidSplitVec) {
17003 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
17004 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
17006 EVT VT = N->getValueType(0);
17007 EVT InVT1 = VecIn1.getValueType();
17008 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
17010 unsigned NumElems = VT.getVectorNumElements();
17011 unsigned ShuffleNumElems = NumElems;
17013 // If we artificially split a vector in two already, then the offsets in the
17014 // operands will all be based off of VecIn1, even those in VecIn2.
17015 unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements();
17017 // We can't generate a shuffle node with mismatched input and output types.
17018 // Try to make the types match the type of the output.
17019 if (InVT1 != VT || InVT2 != VT) {
17020 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
17021 // If the output vector length is a multiple of both input lengths,
17022 // we can concatenate them and pad the rest with undefs.
17023 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
17024 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
17025 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
17026 ConcatOps[0] = VecIn1;
17027 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
17028 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
17029 VecIn2 = SDValue();
17030 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
17031 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
17032 return SDValue();
17034 if (!VecIn2.getNode()) {
17035 // If we only have one input vector, and it's twice the size of the
17036 // output, split it in two.
17037 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
17038 DAG.getConstant(NumElems, DL, IdxTy));
17039 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
17040 // Since we now have shorter input vectors, adjust the offset of the
17041 // second vector's start.
17042 Vec2Offset = NumElems;
17043 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
17044 // VecIn1 is wider than the output, and we have another, possibly
17045 // smaller input. Pad the smaller input with undefs, shuffle at the
17046 // input vector width, and extract the output.
17047 // The shuffle type is different than VT, so check legality again.
17048 if (LegalOperations &&
17049 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
17050 return SDValue();
17052 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
17053 // lower it back into a BUILD_VECTOR. So if the inserted type is
17054 // illegal, don't even try.
17055 if (InVT1 != InVT2) {
17056 if (!TLI.isTypeLegal(InVT2))
17057 return SDValue();
17058 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
17059 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
17061 ShuffleNumElems = NumElems * 2;
17062 } else {
17063 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
17064 // than VecIn1. We can't handle this for now - this case will disappear
17065 // when we start sorting the vectors by type.
17066 return SDValue();
17068 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
17069 InVT1.getSizeInBits() == VT.getSizeInBits()) {
17070 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
17071 ConcatOps[0] = VecIn2;
17072 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
17073 } else {
17074 // TODO: Support cases where the length mismatch isn't exactly by a
17075 // factor of 2.
17076 // TODO: Move this check upwards, so that if we have bad type
17077 // mismatches, we don't create any DAG nodes.
17078 return SDValue();
17082 // Initialize mask to undef.
17083 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
17085 // Only need to run up to the number of elements actually used, not the
17086 // total number of elements in the shuffle - if we are shuffling a wider
17087 // vector, the high lanes should be set to undef.
17088 for (unsigned i = 0; i != NumElems; ++i) {
17089 if (VectorMask[i] <= 0)
17090 continue;
17092 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
17093 if (VectorMask[i] == (int)LeftIdx) {
17094 Mask[i] = ExtIndex;
17095 } else if (VectorMask[i] == (int)LeftIdx + 1) {
17096 Mask[i] = Vec2Offset + ExtIndex;
17100 // The type the input vectors may have changed above.
17101 InVT1 = VecIn1.getValueType();
17103 // If we already have a VecIn2, it should have the same type as VecIn1.
17104 // If we don't, get an undef/zero vector of the appropriate type.
17105 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
17106 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
17108 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
17109 if (ShuffleNumElems > NumElems)
17110 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
17112 return Shuffle;
17115 static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) {
17116 assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
17118 // First, determine where the build vector is not undef.
17119 // TODO: We could extend this to handle zero elements as well as undefs.
17120 int NumBVOps = BV->getNumOperands();
17121 int ZextElt = -1;
17122 for (int i = 0; i != NumBVOps; ++i) {
17123 SDValue Op = BV->getOperand(i);
17124 if (Op.isUndef())
17125 continue;
17126 if (ZextElt == -1)
17127 ZextElt = i;
17128 else
17129 return SDValue();
17131 // Bail out if there's no non-undef element.
17132 if (ZextElt == -1)
17133 return SDValue();
17135 // The build vector contains some number of undef elements and exactly
17136 // one other element. That other element must be a zero-extended scalar
17137 // extracted from a vector at a constant index to turn this into a shuffle.
17138 // Also, require that the build vector does not implicitly truncate/extend
17139 // its elements.
17140 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
17141 EVT VT = BV->getValueType(0);
17142 SDValue Zext = BV->getOperand(ZextElt);
17143 if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() ||
17144 Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
17145 !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) ||
17146 Zext.getValueSizeInBits() != VT.getScalarSizeInBits())
17147 return SDValue();
17149 // The zero-extend must be a multiple of the source size, and we must be
17150 // building a vector of the same size as the source of the extract element.
17151 SDValue Extract = Zext.getOperand(0);
17152 unsigned DestSize = Zext.getValueSizeInBits();
17153 unsigned SrcSize = Extract.getValueSizeInBits();
17154 if (DestSize % SrcSize != 0 ||
17155 Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits())
17156 return SDValue();
17158 // Create a shuffle mask that will combine the extracted element with zeros
17159 // and undefs.
17160 int ZextRatio = DestSize / SrcSize;
17161 int NumMaskElts = NumBVOps * ZextRatio;
17162 SmallVector<int, 32> ShufMask(NumMaskElts, -1);
17163 for (int i = 0; i != NumMaskElts; ++i) {
17164 if (i / ZextRatio == ZextElt) {
17165 // The low bits of the (potentially translated) extracted element map to
17166 // the source vector. The high bits map to zero. We will use a zero vector
17167 // as the 2nd source operand of the shuffle, so use the 1st element of
17168 // that vector (mask value is number-of-elements) for the high bits.
17169 if (i % ZextRatio == 0)
17170 ShufMask[i] = Extract.getConstantOperandVal(1);
17171 else
17172 ShufMask[i] = NumMaskElts;
17175 // Undef elements of the build vector remain undef because we initialize
17176 // the shuffle mask with -1.
17179 // Turn this into a shuffle with zero if that's legal.
17180 EVT VecVT = Extract.getOperand(0).getValueType();
17181 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(ShufMask, VecVT))
17182 return SDValue();
17184 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
17185 // bitcast (shuffle V, ZeroVec, VectorMask)
17186 SDLoc DL(BV);
17187 SDValue ZeroVec = DAG.getConstant(0, DL, VecVT);
17188 SDValue Shuf = DAG.getVectorShuffle(VecVT, DL, Extract.getOperand(0), ZeroVec,
17189 ShufMask);
17190 return DAG.getBitcast(VT, Shuf);
17193 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
17194 // operations. If the types of the vectors we're extracting from allow it,
17195 // turn this into a vector_shuffle node.
17196 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
17197 SDLoc DL(N);
17198 EVT VT = N->getValueType(0);
17200 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
17201 if (!isTypeLegal(VT))
17202 return SDValue();
17204 if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG))
17205 return V;
17207 // May only combine to shuffle after legalize if shuffle is legal.
17208 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
17209 return SDValue();
17211 bool UsesZeroVector = false;
17212 unsigned NumElems = N->getNumOperands();
17214 // Record, for each element of the newly built vector, which input vector
17215 // that element comes from. -1 stands for undef, 0 for the zero vector,
17216 // and positive values for the input vectors.
17217 // VectorMask maps each element to its vector number, and VecIn maps vector
17218 // numbers to their initial SDValues.
17220 SmallVector<int, 8> VectorMask(NumElems, -1);
17221 SmallVector<SDValue, 8> VecIn;
17222 VecIn.push_back(SDValue());
17224 for (unsigned i = 0; i != NumElems; ++i) {
17225 SDValue Op = N->getOperand(i);
17227 if (Op.isUndef())
17228 continue;
17230 // See if we can use a blend with a zero vector.
17231 // TODO: Should we generalize this to a blend with an arbitrary constant
17232 // vector?
17233 if (isNullConstant(Op) || isNullFPConstant(Op)) {
17234 UsesZeroVector = true;
17235 VectorMask[i] = 0;
17236 continue;
17239 // Not an undef or zero. If the input is something other than an
17240 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
17241 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
17242 !isa<ConstantSDNode>(Op.getOperand(1)))
17243 return SDValue();
17244 SDValue ExtractedFromVec = Op.getOperand(0);
17246 const APInt &ExtractIdx = Op.getConstantOperandAPInt(1);
17247 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
17248 return SDValue();
17250 // All inputs must have the same element type as the output.
17251 if (VT.getVectorElementType() !=
17252 ExtractedFromVec.getValueType().getVectorElementType())
17253 return SDValue();
17255 // Have we seen this input vector before?
17256 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
17257 // a map back from SDValues to numbers isn't worth it.
17258 unsigned Idx = std::distance(
17259 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
17260 if (Idx == VecIn.size())
17261 VecIn.push_back(ExtractedFromVec);
17263 VectorMask[i] = Idx;
17266 // If we didn't find at least one input vector, bail out.
17267 if (VecIn.size() < 2)
17268 return SDValue();
17270 // If all the Operands of BUILD_VECTOR extract from same
17271 // vector, then split the vector efficiently based on the maximum
17272 // vector access index and adjust the VectorMask and
17273 // VecIn accordingly.
17274 bool DidSplitVec = false;
17275 if (VecIn.size() == 2) {
17276 unsigned MaxIndex = 0;
17277 unsigned NearestPow2 = 0;
17278 SDValue Vec = VecIn.back();
17279 EVT InVT = Vec.getValueType();
17280 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
17281 SmallVector<unsigned, 8> IndexVec(NumElems, 0);
17283 for (unsigned i = 0; i < NumElems; i++) {
17284 if (VectorMask[i] <= 0)
17285 continue;
17286 unsigned Index = N->getOperand(i).getConstantOperandVal(1);
17287 IndexVec[i] = Index;
17288 MaxIndex = std::max(MaxIndex, Index);
17291 NearestPow2 = PowerOf2Ceil(MaxIndex);
17292 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
17293 NumElems * 2 < NearestPow2) {
17294 unsigned SplitSize = NearestPow2 / 2;
17295 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
17296 InVT.getVectorElementType(), SplitSize);
17297 if (TLI.isTypeLegal(SplitVT)) {
17298 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
17299 DAG.getConstant(SplitSize, DL, IdxTy));
17300 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
17301 DAG.getConstant(0, DL, IdxTy));
17302 VecIn.pop_back();
17303 VecIn.push_back(VecIn1);
17304 VecIn.push_back(VecIn2);
17305 DidSplitVec = true;
17307 for (unsigned i = 0; i < NumElems; i++) {
17308 if (VectorMask[i] <= 0)
17309 continue;
17310 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
17316 // TODO: We want to sort the vectors by descending length, so that adjacent
17317 // pairs have similar length, and the longer vector is always first in the
17318 // pair.
17320 // TODO: Should this fire if some of the input vectors has illegal type (like
17321 // it does now), or should we let legalization run its course first?
17323 // Shuffle phase:
17324 // Take pairs of vectors, and shuffle them so that the result has elements
17325 // from these vectors in the correct places.
17326 // For example, given:
17327 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
17328 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
17329 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
17330 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
17331 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
17332 // We will generate:
17333 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
17334 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
17335 SmallVector<SDValue, 4> Shuffles;
17336 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
17337 unsigned LeftIdx = 2 * In + 1;
17338 SDValue VecLeft = VecIn[LeftIdx];
17339 SDValue VecRight =
17340 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
17342 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
17343 VecRight, LeftIdx, DidSplitVec))
17344 Shuffles.push_back(Shuffle);
17345 else
17346 return SDValue();
17349 // If we need the zero vector as an "ingredient" in the blend tree, add it
17350 // to the list of shuffles.
17351 if (UsesZeroVector)
17352 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
17353 : DAG.getConstantFP(0.0, DL, VT));
17355 // If we only have one shuffle, we're done.
17356 if (Shuffles.size() == 1)
17357 return Shuffles[0];
17359 // Update the vector mask to point to the post-shuffle vectors.
17360 for (int &Vec : VectorMask)
17361 if (Vec == 0)
17362 Vec = Shuffles.size() - 1;
17363 else
17364 Vec = (Vec - 1) / 2;
17366 // More than one shuffle. Generate a binary tree of blends, e.g. if from
17367 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
17368 // generate:
17369 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
17370 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
17371 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
17372 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
17373 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
17374 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
17375 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
17377 // Make sure the initial size of the shuffle list is even.
17378 if (Shuffles.size() % 2)
17379 Shuffles.push_back(DAG.getUNDEF(VT));
17381 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
17382 if (CurSize % 2) {
17383 Shuffles[CurSize] = DAG.getUNDEF(VT);
17384 CurSize++;
17386 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
17387 int Left = 2 * In;
17388 int Right = 2 * In + 1;
17389 SmallVector<int, 8> Mask(NumElems, -1);
17390 for (unsigned i = 0; i != NumElems; ++i) {
17391 if (VectorMask[i] == Left) {
17392 Mask[i] = i;
17393 VectorMask[i] = In;
17394 } else if (VectorMask[i] == Right) {
17395 Mask[i] = i + NumElems;
17396 VectorMask[i] = In;
17400 Shuffles[In] =
17401 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
17404 return Shuffles[0];
17407 // Try to turn a build vector of zero extends of extract vector elts into a
17408 // a vector zero extend and possibly an extract subvector.
17409 // TODO: Support sign extend?
17410 // TODO: Allow undef elements?
17411 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
17412 if (LegalOperations)
17413 return SDValue();
17415 EVT VT = N->getValueType(0);
17417 bool FoundZeroExtend = false;
17418 SDValue Op0 = N->getOperand(0);
17419 auto checkElem = [&](SDValue Op) -> int64_t {
17420 unsigned Opc = Op.getOpcode();
17421 FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND);
17422 if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) &&
17423 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
17424 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
17425 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
17426 return C->getZExtValue();
17427 return -1;
17430 // Make sure the first element matches
17431 // (zext (extract_vector_elt X, C))
17432 int64_t Offset = checkElem(Op0);
17433 if (Offset < 0)
17434 return SDValue();
17436 unsigned NumElems = N->getNumOperands();
17437 SDValue In = Op0.getOperand(0).getOperand(0);
17438 EVT InSVT = In.getValueType().getScalarType();
17439 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
17441 // Don't create an illegal input type after type legalization.
17442 if (LegalTypes && !TLI.isTypeLegal(InVT))
17443 return SDValue();
17445 // Ensure all the elements come from the same vector and are adjacent.
17446 for (unsigned i = 1; i != NumElems; ++i) {
17447 if ((Offset + i) != checkElem(N->getOperand(i)))
17448 return SDValue();
17451 SDLoc DL(N);
17452 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
17453 Op0.getOperand(0).getOperand(1));
17454 return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL,
17455 VT, In);
17458 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
17459 EVT VT = N->getValueType(0);
17461 // A vector built entirely of undefs is undef.
17462 if (ISD::allOperandsUndef(N))
17463 return DAG.getUNDEF(VT);
17465 // If this is a splat of a bitcast from another vector, change to a
17466 // concat_vector.
17467 // For example:
17468 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
17469 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
17471 // If X is a build_vector itself, the concat can become a larger build_vector.
17472 // TODO: Maybe this is useful for non-splat too?
17473 if (!LegalOperations) {
17474 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
17475 Splat = peekThroughBitcasts(Splat);
17476 EVT SrcVT = Splat.getValueType();
17477 if (SrcVT.isVector()) {
17478 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
17479 EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
17480 SrcVT.getVectorElementType(), NumElts);
17481 if (!LegalTypes || TLI.isTypeLegal(NewVT)) {
17482 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
17483 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N),
17484 NewVT, Ops);
17485 return DAG.getBitcast(VT, Concat);
17491 // Check if we can express BUILD VECTOR via subvector extract.
17492 if (!LegalTypes && (N->getNumOperands() > 1)) {
17493 SDValue Op0 = N->getOperand(0);
17494 auto checkElem = [&](SDValue Op) -> uint64_t {
17495 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
17496 (Op0.getOperand(0) == Op.getOperand(0)))
17497 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
17498 return CNode->getZExtValue();
17499 return -1;
17502 int Offset = checkElem(Op0);
17503 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
17504 if (Offset + i != checkElem(N->getOperand(i))) {
17505 Offset = -1;
17506 break;
17510 if ((Offset == 0) &&
17511 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
17512 return Op0.getOperand(0);
17513 if ((Offset != -1) &&
17514 ((Offset % N->getValueType(0).getVectorNumElements()) ==
17515 0)) // IDX must be multiple of output size.
17516 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
17517 Op0.getOperand(0), Op0.getOperand(1));
17520 if (SDValue V = convertBuildVecZextToZext(N))
17521 return V;
17523 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
17524 return V;
17526 if (SDValue V = reduceBuildVecToShuffle(N))
17527 return V;
17529 return SDValue();
17532 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
17533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17534 EVT OpVT = N->getOperand(0).getValueType();
17536 // If the operands are legal vectors, leave them alone.
17537 if (TLI.isTypeLegal(OpVT))
17538 return SDValue();
17540 SDLoc DL(N);
17541 EVT VT = N->getValueType(0);
17542 SmallVector<SDValue, 8> Ops;
17544 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
17545 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
17547 // Keep track of what we encounter.
17548 bool AnyInteger = false;
17549 bool AnyFP = false;
17550 for (const SDValue &Op : N->ops()) {
17551 if (ISD::BITCAST == Op.getOpcode() &&
17552 !Op.getOperand(0).getValueType().isVector())
17553 Ops.push_back(Op.getOperand(0));
17554 else if (ISD::UNDEF == Op.getOpcode())
17555 Ops.push_back(ScalarUndef);
17556 else
17557 return SDValue();
17559 // Note whether we encounter an integer or floating point scalar.
17560 // If it's neither, bail out, it could be something weird like x86mmx.
17561 EVT LastOpVT = Ops.back().getValueType();
17562 if (LastOpVT.isFloatingPoint())
17563 AnyFP = true;
17564 else if (LastOpVT.isInteger())
17565 AnyInteger = true;
17566 else
17567 return SDValue();
17570 // If any of the operands is a floating point scalar bitcast to a vector,
17571 // use floating point types throughout, and bitcast everything.
17572 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
17573 if (AnyFP) {
17574 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
17575 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
17576 if (AnyInteger) {
17577 for (SDValue &Op : Ops) {
17578 if (Op.getValueType() == SVT)
17579 continue;
17580 if (Op.isUndef())
17581 Op = ScalarUndef;
17582 else
17583 Op = DAG.getBitcast(SVT, Op);
17588 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
17589 VT.getSizeInBits() / SVT.getSizeInBits());
17590 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
17593 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
17594 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
17595 // most two distinct vectors the same size as the result, attempt to turn this
17596 // into a legal shuffle.
17597 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
17598 EVT VT = N->getValueType(0);
17599 EVT OpVT = N->getOperand(0).getValueType();
17600 int NumElts = VT.getVectorNumElements();
17601 int NumOpElts = OpVT.getVectorNumElements();
17603 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
17604 SmallVector<int, 8> Mask;
17606 for (SDValue Op : N->ops()) {
17607 Op = peekThroughBitcasts(Op);
17609 // UNDEF nodes convert to UNDEF shuffle mask values.
17610 if (Op.isUndef()) {
17611 Mask.append((unsigned)NumOpElts, -1);
17612 continue;
17615 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
17616 return SDValue();
17618 // What vector are we extracting the subvector from and at what index?
17619 SDValue ExtVec = Op.getOperand(0);
17621 // We want the EVT of the original extraction to correctly scale the
17622 // extraction index.
17623 EVT ExtVT = ExtVec.getValueType();
17624 ExtVec = peekThroughBitcasts(ExtVec);
17626 // UNDEF nodes convert to UNDEF shuffle mask values.
17627 if (ExtVec.isUndef()) {
17628 Mask.append((unsigned)NumOpElts, -1);
17629 continue;
17632 if (!isa<ConstantSDNode>(Op.getOperand(1)))
17633 return SDValue();
17634 int ExtIdx = Op.getConstantOperandVal(1);
17636 // Ensure that we are extracting a subvector from a vector the same
17637 // size as the result.
17638 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
17639 return SDValue();
17641 // Scale the subvector index to account for any bitcast.
17642 int NumExtElts = ExtVT.getVectorNumElements();
17643 if (0 == (NumExtElts % NumElts))
17644 ExtIdx /= (NumExtElts / NumElts);
17645 else if (0 == (NumElts % NumExtElts))
17646 ExtIdx *= (NumElts / NumExtElts);
17647 else
17648 return SDValue();
17650 // At most we can reference 2 inputs in the final shuffle.
17651 if (SV0.isUndef() || SV0 == ExtVec) {
17652 SV0 = ExtVec;
17653 for (int i = 0; i != NumOpElts; ++i)
17654 Mask.push_back(i + ExtIdx);
17655 } else if (SV1.isUndef() || SV1 == ExtVec) {
17656 SV1 = ExtVec;
17657 for (int i = 0; i != NumOpElts; ++i)
17658 Mask.push_back(i + ExtIdx + NumElts);
17659 } else {
17660 return SDValue();
17664 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
17665 return SDValue();
17667 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
17668 DAG.getBitcast(VT, SV1), Mask);
17671 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
17672 // If we only have one input vector, we don't need to do any concatenation.
17673 if (N->getNumOperands() == 1)
17674 return N->getOperand(0);
17676 // Check if all of the operands are undefs.
17677 EVT VT = N->getValueType(0);
17678 if (ISD::allOperandsUndef(N))
17679 return DAG.getUNDEF(VT);
17681 // Optimize concat_vectors where all but the first of the vectors are undef.
17682 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
17683 return Op.isUndef();
17684 })) {
17685 SDValue In = N->getOperand(0);
17686 assert(In.getValueType().isVector() && "Must concat vectors");
17688 // If the input is a concat_vectors, just make a larger concat by padding
17689 // with smaller undefs.
17690 if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) {
17691 unsigned NumOps = N->getNumOperands() * In.getNumOperands();
17692 SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end());
17693 Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType()));
17694 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
17697 SDValue Scalar = peekThroughOneUseBitcasts(In);
17699 // concat_vectors(scalar_to_vector(scalar), undef) ->
17700 // scalar_to_vector(scalar)
17701 if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR &&
17702 Scalar.hasOneUse()) {
17703 EVT SVT = Scalar.getValueType().getVectorElementType();
17704 if (SVT == Scalar.getOperand(0).getValueType())
17705 Scalar = Scalar.getOperand(0);
17708 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
17709 if (!Scalar.getValueType().isVector()) {
17710 // If the bitcast type isn't legal, it might be a trunc of a legal type;
17711 // look through the trunc so we can still do the transform:
17712 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
17713 if (Scalar->getOpcode() == ISD::TRUNCATE &&
17714 !TLI.isTypeLegal(Scalar.getValueType()) &&
17715 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
17716 Scalar = Scalar->getOperand(0);
17718 EVT SclTy = Scalar.getValueType();
17720 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
17721 return SDValue();
17723 // Bail out if the vector size is not a multiple of the scalar size.
17724 if (VT.getSizeInBits() % SclTy.getSizeInBits())
17725 return SDValue();
17727 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
17728 if (VNTNumElms < 2)
17729 return SDValue();
17731 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
17732 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
17733 return SDValue();
17735 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
17736 return DAG.getBitcast(VT, Res);
17740 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
17741 // We have already tested above for an UNDEF only concatenation.
17742 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
17743 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
17744 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
17745 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
17747 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
17748 SmallVector<SDValue, 8> Opnds;
17749 EVT SVT = VT.getScalarType();
17751 EVT MinVT = SVT;
17752 if (!SVT.isFloatingPoint()) {
17753 // If BUILD_VECTOR are from built from integer, they may have different
17754 // operand types. Get the smallest type and truncate all operands to it.
17755 bool FoundMinVT = false;
17756 for (const SDValue &Op : N->ops())
17757 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
17758 EVT OpSVT = Op.getOperand(0).getValueType();
17759 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
17760 FoundMinVT = true;
17762 assert(FoundMinVT && "Concat vector type mismatch");
17765 for (const SDValue &Op : N->ops()) {
17766 EVT OpVT = Op.getValueType();
17767 unsigned NumElts = OpVT.getVectorNumElements();
17769 if (ISD::UNDEF == Op.getOpcode())
17770 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
17772 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
17773 if (SVT.isFloatingPoint()) {
17774 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
17775 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
17776 } else {
17777 for (unsigned i = 0; i != NumElts; ++i)
17778 Opnds.push_back(
17779 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
17784 assert(VT.getVectorNumElements() == Opnds.size() &&
17785 "Concat vector type mismatch");
17786 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
17789 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
17790 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
17791 return V;
17793 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
17794 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
17795 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
17796 return V;
17798 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
17799 // nodes often generate nop CONCAT_VECTOR nodes.
17800 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
17801 // place the incoming vectors at the exact same location.
17802 SDValue SingleSource = SDValue();
17803 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
17805 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
17806 SDValue Op = N->getOperand(i);
17808 if (Op.isUndef())
17809 continue;
17811 // Check if this is the identity extract:
17812 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
17813 return SDValue();
17815 // Find the single incoming vector for the extract_subvector.
17816 if (SingleSource.getNode()) {
17817 if (Op.getOperand(0) != SingleSource)
17818 return SDValue();
17819 } else {
17820 SingleSource = Op.getOperand(0);
17822 // Check the source type is the same as the type of the result.
17823 // If not, this concat may extend the vector, so we can not
17824 // optimize it away.
17825 if (SingleSource.getValueType() != N->getValueType(0))
17826 return SDValue();
17829 auto *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17830 // The extract index must be constant.
17831 if (!CS)
17832 return SDValue();
17834 // Check that we are reading from the identity index.
17835 unsigned IdentityIndex = i * PartNumElem;
17836 if (CS->getAPIntValue() != IdentityIndex)
17837 return SDValue();
17840 if (SingleSource.getNode())
17841 return SingleSource;
17843 return SDValue();
17846 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
17847 // if the subvector can be sourced for free.
17848 static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) {
17849 if (V.getOpcode() == ISD::INSERT_SUBVECTOR &&
17850 V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) {
17851 return V.getOperand(1);
17853 auto *IndexC = dyn_cast<ConstantSDNode>(Index);
17854 if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS &&
17855 V.getOperand(0).getValueType() == SubVT &&
17856 (IndexC->getZExtValue() % SubVT.getVectorNumElements()) == 0) {
17857 uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorNumElements();
17858 return V.getOperand(SubIdx);
17860 return SDValue();
17863 static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract,
17864 SelectionDAG &DAG) {
17865 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17866 SDValue BinOp = Extract->getOperand(0);
17867 unsigned BinOpcode = BinOp.getOpcode();
17868 if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1)
17869 return SDValue();
17871 EVT VecVT = BinOp.getValueType();
17872 SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1);
17873 if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType())
17874 return SDValue();
17876 SDValue Index = Extract->getOperand(1);
17877 EVT SubVT = Extract->getValueType(0);
17878 if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT))
17879 return SDValue();
17881 SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT);
17882 SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT);
17884 // TODO: We could handle the case where only 1 operand is being inserted by
17885 // creating an extract of the other operand, but that requires checking
17886 // number of uses and/or costs.
17887 if (!Sub0 || !Sub1)
17888 return SDValue();
17890 // We are inserting both operands of the wide binop only to extract back
17891 // to the narrow vector size. Eliminate all of the insert/extract:
17892 // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
17893 return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1,
17894 BinOp->getFlags());
17897 /// If we are extracting a subvector produced by a wide binary operator try
17898 /// to use a narrow binary operator and/or avoid concatenation and extraction.
17899 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
17900 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
17901 // some of these bailouts with other transforms.
17903 if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG))
17904 return V;
17906 // The extract index must be a constant, so we can map it to a concat operand.
17907 auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
17908 if (!ExtractIndexC)
17909 return SDValue();
17911 // We are looking for an optionally bitcasted wide vector binary operator
17912 // feeding an extract subvector.
17913 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17914 SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0));
17915 unsigned BOpcode = BinOp.getOpcode();
17916 if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1)
17917 return SDValue();
17919 // The binop must be a vector type, so we can extract some fraction of it.
17920 EVT WideBVT = BinOp.getValueType();
17921 if (!WideBVT.isVector())
17922 return SDValue();
17924 EVT VT = Extract->getValueType(0);
17925 unsigned ExtractIndex = ExtractIndexC->getZExtValue();
17926 assert(ExtractIndex % VT.getVectorNumElements() == 0 &&
17927 "Extract index is not a multiple of the vector length.");
17929 // Bail out if this is not a proper multiple width extraction.
17930 unsigned WideWidth = WideBVT.getSizeInBits();
17931 unsigned NarrowWidth = VT.getSizeInBits();
17932 if (WideWidth % NarrowWidth != 0)
17933 return SDValue();
17935 // Bail out if we are extracting a fraction of a single operation. This can
17936 // occur because we potentially looked through a bitcast of the binop.
17937 unsigned NarrowingRatio = WideWidth / NarrowWidth;
17938 unsigned WideNumElts = WideBVT.getVectorNumElements();
17939 if (WideNumElts % NarrowingRatio != 0)
17940 return SDValue();
17942 // Bail out if the target does not support a narrower version of the binop.
17943 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
17944 WideNumElts / NarrowingRatio);
17945 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
17946 return SDValue();
17948 // If extraction is cheap, we don't need to look at the binop operands
17949 // for concat ops. The narrow binop alone makes this transform profitable.
17950 // We can't just reuse the original extract index operand because we may have
17951 // bitcasted.
17952 unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements();
17953 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
17954 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
17955 if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) &&
17956 BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) {
17957 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
17958 SDLoc DL(Extract);
17959 SDValue NewExtIndex = DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT);
17960 SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
17961 BinOp.getOperand(0), NewExtIndex);
17962 SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
17963 BinOp.getOperand(1), NewExtIndex);
17964 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y,
17965 BinOp.getNode()->getFlags());
17966 return DAG.getBitcast(VT, NarrowBinOp);
17969 // Only handle the case where we are doubling and then halving. A larger ratio
17970 // may require more than two narrow binops to replace the wide binop.
17971 if (NarrowingRatio != 2)
17972 return SDValue();
17974 // TODO: The motivating case for this transform is an x86 AVX1 target. That
17975 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
17976 // flavors, but no other 256-bit integer support. This could be extended to
17977 // handle any binop, but that may require fixing/adding other folds to avoid
17978 // codegen regressions.
17979 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
17980 return SDValue();
17982 // We need at least one concatenation operation of a binop operand to make
17983 // this transform worthwhile. The concat must double the input vector sizes.
17984 auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue {
17985 if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2)
17986 return V.getOperand(ConcatOpNum);
17987 return SDValue();
17989 SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0)));
17990 SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1)));
17992 if (SubVecL || SubVecR) {
17993 // If a binop operand was not the result of a concat, we must extract a
17994 // half-sized operand for our new narrow binop:
17995 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
17996 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
17997 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
17998 SDLoc DL(Extract);
17999 SDValue IndexC = DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT);
18000 SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL)
18001 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18002 BinOp.getOperand(0), IndexC);
18004 SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR)
18005 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18006 BinOp.getOperand(1), IndexC);
18008 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
18009 return DAG.getBitcast(VT, NarrowBinOp);
18012 return SDValue();
18015 /// If we are extracting a subvector from a wide vector load, convert to a
18016 /// narrow load to eliminate the extraction:
18017 /// (extract_subvector (load wide vector)) --> (load narrow vector)
18018 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
18019 // TODO: Add support for big-endian. The offset calculation must be adjusted.
18020 if (DAG.getDataLayout().isBigEndian())
18021 return SDValue();
18023 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
18024 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
18025 if (!Ld || Ld->getExtensionType() || Ld->isVolatile() || !ExtIdx)
18026 return SDValue();
18028 // Allow targets to opt-out.
18029 EVT VT = Extract->getValueType(0);
18030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18031 if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT))
18032 return SDValue();
18034 // The narrow load will be offset from the base address of the old load if
18035 // we are extracting from something besides index 0 (little-endian).
18036 SDLoc DL(Extract);
18037 SDValue BaseAddr = Ld->getOperand(1);
18038 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
18040 // TODO: Use "BaseIndexOffset" to make this more effective.
18041 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
18042 MachineFunction &MF = DAG.getMachineFunction();
18043 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
18044 VT.getStoreSize());
18045 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
18046 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
18047 return NewLd;
18050 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) {
18051 EVT NVT = N->getValueType(0);
18052 SDValue V = N->getOperand(0);
18054 // Extract from UNDEF is UNDEF.
18055 if (V.isUndef())
18056 return DAG.getUNDEF(NVT);
18058 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
18059 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
18060 return NarrowLoad;
18062 // Combine an extract of an extract into a single extract_subvector.
18063 // ext (ext X, C), 0 --> ext X, C
18064 SDValue Index = N->getOperand(1);
18065 if (isNullConstant(Index) && V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
18066 V.hasOneUse() && isa<ConstantSDNode>(V.getOperand(1))) {
18067 if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(),
18068 V.getConstantOperandVal(1)) &&
18069 TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) {
18070 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0),
18071 V.getOperand(1));
18075 // Try to move vector bitcast after extract_subv by scaling extraction index:
18076 // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
18077 if (isa<ConstantSDNode>(Index) && V.getOpcode() == ISD::BITCAST &&
18078 V.getOperand(0).getValueType().isVector()) {
18079 SDValue SrcOp = V.getOperand(0);
18080 EVT SrcVT = SrcOp.getValueType();
18081 unsigned SrcNumElts = SrcVT.getVectorNumElements();
18082 unsigned DestNumElts = V.getValueType().getVectorNumElements();
18083 if ((SrcNumElts % DestNumElts) == 0) {
18084 unsigned SrcDestRatio = SrcNumElts / DestNumElts;
18085 unsigned NewExtNumElts = NVT.getVectorNumElements() * SrcDestRatio;
18086 EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
18087 NewExtNumElts);
18088 if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
18089 unsigned IndexValScaled = N->getConstantOperandVal(1) * SrcDestRatio;
18090 SDLoc DL(N);
18091 SDValue NewIndex = DAG.getIntPtrConstant(IndexValScaled, DL);
18092 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
18093 V.getOperand(0), NewIndex);
18094 return DAG.getBitcast(NVT, NewExtract);
18097 // TODO - handle (DestNumElts % SrcNumElts) == 0
18100 // Combine:
18101 // (extract_subvec (concat V1, V2, ...), i)
18102 // Into:
18103 // Vi if possible
18104 // Only operand 0 is checked as 'concat' assumes all inputs of the same
18105 // type.
18106 if (V.getOpcode() == ISD::CONCAT_VECTORS && isa<ConstantSDNode>(Index) &&
18107 V.getOperand(0).getValueType() == NVT) {
18108 unsigned Idx = N->getConstantOperandVal(1);
18109 unsigned NumElems = NVT.getVectorNumElements();
18110 assert((Idx % NumElems) == 0 &&
18111 "IDX in concat is not a multiple of the result vector length.");
18112 return V->getOperand(Idx / NumElems);
18115 V = peekThroughBitcasts(V);
18117 // If the input is a build vector. Try to make a smaller build vector.
18118 if (V.getOpcode() == ISD::BUILD_VECTOR) {
18119 if (auto *IdxC = dyn_cast<ConstantSDNode>(Index)) {
18120 EVT InVT = V.getValueType();
18121 unsigned ExtractSize = NVT.getSizeInBits();
18122 unsigned EltSize = InVT.getScalarSizeInBits();
18123 // Only do this if we won't split any elements.
18124 if (ExtractSize % EltSize == 0) {
18125 unsigned NumElems = ExtractSize / EltSize;
18126 EVT EltVT = InVT.getVectorElementType();
18127 EVT ExtractVT = NumElems == 1 ? EltVT
18128 : EVT::getVectorVT(*DAG.getContext(),
18129 EltVT, NumElems);
18130 if ((Level < AfterLegalizeDAG ||
18131 (NumElems == 1 ||
18132 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) &&
18133 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
18134 unsigned IdxVal = IdxC->getZExtValue();
18135 IdxVal *= NVT.getScalarSizeInBits();
18136 IdxVal /= EltSize;
18138 if (NumElems == 1) {
18139 SDValue Src = V->getOperand(IdxVal);
18140 if (EltVT != Src.getValueType())
18141 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src);
18142 return DAG.getBitcast(NVT, Src);
18145 // Extract the pieces from the original build_vector.
18146 SDValue BuildVec = DAG.getBuildVector(
18147 ExtractVT, SDLoc(N), V->ops().slice(IdxVal, NumElems));
18148 return DAG.getBitcast(NVT, BuildVec);
18154 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
18155 // Handle only simple case where vector being inserted and vector
18156 // being extracted are of same size.
18157 EVT SmallVT = V.getOperand(1).getValueType();
18158 if (!NVT.bitsEq(SmallVT))
18159 return SDValue();
18161 // Only handle cases where both indexes are constants.
18162 auto *ExtIdx = dyn_cast<ConstantSDNode>(Index);
18163 auto *InsIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
18164 if (InsIdx && ExtIdx) {
18165 // Combine:
18166 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
18167 // Into:
18168 // indices are equal or bit offsets are equal => V1
18169 // otherwise => (extract_subvec V1, ExtIdx)
18170 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
18171 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
18172 return DAG.getBitcast(NVT, V.getOperand(1));
18173 return DAG.getNode(
18174 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
18175 DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)),
18176 Index);
18180 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
18181 return NarrowBOp;
18183 if (SimplifyDemandedVectorElts(SDValue(N, 0)))
18184 return SDValue(N, 0);
18186 return SDValue();
18189 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
18190 /// followed by concatenation. Narrow vector ops may have better performance
18191 /// than wide ops, and this can unlock further narrowing of other vector ops.
18192 /// Targets can invert this transform later if it is not profitable.
18193 static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf,
18194 SelectionDAG &DAG) {
18195 SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1);
18196 if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
18197 N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 ||
18198 !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef())
18199 return SDValue();
18201 // Split the wide shuffle mask into halves. Any mask element that is accessing
18202 // operand 1 is offset down to account for narrowing of the vectors.
18203 ArrayRef<int> Mask = Shuf->getMask();
18204 EVT VT = Shuf->getValueType(0);
18205 unsigned NumElts = VT.getVectorNumElements();
18206 unsigned HalfNumElts = NumElts / 2;
18207 SmallVector<int, 16> Mask0(HalfNumElts, -1);
18208 SmallVector<int, 16> Mask1(HalfNumElts, -1);
18209 for (unsigned i = 0; i != NumElts; ++i) {
18210 if (Mask[i] == -1)
18211 continue;
18212 int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts;
18213 if (i < HalfNumElts)
18214 Mask0[i] = M;
18215 else
18216 Mask1[i - HalfNumElts] = M;
18219 // Ask the target if this is a valid transform.
18220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18221 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
18222 HalfNumElts);
18223 if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) ||
18224 !TLI.isShuffleMaskLegal(Mask1, HalfVT))
18225 return SDValue();
18227 // shuffle (concat X, undef), (concat Y, undef), Mask -->
18228 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
18229 SDValue X = N0.getOperand(0), Y = N1.getOperand(0);
18230 SDLoc DL(Shuf);
18231 SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0);
18232 SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1);
18233 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1);
18236 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
18237 // or turn a shuffle of a single concat into simpler shuffle then concat.
18238 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
18239 EVT VT = N->getValueType(0);
18240 unsigned NumElts = VT.getVectorNumElements();
18242 SDValue N0 = N->getOperand(0);
18243 SDValue N1 = N->getOperand(1);
18244 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
18245 ArrayRef<int> Mask = SVN->getMask();
18247 SmallVector<SDValue, 4> Ops;
18248 EVT ConcatVT = N0.getOperand(0).getValueType();
18249 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
18250 unsigned NumConcats = NumElts / NumElemsPerConcat;
18252 auto IsUndefMaskElt = [](int i) { return i == -1; };
18254 // Special case: shuffle(concat(A,B)) can be more efficiently represented
18255 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
18256 // half vector elements.
18257 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
18258 llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat),
18259 IsUndefMaskElt)) {
18260 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0),
18261 N0.getOperand(1),
18262 Mask.slice(0, NumElemsPerConcat));
18263 N1 = DAG.getUNDEF(ConcatVT);
18264 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
18267 // Look at every vector that's inserted. We're looking for exact
18268 // subvector-sized copies from a concatenated vector
18269 for (unsigned I = 0; I != NumConcats; ++I) {
18270 unsigned Begin = I * NumElemsPerConcat;
18271 ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat);
18273 // Make sure we're dealing with a copy.
18274 if (llvm::all_of(SubMask, IsUndefMaskElt)) {
18275 Ops.push_back(DAG.getUNDEF(ConcatVT));
18276 continue;
18279 int OpIdx = -1;
18280 for (int i = 0; i != (int)NumElemsPerConcat; ++i) {
18281 if (IsUndefMaskElt(SubMask[i]))
18282 continue;
18283 if ((SubMask[i] % (int)NumElemsPerConcat) != i)
18284 return SDValue();
18285 int EltOpIdx = SubMask[i] / NumElemsPerConcat;
18286 if (0 <= OpIdx && EltOpIdx != OpIdx)
18287 return SDValue();
18288 OpIdx = EltOpIdx;
18290 assert(0 <= OpIdx && "Unknown concat_vectors op");
18292 if (OpIdx < (int)N0.getNumOperands())
18293 Ops.push_back(N0.getOperand(OpIdx));
18294 else
18295 Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands()));
18298 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
18301 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
18302 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
18304 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
18305 // a simplification in some sense, but it isn't appropriate in general: some
18306 // BUILD_VECTORs are substantially cheaper than others. The general case
18307 // of a BUILD_VECTOR requires inserting each element individually (or
18308 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
18309 // all constants is a single constant pool load. A BUILD_VECTOR where each
18310 // element is identical is a splat. A BUILD_VECTOR where most of the operands
18311 // are undef lowers to a small number of element insertions.
18313 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
18314 // We don't fold shuffles where one side is a non-zero constant, and we don't
18315 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
18316 // non-constant operands. This seems to work out reasonably well in practice.
18317 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
18318 SelectionDAG &DAG,
18319 const TargetLowering &TLI) {
18320 EVT VT = SVN->getValueType(0);
18321 unsigned NumElts = VT.getVectorNumElements();
18322 SDValue N0 = SVN->getOperand(0);
18323 SDValue N1 = SVN->getOperand(1);
18325 if (!N0->hasOneUse())
18326 return SDValue();
18328 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
18329 // discussed above.
18330 if (!N1.isUndef()) {
18331 if (!N1->hasOneUse())
18332 return SDValue();
18334 bool N0AnyConst = isAnyConstantBuildVector(N0);
18335 bool N1AnyConst = isAnyConstantBuildVector(N1);
18336 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
18337 return SDValue();
18338 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
18339 return SDValue();
18342 // If both inputs are splats of the same value then we can safely merge this
18343 // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
18344 bool IsSplat = false;
18345 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
18346 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
18347 if (BV0 && BV1)
18348 if (SDValue Splat0 = BV0->getSplatValue())
18349 IsSplat = (Splat0 == BV1->getSplatValue());
18351 SmallVector<SDValue, 8> Ops;
18352 SmallSet<SDValue, 16> DuplicateOps;
18353 for (int M : SVN->getMask()) {
18354 SDValue Op = DAG.getUNDEF(VT.getScalarType());
18355 if (M >= 0) {
18356 int Idx = M < (int)NumElts ? M : M - NumElts;
18357 SDValue &S = (M < (int)NumElts ? N0 : N1);
18358 if (S.getOpcode() == ISD::BUILD_VECTOR) {
18359 Op = S.getOperand(Idx);
18360 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
18361 SDValue Op0 = S.getOperand(0);
18362 Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType());
18363 } else {
18364 // Operand can't be combined - bail out.
18365 return SDValue();
18369 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
18370 // generating a splat; semantically, this is fine, but it's likely to
18371 // generate low-quality code if the target can't reconstruct an appropriate
18372 // shuffle.
18373 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
18374 if (!IsSplat && !DuplicateOps.insert(Op).second)
18375 return SDValue();
18377 Ops.push_back(Op);
18380 // BUILD_VECTOR requires all inputs to be of the same type, find the
18381 // maximum type and extend them all.
18382 EVT SVT = VT.getScalarType();
18383 if (SVT.isInteger())
18384 for (SDValue &Op : Ops)
18385 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
18386 if (SVT != VT.getScalarType())
18387 for (SDValue &Op : Ops)
18388 Op = TLI.isZExtFree(Op.getValueType(), SVT)
18389 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
18390 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
18391 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
18394 // Match shuffles that can be converted to any_vector_extend_in_reg.
18395 // This is often generated during legalization.
18396 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
18397 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
18398 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
18399 SelectionDAG &DAG,
18400 const TargetLowering &TLI,
18401 bool LegalOperations) {
18402 EVT VT = SVN->getValueType(0);
18403 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
18405 // TODO Add support for big-endian when we have a test case.
18406 if (!VT.isInteger() || IsBigEndian)
18407 return SDValue();
18409 unsigned NumElts = VT.getVectorNumElements();
18410 unsigned EltSizeInBits = VT.getScalarSizeInBits();
18411 ArrayRef<int> Mask = SVN->getMask();
18412 SDValue N0 = SVN->getOperand(0);
18414 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
18415 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
18416 for (unsigned i = 0; i != NumElts; ++i) {
18417 if (Mask[i] < 0)
18418 continue;
18419 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
18420 continue;
18421 return false;
18423 return true;
18426 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
18427 // power-of-2 extensions as they are the most likely.
18428 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
18429 // Check for non power of 2 vector sizes
18430 if (NumElts % Scale != 0)
18431 continue;
18432 if (!isAnyExtend(Scale))
18433 continue;
18435 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
18436 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
18437 // Never create an illegal type. Only create unsupported operations if we
18438 // are pre-legalization.
18439 if (TLI.isTypeLegal(OutVT))
18440 if (!LegalOperations ||
18441 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
18442 return DAG.getBitcast(VT,
18443 DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG,
18444 SDLoc(SVN), OutVT, N0));
18447 return SDValue();
18450 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
18451 // each source element of a large type into the lowest elements of a smaller
18452 // destination type. This is often generated during legalization.
18453 // If the source node itself was a '*_extend_vector_inreg' node then we should
18454 // then be able to remove it.
18455 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
18456 SelectionDAG &DAG) {
18457 EVT VT = SVN->getValueType(0);
18458 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
18460 // TODO Add support for big-endian when we have a test case.
18461 if (!VT.isInteger() || IsBigEndian)
18462 return SDValue();
18464 SDValue N0 = peekThroughBitcasts(SVN->getOperand(0));
18466 unsigned Opcode = N0.getOpcode();
18467 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
18468 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
18469 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
18470 return SDValue();
18472 SDValue N00 = N0.getOperand(0);
18473 ArrayRef<int> Mask = SVN->getMask();
18474 unsigned NumElts = VT.getVectorNumElements();
18475 unsigned EltSizeInBits = VT.getScalarSizeInBits();
18476 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
18477 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
18479 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
18480 return SDValue();
18481 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
18483 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
18484 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
18485 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
18486 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
18487 for (unsigned i = 0; i != NumElts; ++i) {
18488 if (Mask[i] < 0)
18489 continue;
18490 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
18491 continue;
18492 return false;
18494 return true;
18497 // At the moment we just handle the case where we've truncated back to the
18498 // same size as before the extension.
18499 // TODO: handle more extension/truncation cases as cases arise.
18500 if (EltSizeInBits != ExtSrcSizeInBits)
18501 return SDValue();
18503 // We can remove *extend_vector_inreg only if the truncation happens at
18504 // the same scale as the extension.
18505 if (isTruncate(ExtScale))
18506 return DAG.getBitcast(VT, N00);
18508 return SDValue();
18511 // Combine shuffles of splat-shuffles of the form:
18512 // shuffle (shuffle V, undef, splat-mask), undef, M
18513 // If splat-mask contains undef elements, we need to be careful about
18514 // introducing undef's in the folded mask which are not the result of composing
18515 // the masks of the shuffles.
18516 static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf,
18517 SelectionDAG &DAG) {
18518 if (!Shuf->getOperand(1).isUndef())
18519 return SDValue();
18520 auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
18521 if (!Splat || !Splat->isSplat())
18522 return SDValue();
18524 ArrayRef<int> ShufMask = Shuf->getMask();
18525 ArrayRef<int> SplatMask = Splat->getMask();
18526 assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch");
18528 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
18529 // every undef mask element in the splat-shuffle has a corresponding undef
18530 // element in the user-shuffle's mask or if the composition of mask elements
18531 // would result in undef.
18532 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
18533 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
18534 // In this case it is not legal to simplify to the splat-shuffle because we
18535 // may be exposing the users of the shuffle an undef element at index 1
18536 // which was not there before the combine.
18537 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
18538 // In this case the composition of masks yields SplatMask, so it's ok to
18539 // simplify to the splat-shuffle.
18540 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
18541 // In this case the composed mask includes all undef elements of SplatMask
18542 // and in addition sets element zero to undef. It is safe to simplify to
18543 // the splat-shuffle.
18544 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
18545 ArrayRef<int> SplatMask) {
18546 for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
18547 if (UserMask[i] != -1 && SplatMask[i] == -1 &&
18548 SplatMask[UserMask[i]] != -1)
18549 return false;
18550 return true;
18552 if (CanSimplifyToExistingSplat(ShufMask, SplatMask))
18553 return Shuf->getOperand(0);
18555 // Create a new shuffle with a mask that is composed of the two shuffles'
18556 // masks.
18557 SmallVector<int, 32> NewMask;
18558 for (int Idx : ShufMask)
18559 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
18561 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
18562 Splat->getOperand(0), Splat->getOperand(1),
18563 NewMask);
18566 /// If the shuffle mask is taking exactly one element from the first vector
18567 /// operand and passing through all other elements from the second vector
18568 /// operand, return the index of the mask element that is choosing an element
18569 /// from the first operand. Otherwise, return -1.
18570 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
18571 int MaskSize = Mask.size();
18572 int EltFromOp0 = -1;
18573 // TODO: This does not match if there are undef elements in the shuffle mask.
18574 // Should we ignore undefs in the shuffle mask instead? The trade-off is
18575 // removing an instruction (a shuffle), but losing the knowledge that some
18576 // vector lanes are not needed.
18577 for (int i = 0; i != MaskSize; ++i) {
18578 if (Mask[i] >= 0 && Mask[i] < MaskSize) {
18579 // We're looking for a shuffle of exactly one element from operand 0.
18580 if (EltFromOp0 != -1)
18581 return -1;
18582 EltFromOp0 = i;
18583 } else if (Mask[i] != i + MaskSize) {
18584 // Nothing from operand 1 can change lanes.
18585 return -1;
18588 return EltFromOp0;
18591 /// If a shuffle inserts exactly one element from a source vector operand into
18592 /// another vector operand and we can access the specified element as a scalar,
18593 /// then we can eliminate the shuffle.
18594 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
18595 SelectionDAG &DAG) {
18596 // First, check if we are taking one element of a vector and shuffling that
18597 // element into another vector.
18598 ArrayRef<int> Mask = Shuf->getMask();
18599 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
18600 SDValue Op0 = Shuf->getOperand(0);
18601 SDValue Op1 = Shuf->getOperand(1);
18602 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
18603 if (ShufOp0Index == -1) {
18604 // Commute mask and check again.
18605 ShuffleVectorSDNode::commuteMask(CommutedMask);
18606 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
18607 if (ShufOp0Index == -1)
18608 return SDValue();
18609 // Commute operands to match the commuted shuffle mask.
18610 std::swap(Op0, Op1);
18611 Mask = CommutedMask;
18614 // The shuffle inserts exactly one element from operand 0 into operand 1.
18615 // Now see if we can access that element as a scalar via a real insert element
18616 // instruction.
18617 // TODO: We can try harder to locate the element as a scalar. Examples: it
18618 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
18619 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
18620 "Shuffle mask value must be from operand 0");
18621 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
18622 return SDValue();
18624 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
18625 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
18626 return SDValue();
18628 // There's an existing insertelement with constant insertion index, so we
18629 // don't need to check the legality/profitability of a replacement operation
18630 // that differs at most in the constant value. The target should be able to
18631 // lower any of those in a similar way. If not, legalization will expand this
18632 // to a scalar-to-vector plus shuffle.
18634 // Note that the shuffle may move the scalar from the position that the insert
18635 // element used. Therefore, our new insert element occurs at the shuffle's
18636 // mask index value, not the insert's index value.
18637 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
18638 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
18639 Op0.getOperand(2).getValueType());
18640 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
18641 Op1, Op0.getOperand(1), NewInsIndex);
18644 /// If we have a unary shuffle of a shuffle, see if it can be folded away
18645 /// completely. This has the potential to lose undef knowledge because the first
18646 /// shuffle may not have an undef mask element where the second one does. So
18647 /// only call this after doing simplifications based on demanded elements.
18648 static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) {
18649 // shuf (shuf0 X, Y, Mask0), undef, Mask
18650 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
18651 if (!Shuf0 || !Shuf->getOperand(1).isUndef())
18652 return SDValue();
18654 ArrayRef<int> Mask = Shuf->getMask();
18655 ArrayRef<int> Mask0 = Shuf0->getMask();
18656 for (int i = 0, e = (int)Mask.size(); i != e; ++i) {
18657 // Ignore undef elements.
18658 if (Mask[i] == -1)
18659 continue;
18660 assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value");
18662 // Is the element of the shuffle operand chosen by this shuffle the same as
18663 // the element chosen by the shuffle operand itself?
18664 if (Mask0[Mask[i]] != Mask0[i])
18665 return SDValue();
18667 // Every element of this shuffle is identical to the result of the previous
18668 // shuffle, so we can replace this value.
18669 return Shuf->getOperand(0);
18672 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
18673 EVT VT = N->getValueType(0);
18674 unsigned NumElts = VT.getVectorNumElements();
18676 SDValue N0 = N->getOperand(0);
18677 SDValue N1 = N->getOperand(1);
18679 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
18681 // Canonicalize shuffle undef, undef -> undef
18682 if (N0.isUndef() && N1.isUndef())
18683 return DAG.getUNDEF(VT);
18685 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
18687 // Canonicalize shuffle v, v -> v, undef
18688 if (N0 == N1) {
18689 SmallVector<int, 8> NewMask;
18690 for (unsigned i = 0; i != NumElts; ++i) {
18691 int Idx = SVN->getMaskElt(i);
18692 if (Idx >= (int)NumElts) Idx -= NumElts;
18693 NewMask.push_back(Idx);
18695 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
18698 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
18699 if (N0.isUndef())
18700 return DAG.getCommutedVectorShuffle(*SVN);
18702 // Remove references to rhs if it is undef
18703 if (N1.isUndef()) {
18704 bool Changed = false;
18705 SmallVector<int, 8> NewMask;
18706 for (unsigned i = 0; i != NumElts; ++i) {
18707 int Idx = SVN->getMaskElt(i);
18708 if (Idx >= (int)NumElts) {
18709 Idx = -1;
18710 Changed = true;
18712 NewMask.push_back(Idx);
18714 if (Changed)
18715 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
18718 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
18719 return InsElt;
18721 // A shuffle of a single vector that is a splatted value can always be folded.
18722 if (SDValue V = combineShuffleOfSplatVal(SVN, DAG))
18723 return V;
18725 // If it is a splat, check if the argument vector is another splat or a
18726 // build_vector.
18727 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
18728 int SplatIndex = SVN->getSplatIndex();
18729 if (TLI.isExtractVecEltCheap(VT, SplatIndex) &&
18730 TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) {
18731 // splat (vector_bo L, R), Index -->
18732 // splat (scalar_bo (extelt L, Index), (extelt R, Index))
18733 SDValue L = N0.getOperand(0), R = N0.getOperand(1);
18734 SDLoc DL(N);
18735 EVT EltVT = VT.getScalarType();
18736 SDValue Index = DAG.getIntPtrConstant(SplatIndex, DL);
18737 SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index);
18738 SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index);
18739 SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR,
18740 N0.getNode()->getFlags());
18741 SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO);
18742 SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0);
18743 return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask);
18746 // If this is a bit convert that changes the element type of the vector but
18747 // not the number of vector elements, look through it. Be careful not to
18748 // look though conversions that change things like v4f32 to v2f64.
18749 SDNode *V = N0.getNode();
18750 if (V->getOpcode() == ISD::BITCAST) {
18751 SDValue ConvInput = V->getOperand(0);
18752 if (ConvInput.getValueType().isVector() &&
18753 ConvInput.getValueType().getVectorNumElements() == NumElts)
18754 V = ConvInput.getNode();
18757 if (V->getOpcode() == ISD::BUILD_VECTOR) {
18758 assert(V->getNumOperands() == NumElts &&
18759 "BUILD_VECTOR has wrong number of operands");
18760 SDValue Base;
18761 bool AllSame = true;
18762 for (unsigned i = 0; i != NumElts; ++i) {
18763 if (!V->getOperand(i).isUndef()) {
18764 Base = V->getOperand(i);
18765 break;
18768 // Splat of <u, u, u, u>, return <u, u, u, u>
18769 if (!Base.getNode())
18770 return N0;
18771 for (unsigned i = 0; i != NumElts; ++i) {
18772 if (V->getOperand(i) != Base) {
18773 AllSame = false;
18774 break;
18777 // Splat of <x, x, x, x>, return <x, x, x, x>
18778 if (AllSame)
18779 return N0;
18781 // Canonicalize any other splat as a build_vector.
18782 SDValue Splatted = V->getOperand(SplatIndex);
18783 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
18784 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
18786 // We may have jumped through bitcasts, so the type of the
18787 // BUILD_VECTOR may not match the type of the shuffle.
18788 if (V->getValueType(0) != VT)
18789 NewBV = DAG.getBitcast(VT, NewBV);
18790 return NewBV;
18794 // Simplify source operands based on shuffle mask.
18795 if (SimplifyDemandedVectorElts(SDValue(N, 0)))
18796 return SDValue(N, 0);
18798 // This is intentionally placed after demanded elements simplification because
18799 // it could eliminate knowledge of undef elements created by this shuffle.
18800 if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN))
18801 return ShufOp;
18803 // Match shuffles that can be converted to any_vector_extend_in_reg.
18804 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
18805 return V;
18807 // Combine "truncate_vector_in_reg" style shuffles.
18808 if (SDValue V = combineTruncationShuffle(SVN, DAG))
18809 return V;
18811 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
18812 Level < AfterLegalizeVectorOps &&
18813 (N1.isUndef() ||
18814 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
18815 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
18816 if (SDValue V = partitionShuffleOfConcats(N, DAG))
18817 return V;
18820 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
18821 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
18822 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT))
18823 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
18824 return Res;
18826 // If this shuffle only has a single input that is a bitcasted shuffle,
18827 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
18828 // back to their original types.
18829 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
18830 N1.isUndef() && Level < AfterLegalizeVectorOps &&
18831 TLI.isTypeLegal(VT)) {
18832 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
18833 if (Scale == 1)
18834 return SmallVector<int, 8>(Mask.begin(), Mask.end());
18836 SmallVector<int, 8> NewMask;
18837 for (int M : Mask)
18838 for (int s = 0; s != Scale; ++s)
18839 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
18840 return NewMask;
18843 SDValue BC0 = peekThroughOneUseBitcasts(N0);
18844 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
18845 EVT SVT = VT.getScalarType();
18846 EVT InnerVT = BC0->getValueType(0);
18847 EVT InnerSVT = InnerVT.getScalarType();
18849 // Determine which shuffle works with the smaller scalar type.
18850 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
18851 EVT ScaleSVT = ScaleVT.getScalarType();
18853 if (TLI.isTypeLegal(ScaleVT) &&
18854 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
18855 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
18856 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
18857 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
18859 // Scale the shuffle masks to the smaller scalar type.
18860 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
18861 SmallVector<int, 8> InnerMask =
18862 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
18863 SmallVector<int, 8> OuterMask =
18864 ScaleShuffleMask(SVN->getMask(), OuterScale);
18866 // Merge the shuffle masks.
18867 SmallVector<int, 8> NewMask;
18868 for (int M : OuterMask)
18869 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
18871 // Test for shuffle mask legality over both commutations.
18872 SDValue SV0 = BC0->getOperand(0);
18873 SDValue SV1 = BC0->getOperand(1);
18874 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
18875 if (!LegalMask) {
18876 std::swap(SV0, SV1);
18877 ShuffleVectorSDNode::commuteMask(NewMask);
18878 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
18881 if (LegalMask) {
18882 SV0 = DAG.getBitcast(ScaleVT, SV0);
18883 SV1 = DAG.getBitcast(ScaleVT, SV1);
18884 return DAG.getBitcast(
18885 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
18891 // Canonicalize shuffles according to rules:
18892 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
18893 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
18894 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
18895 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
18896 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
18897 TLI.isTypeLegal(VT)) {
18898 // The incoming shuffle must be of the same type as the result of the
18899 // current shuffle.
18900 assert(N1->getOperand(0).getValueType() == VT &&
18901 "Shuffle types don't match");
18903 SDValue SV0 = N1->getOperand(0);
18904 SDValue SV1 = N1->getOperand(1);
18905 bool HasSameOp0 = N0 == SV0;
18906 bool IsSV1Undef = SV1.isUndef();
18907 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
18908 // Commute the operands of this shuffle so that next rule
18909 // will trigger.
18910 return DAG.getCommutedVectorShuffle(*SVN);
18913 // Try to fold according to rules:
18914 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
18915 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
18916 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
18917 // Don't try to fold shuffles with illegal type.
18918 // Only fold if this shuffle is the only user of the other shuffle.
18919 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
18920 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
18921 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
18923 // Don't try to fold splats; they're likely to simplify somehow, or they
18924 // might be free.
18925 if (OtherSV->isSplat())
18926 return SDValue();
18928 // The incoming shuffle must be of the same type as the result of the
18929 // current shuffle.
18930 assert(OtherSV->getOperand(0).getValueType() == VT &&
18931 "Shuffle types don't match");
18933 SDValue SV0, SV1;
18934 SmallVector<int, 4> Mask;
18935 // Compute the combined shuffle mask for a shuffle with SV0 as the first
18936 // operand, and SV1 as the second operand.
18937 for (unsigned i = 0; i != NumElts; ++i) {
18938 int Idx = SVN->getMaskElt(i);
18939 if (Idx < 0) {
18940 // Propagate Undef.
18941 Mask.push_back(Idx);
18942 continue;
18945 SDValue CurrentVec;
18946 if (Idx < (int)NumElts) {
18947 // This shuffle index refers to the inner shuffle N0. Lookup the inner
18948 // shuffle mask to identify which vector is actually referenced.
18949 Idx = OtherSV->getMaskElt(Idx);
18950 if (Idx < 0) {
18951 // Propagate Undef.
18952 Mask.push_back(Idx);
18953 continue;
18956 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
18957 : OtherSV->getOperand(1);
18958 } else {
18959 // This shuffle index references an element within N1.
18960 CurrentVec = N1;
18963 // Simple case where 'CurrentVec' is UNDEF.
18964 if (CurrentVec.isUndef()) {
18965 Mask.push_back(-1);
18966 continue;
18969 // Canonicalize the shuffle index. We don't know yet if CurrentVec
18970 // will be the first or second operand of the combined shuffle.
18971 Idx = Idx % NumElts;
18972 if (!SV0.getNode() || SV0 == CurrentVec) {
18973 // Ok. CurrentVec is the left hand side.
18974 // Update the mask accordingly.
18975 SV0 = CurrentVec;
18976 Mask.push_back(Idx);
18977 continue;
18980 // Bail out if we cannot convert the shuffle pair into a single shuffle.
18981 if (SV1.getNode() && SV1 != CurrentVec)
18982 return SDValue();
18984 // Ok. CurrentVec is the right hand side.
18985 // Update the mask accordingly.
18986 SV1 = CurrentVec;
18987 Mask.push_back(Idx + NumElts);
18990 // Check if all indices in Mask are Undef. In case, propagate Undef.
18991 bool isUndefMask = true;
18992 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
18993 isUndefMask &= Mask[i] < 0;
18995 if (isUndefMask)
18996 return DAG.getUNDEF(VT);
18998 if (!SV0.getNode())
18999 SV0 = DAG.getUNDEF(VT);
19000 if (!SV1.getNode())
19001 SV1 = DAG.getUNDEF(VT);
19003 // Avoid introducing shuffles with illegal mask.
19004 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
19005 ShuffleVectorSDNode::commuteMask(Mask);
19007 if (!TLI.isShuffleMaskLegal(Mask, VT))
19008 return SDValue();
19010 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
19011 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
19012 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
19013 std::swap(SV0, SV1);
19016 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
19017 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
19018 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
19019 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
19022 if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG))
19023 return V;
19025 return SDValue();
19028 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
19029 SDValue InVal = N->getOperand(0);
19030 EVT VT = N->getValueType(0);
19032 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
19033 // with a VECTOR_SHUFFLE and possible truncate.
19034 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
19035 SDValue InVec = InVal->getOperand(0);
19036 SDValue EltNo = InVal->getOperand(1);
19037 auto InVecT = InVec.getValueType();
19038 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
19039 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
19040 int Elt = C0->getZExtValue();
19041 NewMask[0] = Elt;
19042 SDValue Val;
19043 // If we have an implict truncate do truncate here as long as it's legal.
19044 // if it's not legal, this should
19045 if (VT.getScalarType() != InVal.getValueType() &&
19046 InVal.getValueType().isScalarInteger() &&
19047 isTypeLegal(VT.getScalarType())) {
19048 Val =
19049 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
19050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
19052 if (VT.getScalarType() == InVecT.getScalarType() &&
19053 VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
19054 TLI.isShuffleMaskLegal(NewMask, VT)) {
19055 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
19056 DAG.getUNDEF(InVecT), NewMask);
19057 // If the initial vector is the correct size this shuffle is a
19058 // valid result.
19059 if (VT == InVecT)
19060 return Val;
19061 // If not we must truncate the vector.
19062 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
19063 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
19064 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
19065 EVT SubVT =
19066 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
19067 VT.getVectorNumElements());
19068 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
19069 ZeroIdx);
19070 return Val;
19076 return SDValue();
19079 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
19080 EVT VT = N->getValueType(0);
19081 SDValue N0 = N->getOperand(0);
19082 SDValue N1 = N->getOperand(1);
19083 SDValue N2 = N->getOperand(2);
19085 // If inserting an UNDEF, just return the original vector.
19086 if (N1.isUndef())
19087 return N0;
19089 // If this is an insert of an extracted vector into an undef vector, we can
19090 // just use the input to the extract.
19091 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
19092 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
19093 return N1.getOperand(0);
19095 // If we are inserting a bitcast value into an undef, with the same
19096 // number of elements, just use the bitcast input of the extract.
19097 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
19098 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
19099 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
19100 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
19101 N1.getOperand(0).getOperand(1) == N2 &&
19102 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
19103 VT.getVectorNumElements() &&
19104 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
19105 VT.getSizeInBits()) {
19106 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
19109 // If both N1 and N2 are bitcast values on which insert_subvector
19110 // would makes sense, pull the bitcast through.
19111 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
19112 // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
19113 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
19114 SDValue CN0 = N0.getOperand(0);
19115 SDValue CN1 = N1.getOperand(0);
19116 EVT CN0VT = CN0.getValueType();
19117 EVT CN1VT = CN1.getValueType();
19118 if (CN0VT.isVector() && CN1VT.isVector() &&
19119 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
19120 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) {
19121 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
19122 CN0.getValueType(), CN0, CN1, N2);
19123 return DAG.getBitcast(VT, NewINSERT);
19127 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
19128 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
19129 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
19130 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
19131 N0.getOperand(1).getValueType() == N1.getValueType() &&
19132 N0.getOperand(2) == N2)
19133 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
19134 N1, N2);
19136 // Eliminate an intermediate insert into an undef vector:
19137 // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
19138 // insert_subvector undef, X, N2
19139 if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19140 N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2)))
19141 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0,
19142 N1.getOperand(1), N2);
19144 if (!isa<ConstantSDNode>(N2))
19145 return SDValue();
19147 uint64_t InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
19149 // Push subvector bitcasts to the output, adjusting the index as we go.
19150 // insert_subvector(bitcast(v), bitcast(s), c1)
19151 // -> bitcast(insert_subvector(v, s, c2))
19152 if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) &&
19153 N1.getOpcode() == ISD::BITCAST) {
19154 SDValue N0Src = peekThroughBitcasts(N0);
19155 SDValue N1Src = peekThroughBitcasts(N1);
19156 EVT N0SrcSVT = N0Src.getValueType().getScalarType();
19157 EVT N1SrcSVT = N1Src.getValueType().getScalarType();
19158 if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) &&
19159 N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) {
19160 EVT NewVT;
19161 SDLoc DL(N);
19162 SDValue NewIdx;
19163 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
19164 LLVMContext &Ctx = *DAG.getContext();
19165 unsigned NumElts = VT.getVectorNumElements();
19166 unsigned EltSizeInBits = VT.getScalarSizeInBits();
19167 if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) {
19168 unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits();
19169 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale);
19170 NewIdx = DAG.getConstant(InsIdx * Scale, DL, IdxVT);
19171 } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) {
19172 unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits;
19173 if ((NumElts % Scale) == 0 && (InsIdx % Scale) == 0) {
19174 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts / Scale);
19175 NewIdx = DAG.getConstant(InsIdx / Scale, DL, IdxVT);
19178 if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) {
19179 SDValue Res = DAG.getBitcast(NewVT, N0Src);
19180 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx);
19181 return DAG.getBitcast(VT, Res);
19186 // Canonicalize insert_subvector dag nodes.
19187 // Example:
19188 // (insert_subvector (insert_subvector A, Idx0), Idx1)
19189 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
19190 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
19191 N1.getValueType() == N0.getOperand(1).getValueType() &&
19192 isa<ConstantSDNode>(N0.getOperand(2))) {
19193 unsigned OtherIdx = N0.getConstantOperandVal(2);
19194 if (InsIdx < OtherIdx) {
19195 // Swap nodes.
19196 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
19197 N0.getOperand(0), N1, N2);
19198 AddToWorklist(NewOp.getNode());
19199 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
19200 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
19204 // If the input vector is a concatenation, and the insert replaces
19205 // one of the pieces, we can optimize into a single concat_vectors.
19206 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
19207 N0.getOperand(0).getValueType() == N1.getValueType()) {
19208 unsigned Factor = N1.getValueType().getVectorNumElements();
19210 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
19211 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
19213 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
19216 // Simplify source operands based on insertion.
19217 if (SimplifyDemandedVectorElts(SDValue(N, 0)))
19218 return SDValue(N, 0);
19220 return SDValue();
19223 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
19224 SDValue N0 = N->getOperand(0);
19226 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
19227 if (N0->getOpcode() == ISD::FP16_TO_FP)
19228 return N0->getOperand(0);
19230 return SDValue();
19233 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
19234 SDValue N0 = N->getOperand(0);
19236 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
19237 if (N0->getOpcode() == ISD::AND) {
19238 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
19239 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
19240 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
19241 N0.getOperand(0));
19245 return SDValue();
19248 SDValue DAGCombiner::visitVECREDUCE(SDNode *N) {
19249 SDValue N0 = N->getOperand(0);
19250 EVT VT = N0.getValueType();
19251 unsigned Opcode = N->getOpcode();
19253 // VECREDUCE over 1-element vector is just an extract.
19254 if (VT.getVectorNumElements() == 1) {
19255 SDLoc dl(N);
19256 SDValue Res = DAG.getNode(
19257 ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0,
19258 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
19259 if (Res.getValueType() != N->getValueType(0))
19260 Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res);
19261 return Res;
19264 // On an boolean vector an and/or reduction is the same as a umin/umax
19265 // reduction. Convert them if the latter is legal while the former isn't.
19266 if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) {
19267 unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND
19268 ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX;
19269 if (!TLI.isOperationLegalOrCustom(Opcode, VT) &&
19270 TLI.isOperationLegalOrCustom(NewOpcode, VT) &&
19271 DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits())
19272 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0);
19275 return SDValue();
19278 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
19279 /// with the destination vector and a zero vector.
19280 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
19281 /// vector_shuffle V, Zero, <0, 4, 2, 4>
19282 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
19283 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
19285 EVT VT = N->getValueType(0);
19286 SDValue LHS = N->getOperand(0);
19287 SDValue RHS = peekThroughBitcasts(N->getOperand(1));
19288 SDLoc DL(N);
19290 // Make sure we're not running after operation legalization where it
19291 // may have custom lowered the vector shuffles.
19292 if (LegalOperations)
19293 return SDValue();
19295 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
19296 return SDValue();
19298 EVT RVT = RHS.getValueType();
19299 unsigned NumElts = RHS.getNumOperands();
19301 // Attempt to create a valid clear mask, splitting the mask into
19302 // sub elements and checking to see if each is
19303 // all zeros or all ones - suitable for shuffle masking.
19304 auto BuildClearMask = [&](int Split) {
19305 int NumSubElts = NumElts * Split;
19306 int NumSubBits = RVT.getScalarSizeInBits() / Split;
19308 SmallVector<int, 8> Indices;
19309 for (int i = 0; i != NumSubElts; ++i) {
19310 int EltIdx = i / Split;
19311 int SubIdx = i % Split;
19312 SDValue Elt = RHS.getOperand(EltIdx);
19313 if (Elt.isUndef()) {
19314 Indices.push_back(-1);
19315 continue;
19318 APInt Bits;
19319 if (isa<ConstantSDNode>(Elt))
19320 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
19321 else if (isa<ConstantFPSDNode>(Elt))
19322 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
19323 else
19324 return SDValue();
19326 // Extract the sub element from the constant bit mask.
19327 if (DAG.getDataLayout().isBigEndian()) {
19328 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
19329 } else {
19330 Bits.lshrInPlace(SubIdx * NumSubBits);
19333 if (Split > 1)
19334 Bits = Bits.trunc(NumSubBits);
19336 if (Bits.isAllOnesValue())
19337 Indices.push_back(i);
19338 else if (Bits == 0)
19339 Indices.push_back(i + NumSubElts);
19340 else
19341 return SDValue();
19344 // Let's see if the target supports this vector_shuffle.
19345 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
19346 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
19347 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
19348 return SDValue();
19350 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
19351 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
19352 DAG.getBitcast(ClearVT, LHS),
19353 Zero, Indices));
19356 // Determine maximum split level (byte level masking).
19357 int MaxSplit = 1;
19358 if (RVT.getScalarSizeInBits() % 8 == 0)
19359 MaxSplit = RVT.getScalarSizeInBits() / 8;
19361 for (int Split = 1; Split <= MaxSplit; ++Split)
19362 if (RVT.getScalarSizeInBits() % Split == 0)
19363 if (SDValue S = BuildClearMask(Split))
19364 return S;
19366 return SDValue();
19369 /// If a vector binop is performed on splat values, it may be profitable to
19370 /// extract, scalarize, and insert/splat.
19371 static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG) {
19372 SDValue N0 = N->getOperand(0);
19373 SDValue N1 = N->getOperand(1);
19374 unsigned Opcode = N->getOpcode();
19375 EVT VT = N->getValueType(0);
19376 EVT EltVT = VT.getVectorElementType();
19377 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19379 // TODO: Remove/replace the extract cost check? If the elements are available
19380 // as scalars, then there may be no extract cost. Should we ask if
19381 // inserting a scalar back into a vector is cheap instead?
19382 int Index0, Index1;
19383 SDValue Src0 = DAG.getSplatSourceVector(N0, Index0);
19384 SDValue Src1 = DAG.getSplatSourceVector(N1, Index1);
19385 if (!Src0 || !Src1 || Index0 != Index1 ||
19386 Src0.getValueType().getVectorElementType() != EltVT ||
19387 Src1.getValueType().getVectorElementType() != EltVT ||
19388 !TLI.isExtractVecEltCheap(VT, Index0) ||
19389 !TLI.isOperationLegalOrCustom(Opcode, EltVT))
19390 return SDValue();
19392 SDLoc DL(N);
19393 SDValue IndexC =
19394 DAG.getConstant(Index0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
19395 SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N0, IndexC);
19396 SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N1, IndexC);
19397 SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags());
19399 // If all lanes but 1 are undefined, no need to splat the scalar result.
19400 // TODO: Keep track of undefs and use that info in the general case.
19401 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() &&
19402 count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 &&
19403 count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) {
19404 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
19405 // build_vec ..undef, (bo X, Y), undef...
19406 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT));
19407 Ops[Index0] = ScalarBO;
19408 return DAG.getBuildVector(VT, DL, Ops);
19411 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
19412 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO);
19413 return DAG.getBuildVector(VT, DL, Ops);
19416 /// Visit a binary vector operation, like ADD.
19417 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
19418 assert(N->getValueType(0).isVector() &&
19419 "SimplifyVBinOp only works on vectors!");
19421 SDValue LHS = N->getOperand(0);
19422 SDValue RHS = N->getOperand(1);
19423 SDValue Ops[] = {LHS, RHS};
19424 EVT VT = N->getValueType(0);
19425 unsigned Opcode = N->getOpcode();
19427 // See if we can constant fold the vector operation.
19428 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
19429 Opcode, SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
19430 return Fold;
19432 // Move unary shuffles with identical masks after a vector binop:
19433 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
19434 // --> shuffle (VBinOp A, B), Undef, Mask
19435 // This does not require type legality checks because we are creating the
19436 // same types of operations that are in the original sequence. We do have to
19437 // restrict ops like integer div that have immediate UB (eg, div-by-zero)
19438 // though. This code is adapted from the identical transform in instcombine.
19439 if (Opcode != ISD::UDIV && Opcode != ISD::SDIV &&
19440 Opcode != ISD::UREM && Opcode != ISD::SREM &&
19441 Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) {
19442 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
19443 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
19444 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
19445 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
19446 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
19447 SDLoc DL(N);
19448 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0),
19449 RHS.getOperand(0), N->getFlags());
19450 SDValue UndefV = LHS.getOperand(1);
19451 return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
19455 // The following pattern is likely to emerge with vector reduction ops. Moving
19456 // the binary operation ahead of insertion may allow using a narrower vector
19457 // instruction that has better performance than the wide version of the op:
19458 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
19459 if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() &&
19460 RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() &&
19461 LHS.getOperand(2) == RHS.getOperand(2) &&
19462 (LHS.hasOneUse() || RHS.hasOneUse())) {
19463 SDValue X = LHS.getOperand(1);
19464 SDValue Y = RHS.getOperand(1);
19465 SDValue Z = LHS.getOperand(2);
19466 EVT NarrowVT = X.getValueType();
19467 if (NarrowVT == Y.getValueType() &&
19468 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) {
19469 // (binop undef, undef) may not return undef, so compute that result.
19470 SDLoc DL(N);
19471 SDValue VecC =
19472 DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT));
19473 SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y);
19474 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z);
19478 if (SDValue V = scalarizeBinOpOfSplats(N, DAG))
19479 return V;
19481 return SDValue();
19484 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
19485 SDValue N2) {
19486 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
19488 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
19489 cast<CondCodeSDNode>(N0.getOperand(2))->get());
19491 // If we got a simplified select_cc node back from SimplifySelectCC, then
19492 // break it down into a new SETCC node, and a new SELECT node, and then return
19493 // the SELECT node, since we were called with a SELECT node.
19494 if (SCC.getNode()) {
19495 // Check to see if we got a select_cc back (to turn into setcc/select).
19496 // Otherwise, just return whatever node we got back, like fabs.
19497 if (SCC.getOpcode() == ISD::SELECT_CC) {
19498 const SDNodeFlags Flags = N0.getNode()->getFlags();
19499 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
19500 N0.getValueType(),
19501 SCC.getOperand(0), SCC.getOperand(1),
19502 SCC.getOperand(4), Flags);
19503 AddToWorklist(SETCC.getNode());
19504 SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
19505 SCC.getOperand(2), SCC.getOperand(3));
19506 SelectNode->setFlags(Flags);
19507 return SelectNode;
19510 return SCC;
19512 return SDValue();
19515 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
19516 /// being selected between, see if we can simplify the select. Callers of this
19517 /// should assume that TheSelect is deleted if this returns true. As such, they
19518 /// should return the appropriate thing (e.g. the node) back to the top-level of
19519 /// the DAG combiner loop to avoid it being looked at.
19520 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
19521 SDValue RHS) {
19522 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19523 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
19524 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
19525 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
19526 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
19527 SDValue Sqrt = RHS;
19528 ISD::CondCode CC;
19529 SDValue CmpLHS;
19530 const ConstantFPSDNode *Zero = nullptr;
19532 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
19533 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
19534 CmpLHS = TheSelect->getOperand(0);
19535 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
19536 } else {
19537 // SELECT or VSELECT
19538 SDValue Cmp = TheSelect->getOperand(0);
19539 if (Cmp.getOpcode() == ISD::SETCC) {
19540 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
19541 CmpLHS = Cmp.getOperand(0);
19542 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
19545 if (Zero && Zero->isZero() &&
19546 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
19547 CC == ISD::SETULT || CC == ISD::SETLT)) {
19548 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19549 CombineTo(TheSelect, Sqrt);
19550 return true;
19554 // Cannot simplify select with vector condition
19555 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
19557 // If this is a select from two identical things, try to pull the operation
19558 // through the select.
19559 if (LHS.getOpcode() != RHS.getOpcode() ||
19560 !LHS.hasOneUse() || !RHS.hasOneUse())
19561 return false;
19563 // If this is a load and the token chain is identical, replace the select
19564 // of two loads with a load through a select of the address to load from.
19565 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
19566 // constants have been dropped into the constant pool.
19567 if (LHS.getOpcode() == ISD::LOAD) {
19568 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
19569 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
19571 // Token chains must be identical.
19572 if (LHS.getOperand(0) != RHS.getOperand(0) ||
19573 // Do not let this transformation reduce the number of volatile loads.
19574 LLD->isVolatile() || RLD->isVolatile() ||
19575 // FIXME: If either is a pre/post inc/dec load,
19576 // we'd need to split out the address adjustment.
19577 LLD->isIndexed() || RLD->isIndexed() ||
19578 // If this is an EXTLOAD, the VT's must match.
19579 LLD->getMemoryVT() != RLD->getMemoryVT() ||
19580 // If this is an EXTLOAD, the kind of extension must match.
19581 (LLD->getExtensionType() != RLD->getExtensionType() &&
19582 // The only exception is if one of the extensions is anyext.
19583 LLD->getExtensionType() != ISD::EXTLOAD &&
19584 RLD->getExtensionType() != ISD::EXTLOAD) ||
19585 // FIXME: this discards src value information. This is
19586 // over-conservative. It would be beneficial to be able to remember
19587 // both potential memory locations. Since we are discarding
19588 // src value info, don't do the transformation if the memory
19589 // locations are not in the default address space.
19590 LLD->getPointerInfo().getAddrSpace() != 0 ||
19591 RLD->getPointerInfo().getAddrSpace() != 0 ||
19592 // We can't produce a CMOV of a TargetFrameIndex since we won't
19593 // generate the address generation required.
19594 LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
19595 RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
19596 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
19597 LLD->getBasePtr().getValueType()))
19598 return false;
19600 // The loads must not depend on one another.
19601 if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD))
19602 return false;
19604 // Check that the select condition doesn't reach either load. If so,
19605 // folding this will induce a cycle into the DAG. If not, this is safe to
19606 // xform, so create a select of the addresses.
19608 SmallPtrSet<const SDNode *, 32> Visited;
19609 SmallVector<const SDNode *, 16> Worklist;
19611 // Always fail if LLD and RLD are not independent. TheSelect is a
19612 // predecessor to all Nodes in question so we need not search past it.
19614 Visited.insert(TheSelect);
19615 Worklist.push_back(LLD);
19616 Worklist.push_back(RLD);
19618 if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) ||
19619 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))
19620 return false;
19622 SDValue Addr;
19623 if (TheSelect->getOpcode() == ISD::SELECT) {
19624 // We cannot do this optimization if any pair of {RLD, LLD} is a
19625 // predecessor to {RLD, LLD, CondNode}. As we've already compared the
19626 // Loads, we only need to check if CondNode is a successor to one of the
19627 // loads. We can further avoid this if there's no use of their chain
19628 // value.
19629 SDNode *CondNode = TheSelect->getOperand(0).getNode();
19630 Worklist.push_back(CondNode);
19632 if ((LLD->hasAnyUseOfValue(1) &&
19633 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
19634 (RLD->hasAnyUseOfValue(1) &&
19635 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
19636 return false;
19638 Addr = DAG.getSelect(SDLoc(TheSelect),
19639 LLD->getBasePtr().getValueType(),
19640 TheSelect->getOperand(0), LLD->getBasePtr(),
19641 RLD->getBasePtr());
19642 } else { // Otherwise SELECT_CC
19643 // We cannot do this optimization if any pair of {RLD, LLD} is a
19644 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
19645 // the Loads, we only need to check if CondLHS/CondRHS is a successor to
19646 // one of the loads. We can further avoid this if there's no use of their
19647 // chain value.
19649 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
19650 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
19651 Worklist.push_back(CondLHS);
19652 Worklist.push_back(CondRHS);
19654 if ((LLD->hasAnyUseOfValue(1) &&
19655 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
19656 (RLD->hasAnyUseOfValue(1) &&
19657 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
19658 return false;
19660 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
19661 LLD->getBasePtr().getValueType(),
19662 TheSelect->getOperand(0),
19663 TheSelect->getOperand(1),
19664 LLD->getBasePtr(), RLD->getBasePtr(),
19665 TheSelect->getOperand(4));
19668 SDValue Load;
19669 // It is safe to replace the two loads if they have different alignments,
19670 // but the new load must be the minimum (most restrictive) alignment of the
19671 // inputs.
19672 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
19673 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
19674 if (!RLD->isInvariant())
19675 MMOFlags &= ~MachineMemOperand::MOInvariant;
19676 if (!RLD->isDereferenceable())
19677 MMOFlags &= ~MachineMemOperand::MODereferenceable;
19678 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
19679 // FIXME: Discards pointer and AA info.
19680 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
19681 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
19682 MMOFlags);
19683 } else {
19684 // FIXME: Discards pointer and AA info.
19685 Load = DAG.getExtLoad(
19686 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
19687 : LLD->getExtensionType(),
19688 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
19689 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
19692 // Users of the select now use the result of the load.
19693 CombineTo(TheSelect, Load);
19695 // Users of the old loads now use the new load's chain. We know the
19696 // old-load value is dead now.
19697 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
19698 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
19699 return true;
19702 return false;
19705 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
19706 /// bitwise 'and'.
19707 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
19708 SDValue N1, SDValue N2, SDValue N3,
19709 ISD::CondCode CC) {
19710 // If this is a select where the false operand is zero and the compare is a
19711 // check of the sign bit, see if we can perform the "gzip trick":
19712 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
19713 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
19714 EVT XType = N0.getValueType();
19715 EVT AType = N2.getValueType();
19716 if (!isNullConstant(N3) || !XType.bitsGE(AType))
19717 return SDValue();
19719 // If the comparison is testing for a positive value, we have to invert
19720 // the sign bit mask, so only do that transform if the target has a bitwise
19721 // 'and not' instruction (the invert is free).
19722 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
19723 // (X > -1) ? A : 0
19724 // (X > 0) ? X : 0 <-- This is canonical signed max.
19725 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
19726 return SDValue();
19727 } else if (CC == ISD::SETLT) {
19728 // (X < 0) ? A : 0
19729 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
19730 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
19731 return SDValue();
19732 } else {
19733 return SDValue();
19736 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
19737 // constant.
19738 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
19739 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
19740 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
19741 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
19742 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
19743 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
19744 AddToWorklist(Shift.getNode());
19746 if (XType.bitsGT(AType)) {
19747 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
19748 AddToWorklist(Shift.getNode());
19751 if (CC == ISD::SETGT)
19752 Shift = DAG.getNOT(DL, Shift, AType);
19754 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
19757 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
19758 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
19759 AddToWorklist(Shift.getNode());
19761 if (XType.bitsGT(AType)) {
19762 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
19763 AddToWorklist(Shift.getNode());
19766 if (CC == ISD::SETGT)
19767 Shift = DAG.getNOT(DL, Shift, AType);
19769 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
19772 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
19773 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
19774 /// in it. This may be a win when the constant is not otherwise available
19775 /// because it replaces two constant pool loads with one.
19776 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
19777 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
19778 ISD::CondCode CC) {
19779 if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType().isFloatingPoint()))
19780 return SDValue();
19782 // If we are before legalize types, we want the other legalization to happen
19783 // first (for example, to avoid messing with soft float).
19784 auto *TV = dyn_cast<ConstantFPSDNode>(N2);
19785 auto *FV = dyn_cast<ConstantFPSDNode>(N3);
19786 EVT VT = N2.getValueType();
19787 if (!TV || !FV || !TLI.isTypeLegal(VT))
19788 return SDValue();
19790 // If a constant can be materialized without loads, this does not make sense.
19791 if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal ||
19792 TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) ||
19793 TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize))
19794 return SDValue();
19796 // If both constants have multiple uses, then we won't need to do an extra
19797 // load. The values are likely around in registers for other users.
19798 if (!TV->hasOneUse() && !FV->hasOneUse())
19799 return SDValue();
19801 Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()),
19802 const_cast<ConstantFP*>(TV->getConstantFPValue()) };
19803 Type *FPTy = Elts[0]->getType();
19804 const DataLayout &TD = DAG.getDataLayout();
19806 // Create a ConstantArray of the two constants.
19807 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
19808 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
19809 TD.getPrefTypeAlignment(FPTy));
19810 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
19812 // Get offsets to the 0 and 1 elements of the array, so we can select between
19813 // them.
19814 SDValue Zero = DAG.getIntPtrConstant(0, DL);
19815 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
19816 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
19817 SDValue Cond =
19818 DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC);
19819 AddToWorklist(Cond.getNode());
19820 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero);
19821 AddToWorklist(CstOffset.getNode());
19822 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset);
19823 AddToWorklist(CPIdx.getNode());
19824 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
19825 MachinePointerInfo::getConstantPool(
19826 DAG.getMachineFunction()), Alignment);
19829 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
19830 /// where 'cond' is the comparison specified by CC.
19831 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
19832 SDValue N2, SDValue N3, ISD::CondCode CC,
19833 bool NotExtCompare) {
19834 // (x ? y : y) -> y.
19835 if (N2 == N3) return N2;
19837 EVT CmpOpVT = N0.getValueType();
19838 EVT CmpResVT = getSetCCResultType(CmpOpVT);
19839 EVT VT = N2.getValueType();
19840 auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
19841 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
19842 auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
19844 // Determine if the condition we're dealing with is constant.
19845 if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) {
19846 AddToWorklist(SCC.getNode());
19847 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) {
19848 // fold select_cc true, x, y -> x
19849 // fold select_cc false, x, y -> y
19850 return !(SCCC->isNullValue()) ? N2 : N3;
19854 if (SDValue V =
19855 convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC))
19856 return V;
19858 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
19859 return V;
19861 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
19862 // where y is has a single bit set.
19863 // A plaintext description would be, we can turn the SELECT_CC into an AND
19864 // when the condition can be materialized as an all-ones register. Any
19865 // single bit-test can be materialized as an all-ones register with
19866 // shift-left and shift-right-arith.
19867 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
19868 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
19869 SDValue AndLHS = N0->getOperand(0);
19870 auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
19871 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
19872 // Shift the tested bit over the sign bit.
19873 const APInt &AndMask = ConstAndRHS->getAPIntValue();
19874 SDValue ShlAmt =
19875 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
19876 getShiftAmountTy(AndLHS.getValueType()));
19877 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
19879 // Now arithmetic right shift it all the way over, so the result is either
19880 // all-ones, or zero.
19881 SDValue ShrAmt =
19882 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
19883 getShiftAmountTy(Shl.getValueType()));
19884 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
19886 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
19890 // fold select C, 16, 0 -> shl C, 4
19891 bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2();
19892 bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2();
19894 if ((Fold || Swap) &&
19895 TLI.getBooleanContents(CmpOpVT) ==
19896 TargetLowering::ZeroOrOneBooleanContent &&
19897 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) {
19899 if (Swap) {
19900 CC = ISD::getSetCCInverse(CC, CmpOpVT.isInteger());
19901 std::swap(N2C, N3C);
19904 // If the caller doesn't want us to simplify this into a zext of a compare,
19905 // don't do it.
19906 if (NotExtCompare && N2C->isOne())
19907 return SDValue();
19909 SDValue Temp, SCC;
19910 // zext (setcc n0, n1)
19911 if (LegalTypes) {
19912 SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC);
19913 if (VT.bitsLT(SCC.getValueType()))
19914 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT);
19915 else
19916 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
19917 } else {
19918 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
19919 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
19922 AddToWorklist(SCC.getNode());
19923 AddToWorklist(Temp.getNode());
19925 if (N2C->isOne())
19926 return Temp;
19928 // shl setcc result by log2 n2c
19929 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
19930 DAG.getConstant(N2C->getAPIntValue().logBase2(),
19931 SDLoc(Temp),
19932 getShiftAmountTy(Temp.getValueType())));
19935 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
19936 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
19937 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
19938 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
19939 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
19940 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
19941 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
19942 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
19943 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
19944 SDValue ValueOnZero = N2;
19945 SDValue Count = N3;
19946 // If the condition is NE instead of E, swap the operands.
19947 if (CC == ISD::SETNE)
19948 std::swap(ValueOnZero, Count);
19949 // Check if the value on zero is a constant equal to the bits in the type.
19950 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
19951 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
19952 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
19953 // legal, combine to just cttz.
19954 if ((Count.getOpcode() == ISD::CTTZ ||
19955 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
19956 N0 == Count.getOperand(0) &&
19957 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
19958 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
19959 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
19960 // legal, combine to just ctlz.
19961 if ((Count.getOpcode() == ISD::CTLZ ||
19962 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
19963 N0 == Count.getOperand(0) &&
19964 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
19965 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
19970 return SDValue();
19973 /// This is a stub for TargetLowering::SimplifySetCC.
19974 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
19975 ISD::CondCode Cond, const SDLoc &DL,
19976 bool foldBooleans) {
19977 TargetLowering::DAGCombinerInfo
19978 DagCombineInfo(DAG, Level, false, this);
19979 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
19982 /// Given an ISD::SDIV node expressing a divide by constant, return
19983 /// a DAG expression to select that will generate the same value by multiplying
19984 /// by a magic number.
19985 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
19986 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
19987 // when optimising for minimum size, we don't want to expand a div to a mul
19988 // and a shift.
19989 if (DAG.getMachineFunction().getFunction().hasMinSize())
19990 return SDValue();
19992 SmallVector<SDNode *, 8> Built;
19993 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) {
19994 for (SDNode *N : Built)
19995 AddToWorklist(N);
19996 return S;
19999 return SDValue();
20002 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
20003 /// DAG expression that will generate the same value by right shifting.
20004 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
20005 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
20006 if (!C)
20007 return SDValue();
20009 // Avoid division by zero.
20010 if (C->isNullValue())
20011 return SDValue();
20013 SmallVector<SDNode *, 8> Built;
20014 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) {
20015 for (SDNode *N : Built)
20016 AddToWorklist(N);
20017 return S;
20020 return SDValue();
20023 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
20024 /// expression that will generate the same value by multiplying by a magic
20025 /// number.
20026 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
20027 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
20028 // when optimising for minimum size, we don't want to expand a div to a mul
20029 // and a shift.
20030 if (DAG.getMachineFunction().getFunction().hasMinSize())
20031 return SDValue();
20033 SmallVector<SDNode *, 8> Built;
20034 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) {
20035 for (SDNode *N : Built)
20036 AddToWorklist(N);
20037 return S;
20040 return SDValue();
20043 /// Determines the LogBase2 value for a non-null input value using the
20044 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
20045 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
20046 EVT VT = V.getValueType();
20047 unsigned EltBits = VT.getScalarSizeInBits();
20048 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
20049 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
20050 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
20051 return LogBase2;
20054 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20055 /// For the reciprocal, we need to find the zero of the function:
20056 /// F(X) = A X - 1 [which has a zero at X = 1/A]
20057 /// =>
20058 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
20059 /// does not require additional intermediate precision]
20060 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
20061 if (Level >= AfterLegalizeDAG)
20062 return SDValue();
20064 // TODO: Handle half and/or extended types?
20065 EVT VT = Op.getValueType();
20066 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
20067 return SDValue();
20069 // If estimates are explicitly disabled for this function, we're done.
20070 MachineFunction &MF = DAG.getMachineFunction();
20071 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
20072 if (Enabled == TLI.ReciprocalEstimate::Disabled)
20073 return SDValue();
20075 // Estimates may be explicitly enabled for this type with a custom number of
20076 // refinement steps.
20077 int Iterations = TLI.getDivRefinementSteps(VT, MF);
20078 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
20079 AddToWorklist(Est.getNode());
20081 if (Iterations) {
20082 SDLoc DL(Op);
20083 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
20085 // Newton iterations: Est = Est + Est (1 - Arg * Est)
20086 for (int i = 0; i < Iterations; ++i) {
20087 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
20088 AddToWorklist(NewEst.getNode());
20090 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
20091 AddToWorklist(NewEst.getNode());
20093 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
20094 AddToWorklist(NewEst.getNode());
20096 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
20097 AddToWorklist(Est.getNode());
20100 return Est;
20103 return SDValue();
20106 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20107 /// For the reciprocal sqrt, we need to find the zero of the function:
20108 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20109 /// =>
20110 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
20111 /// As a result, we precompute A/2 prior to the iteration loop.
20112 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
20113 unsigned Iterations,
20114 SDNodeFlags Flags, bool Reciprocal) {
20115 EVT VT = Arg.getValueType();
20116 SDLoc DL(Arg);
20117 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
20119 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
20120 // this entire sequence requires only one FP constant.
20121 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
20122 AddToWorklist(HalfArg.getNode());
20124 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
20125 AddToWorklist(HalfArg.getNode());
20127 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
20128 for (unsigned i = 0; i < Iterations; ++i) {
20129 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
20130 AddToWorklist(NewEst.getNode());
20132 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
20133 AddToWorklist(NewEst.getNode());
20135 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
20136 AddToWorklist(NewEst.getNode());
20138 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
20139 AddToWorklist(Est.getNode());
20142 // If non-reciprocal square root is requested, multiply the result by Arg.
20143 if (!Reciprocal) {
20144 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
20145 AddToWorklist(Est.getNode());
20148 return Est;
20151 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20152 /// For the reciprocal sqrt, we need to find the zero of the function:
20153 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20154 /// =>
20155 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
20156 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
20157 unsigned Iterations,
20158 SDNodeFlags Flags, bool Reciprocal) {
20159 EVT VT = Arg.getValueType();
20160 SDLoc DL(Arg);
20161 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
20162 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
20164 // This routine must enter the loop below to work correctly
20165 // when (Reciprocal == false).
20166 assert(Iterations > 0);
20168 // Newton iterations for reciprocal square root:
20169 // E = (E * -0.5) * ((A * E) * E + -3.0)
20170 for (unsigned i = 0; i < Iterations; ++i) {
20171 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
20172 AddToWorklist(AE.getNode());
20174 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
20175 AddToWorklist(AEE.getNode());
20177 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
20178 AddToWorklist(RHS.getNode());
20180 // When calculating a square root at the last iteration build:
20181 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
20182 // (notice a common subexpression)
20183 SDValue LHS;
20184 if (Reciprocal || (i + 1) < Iterations) {
20185 // RSQRT: LHS = (E * -0.5)
20186 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
20187 } else {
20188 // SQRT: LHS = (A * E) * -0.5
20189 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
20191 AddToWorklist(LHS.getNode());
20193 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
20194 AddToWorklist(Est.getNode());
20197 return Est;
20200 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
20201 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
20202 /// Op can be zero.
20203 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
20204 bool Reciprocal) {
20205 if (Level >= AfterLegalizeDAG)
20206 return SDValue();
20208 // TODO: Handle half and/or extended types?
20209 EVT VT = Op.getValueType();
20210 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
20211 return SDValue();
20213 // If estimates are explicitly disabled for this function, we're done.
20214 MachineFunction &MF = DAG.getMachineFunction();
20215 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
20216 if (Enabled == TLI.ReciprocalEstimate::Disabled)
20217 return SDValue();
20219 // Estimates may be explicitly enabled for this type with a custom number of
20220 // refinement steps.
20221 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
20223 bool UseOneConstNR = false;
20224 if (SDValue Est =
20225 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
20226 Reciprocal)) {
20227 AddToWorklist(Est.getNode());
20229 if (Iterations) {
20230 Est = UseOneConstNR
20231 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
20232 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
20234 if (!Reciprocal) {
20235 // The estimate is now completely wrong if the input was exactly 0.0 or
20236 // possibly a denormal. Force the answer to 0.0 for those cases.
20237 SDLoc DL(Op);
20238 EVT CCVT = getSetCCResultType(VT);
20239 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
20240 const Function &F = DAG.getMachineFunction().getFunction();
20241 Attribute Denorms = F.getFnAttribute("denormal-fp-math");
20242 if (Denorms.getValueAsString().equals("ieee")) {
20243 // fabs(X) < SmallestNormal ? 0.0 : Est
20244 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
20245 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
20246 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
20247 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
20248 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
20249 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
20250 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
20251 AddToWorklist(Fabs.getNode());
20252 AddToWorklist(IsDenorm.getNode());
20253 AddToWorklist(Est.getNode());
20254 } else {
20255 // X == 0.0 ? 0.0 : Est
20256 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
20257 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
20258 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
20259 AddToWorklist(IsZero.getNode());
20260 AddToWorklist(Est.getNode());
20264 return Est;
20267 return SDValue();
20270 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
20271 return buildSqrtEstimateImpl(Op, Flags, true);
20274 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
20275 return buildSqrtEstimateImpl(Op, Flags, false);
20278 /// Return true if there is any possibility that the two addresses overlap.
20279 bool DAGCombiner::isAlias(SDNode *Op0, SDNode *Op1) const {
20281 struct MemUseCharacteristics {
20282 bool IsVolatile;
20283 SDValue BasePtr;
20284 int64_t Offset;
20285 Optional<int64_t> NumBytes;
20286 MachineMemOperand *MMO;
20289 auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics {
20290 if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) {
20291 int64_t Offset = 0;
20292 if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset()))
20293 Offset = (LSN->getAddressingMode() == ISD::PRE_INC)
20294 ? C->getSExtValue()
20295 : (LSN->getAddressingMode() == ISD::PRE_DEC)
20296 ? -1 * C->getSExtValue()
20297 : 0;
20298 return {LSN->isVolatile(), LSN->getBasePtr(), Offset /*base offset*/,
20299 Optional<int64_t>(LSN->getMemoryVT().getStoreSize()),
20300 LSN->getMemOperand()};
20302 if (const auto *LN = cast<LifetimeSDNode>(N))
20303 return {false /*isVolatile*/, LN->getOperand(1),
20304 (LN->hasOffset()) ? LN->getOffset() : 0,
20305 (LN->hasOffset()) ? Optional<int64_t>(LN->getSize())
20306 : Optional<int64_t>(),
20307 (MachineMemOperand *)nullptr};
20308 // Default.
20309 return {false /*isvolatile*/, SDValue(), (int64_t)0 /*offset*/,
20310 Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr};
20313 MemUseCharacteristics MUC0 = getCharacteristics(Op0),
20314 MUC1 = getCharacteristics(Op1);
20316 // If they are to the same address, then they must be aliases.
20317 if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr &&
20318 MUC0.Offset == MUC1.Offset)
20319 return true;
20321 // If they are both volatile then they cannot be reordered.
20322 if (MUC0.IsVolatile && MUC1.IsVolatile)
20323 return true;
20325 if (MUC0.MMO && MUC1.MMO) {
20326 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
20327 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
20328 return false;
20331 // Try to prove that there is aliasing, or that there is no aliasing. Either
20332 // way, we can return now. If nothing can be proved, proceed with more tests.
20333 bool IsAlias;
20334 if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes,
20335 DAG, IsAlias))
20336 return IsAlias;
20338 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
20339 // either are not known.
20340 if (!MUC0.MMO || !MUC1.MMO)
20341 return true;
20343 // If one operation reads from invariant memory, and the other may store, they
20344 // cannot alias. These should really be checking the equivalent of mayWrite,
20345 // but it only matters for memory nodes other than load /store.
20346 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
20347 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
20348 return false;
20350 // If we know required SrcValue1 and SrcValue2 have relatively large
20351 // alignment compared to the size and offset of the access, we may be able
20352 // to prove they do not alias. This check is conservative for now to catch
20353 // cases created by splitting vector types.
20354 int64_t SrcValOffset0 = MUC0.MMO->getOffset();
20355 int64_t SrcValOffset1 = MUC1.MMO->getOffset();
20356 unsigned OrigAlignment0 = MUC0.MMO->getBaseAlignment();
20357 unsigned OrigAlignment1 = MUC1.MMO->getBaseAlignment();
20358 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
20359 MUC0.NumBytes.hasValue() && MUC1.NumBytes.hasValue() &&
20360 *MUC0.NumBytes == *MUC1.NumBytes && OrigAlignment0 > *MUC0.NumBytes) {
20361 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
20362 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
20364 // There is no overlap between these relatively aligned accesses of
20365 // similar size. Return no alias.
20366 if ((OffAlign0 + *MUC0.NumBytes) <= OffAlign1 ||
20367 (OffAlign1 + *MUC1.NumBytes) <= OffAlign0)
20368 return false;
20371 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
20372 ? CombinerGlobalAA
20373 : DAG.getSubtarget().useAA();
20374 #ifndef NDEBUG
20375 if (CombinerAAOnlyFunc.getNumOccurrences() &&
20376 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
20377 UseAA = false;
20378 #endif
20380 if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue()) {
20381 // Use alias analysis information.
20382 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
20383 int64_t Overlap0 = *MUC0.NumBytes + SrcValOffset0 - MinOffset;
20384 int64_t Overlap1 = *MUC1.NumBytes + SrcValOffset1 - MinOffset;
20385 AliasResult AAResult = AA->alias(
20386 MemoryLocation(MUC0.MMO->getValue(), Overlap0,
20387 UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()),
20388 MemoryLocation(MUC1.MMO->getValue(), Overlap1,
20389 UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes()));
20390 if (AAResult == NoAlias)
20391 return false;
20394 // Otherwise we have to assume they alias.
20395 return true;
20398 /// Walk up chain skipping non-aliasing memory nodes,
20399 /// looking for aliasing nodes and adding them to the Aliases vector.
20400 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
20401 SmallVectorImpl<SDValue> &Aliases) {
20402 SmallVector<SDValue, 8> Chains; // List of chains to visit.
20403 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
20405 // Get alias information for node.
20406 const bool IsLoad = isa<LoadSDNode>(N) && !cast<LoadSDNode>(N)->isVolatile();
20408 // Starting off.
20409 Chains.push_back(OriginalChain);
20410 unsigned Depth = 0;
20412 // Attempt to improve chain by a single step
20413 std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool {
20414 switch (C.getOpcode()) {
20415 case ISD::EntryToken:
20416 // No need to mark EntryToken.
20417 C = SDValue();
20418 return true;
20419 case ISD::LOAD:
20420 case ISD::STORE: {
20421 // Get alias information for C.
20422 bool IsOpLoad = isa<LoadSDNode>(C.getNode()) &&
20423 !cast<LSBaseSDNode>(C.getNode())->isVolatile();
20424 if ((IsLoad && IsOpLoad) || !isAlias(N, C.getNode())) {
20425 // Look further up the chain.
20426 C = C.getOperand(0);
20427 return true;
20429 // Alias, so stop here.
20430 return false;
20433 case ISD::CopyFromReg:
20434 // Always forward past past CopyFromReg.
20435 C = C.getOperand(0);
20436 return true;
20438 case ISD::LIFETIME_START:
20439 case ISD::LIFETIME_END: {
20440 // We can forward past any lifetime start/end that can be proven not to
20441 // alias the memory access.
20442 if (!isAlias(N, C.getNode())) {
20443 // Look further up the chain.
20444 C = C.getOperand(0);
20445 return true;
20447 return false;
20449 default:
20450 return false;
20454 // Look at each chain and determine if it is an alias. If so, add it to the
20455 // aliases list. If not, then continue up the chain looking for the next
20456 // candidate.
20457 while (!Chains.empty()) {
20458 SDValue Chain = Chains.pop_back_val();
20460 // Don't bother if we've seen Chain before.
20461 if (!Visited.insert(Chain.getNode()).second)
20462 continue;
20464 // For TokenFactor nodes, look at each operand and only continue up the
20465 // chain until we reach the depth limit.
20467 // FIXME: The depth check could be made to return the last non-aliasing
20468 // chain we found before we hit a tokenfactor rather than the original
20469 // chain.
20470 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
20471 Aliases.clear();
20472 Aliases.push_back(OriginalChain);
20473 return;
20476 if (Chain.getOpcode() == ISD::TokenFactor) {
20477 // We have to check each of the operands of the token factor for "small"
20478 // token factors, so we queue them up. Adding the operands to the queue
20479 // (stack) in reverse order maintains the original order and increases the
20480 // likelihood that getNode will find a matching token factor (CSE.)
20481 if (Chain.getNumOperands() > 16) {
20482 Aliases.push_back(Chain);
20483 continue;
20485 for (unsigned n = Chain.getNumOperands(); n;)
20486 Chains.push_back(Chain.getOperand(--n));
20487 ++Depth;
20488 continue;
20490 // Everything else
20491 if (ImproveChain(Chain)) {
20492 // Updated Chain Found, Consider new chain if one exists.
20493 if (Chain.getNode())
20494 Chains.push_back(Chain);
20495 ++Depth;
20496 continue;
20498 // No Improved Chain Possible, treat as Alias.
20499 Aliases.push_back(Chain);
20503 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
20504 /// (aliasing node.)
20505 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
20506 if (OptLevel == CodeGenOpt::None)
20507 return OldChain;
20509 // Ops for replacing token factor.
20510 SmallVector<SDValue, 8> Aliases;
20512 // Accumulate all the aliases to this node.
20513 GatherAllAliases(N, OldChain, Aliases);
20515 // If no operands then chain to entry token.
20516 if (Aliases.size() == 0)
20517 return DAG.getEntryNode();
20519 // If a single operand then chain to it. We don't need to revisit it.
20520 if (Aliases.size() == 1)
20521 return Aliases[0];
20523 // Construct a custom tailored token factor.
20524 return DAG.getTokenFactor(SDLoc(N), Aliases);
20527 namespace {
20528 // TODO: Replace with with std::monostate when we move to C++17.
20529 struct UnitT { } Unit;
20530 bool operator==(const UnitT &, const UnitT &) { return true; }
20531 bool operator!=(const UnitT &, const UnitT &) { return false; }
20532 } // namespace
20534 // This function tries to collect a bunch of potentially interesting
20535 // nodes to improve the chains of, all at once. This might seem
20536 // redundant, as this function gets called when visiting every store
20537 // node, so why not let the work be done on each store as it's visited?
20539 // I believe this is mainly important because MergeConsecutiveStores
20540 // is unable to deal with merging stores of different sizes, so unless
20541 // we improve the chains of all the potential candidates up-front
20542 // before running MergeConsecutiveStores, it might only see some of
20543 // the nodes that will eventually be candidates, and then not be able
20544 // to go from a partially-merged state to the desired final
20545 // fully-merged state.
20547 bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) {
20548 SmallVector<StoreSDNode *, 8> ChainedStores;
20549 StoreSDNode *STChain = St;
20550 // Intervals records which offsets from BaseIndex have been covered. In
20551 // the common case, every store writes to the immediately previous address
20552 // space and thus merged with the previous interval at insertion time.
20554 using IMap =
20555 llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>;
20556 IMap::Allocator A;
20557 IMap Intervals(A);
20559 // This holds the base pointer, index, and the offset in bytes from the base
20560 // pointer.
20561 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
20563 // We must have a base and an offset.
20564 if (!BasePtr.getBase().getNode())
20565 return false;
20567 // Do not handle stores to undef base pointers.
20568 if (BasePtr.getBase().isUndef())
20569 return false;
20571 // Add ST's interval.
20572 Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit);
20574 while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) {
20575 // If the chain has more than one use, then we can't reorder the mem ops.
20576 if (!SDValue(Chain, 0)->hasOneUse())
20577 break;
20578 if (Chain->isVolatile() || Chain->isIndexed())
20579 break;
20581 // Find the base pointer and offset for this memory node.
20582 const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG);
20583 // Check that the base pointer is the same as the original one.
20584 int64_t Offset;
20585 if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset))
20586 break;
20587 int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8;
20588 // Make sure we don't overlap with other intervals by checking the ones to
20589 // the left or right before inserting.
20590 auto I = Intervals.find(Offset);
20591 // If there's a next interval, we should end before it.
20592 if (I != Intervals.end() && I.start() < (Offset + Length))
20593 break;
20594 // If there's a previous interval, we should start after it.
20595 if (I != Intervals.begin() && (--I).stop() <= Offset)
20596 break;
20597 Intervals.insert(Offset, Offset + Length, Unit);
20599 ChainedStores.push_back(Chain);
20600 STChain = Chain;
20603 // If we didn't find a chained store, exit.
20604 if (ChainedStores.size() == 0)
20605 return false;
20607 // Improve all chained stores (St and ChainedStores members) starting from
20608 // where the store chain ended and return single TokenFactor.
20609 SDValue NewChain = STChain->getChain();
20610 SmallVector<SDValue, 8> TFOps;
20611 for (unsigned I = ChainedStores.size(); I;) {
20612 StoreSDNode *S = ChainedStores[--I];
20613 SDValue BetterChain = FindBetterChain(S, NewChain);
20614 S = cast<StoreSDNode>(DAG.UpdateNodeOperands(
20615 S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3)));
20616 TFOps.push_back(SDValue(S, 0));
20617 ChainedStores[I] = S;
20620 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
20621 SDValue BetterChain = FindBetterChain(St, NewChain);
20622 SDValue NewST;
20623 if (St->isTruncatingStore())
20624 NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(),
20625 St->getBasePtr(), St->getMemoryVT(),
20626 St->getMemOperand());
20627 else
20628 NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(),
20629 St->getBasePtr(), St->getMemOperand());
20631 TFOps.push_back(NewST);
20633 // If we improved every element of TFOps, then we've lost the dependence on
20634 // NewChain to successors of St and we need to add it back to TFOps. Do so at
20635 // the beginning to keep relative order consistent with FindBetterChains.
20636 auto hasImprovedChain = [&](SDValue ST) -> bool {
20637 return ST->getOperand(0) != NewChain;
20639 bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain);
20640 if (AddNewChain)
20641 TFOps.insert(TFOps.begin(), NewChain);
20643 SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps);
20644 CombineTo(St, TF);
20646 AddToWorklist(STChain);
20647 // Add TF operands worklist in reverse order.
20648 for (auto I = TF->getNumOperands(); I;)
20649 AddToWorklist(TF->getOperand(--I).getNode());
20650 AddToWorklist(TF.getNode());
20651 return true;
20654 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
20655 if (OptLevel == CodeGenOpt::None)
20656 return false;
20658 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
20660 // We must have a base and an offset.
20661 if (!BasePtr.getBase().getNode())
20662 return false;
20664 // Do not handle stores to undef base pointers.
20665 if (BasePtr.getBase().isUndef())
20666 return false;
20668 // Directly improve a chain of disjoint stores starting at St.
20669 if (parallelizeChainedStores(St))
20670 return true;
20672 // Improve St's Chain..
20673 SDValue BetterChain = FindBetterChain(St, St->getChain());
20674 if (St->getChain() != BetterChain) {
20675 replaceStoreChain(St, BetterChain);
20676 return true;
20678 return false;
20681 /// This is the entry point for the file.
20682 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
20683 CodeGenOpt::Level OptLevel) {
20684 /// This is the main entry point to this class.
20685 DAGCombiner(*this, AA, OptLevel).Run(Level);