1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
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");
88 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden
,
89 cl::desc("Enable DAG combiner's use of IR alias analysis"));
92 UseTBAA("combiner-use-tbaa", cl::Hidden
, cl::init(true),
93 cl::desc("Enable DAG combiner's use of TBAA"));
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"
102 /// Hidden option to stress test load slicing, i.e., when this option
103 /// is enabled, load slicing bypasses most of its profitability guards.
105 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden
,
106 cl::desc("Bypass the profitability model of load slicing"),
110 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden
, cl::init(true),
111 cl::desc("DAG combiner may split indexing from loads"));
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"));
131 const TargetLowering
&TLI
;
133 CodeGenOpt::Level OptLevel
;
134 bool LegalOperations
= false;
135 bool LegalTypes
= false;
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
170 DenseMap
<SDNode
*, std::pair
<SDNode
*, unsigned>> StoreRootCountMap
;
172 // AA - Used for DAG load/store alias analysis.
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())
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();
190 recursivelyDeleteUnusedNodes(N
);
194 SDNode
*getNextWorklistEntry() {
195 // Before we do any work, remove nodes that are not in use.
196 clearAddedDanglingWorklistEntries();
198 // The Worklist holds the SDNodes in order, but it may contain null
200 while (!N
&& !Worklist
.empty()) {
201 N
= Worklist
.pop_back_val();
205 bool GoodWorklistEntry
= WorklistMap
.erase(N
);
206 (void)GoodWorklistEntry
;
207 assert(GoodWorklistEntry
&&
208 "Found a worklist entry without a corresponding map entry!");
213 /// Call the node-specific routine that folds each particular type of node.
214 SDValue
visit(SDNode
*N
);
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
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
)
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
,
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
,
282 SDValue To
[] = { Res0
, Res1
};
283 return CombineTo(N
, To
, 2, AddTo
);
286 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt
&TLO
);
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
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
,
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:
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_EXTEND(SDNode
*N
);
444 SDValue
visitFNEG(SDNode
*N
);
445 SDValue
visitFABS(SDNode
*N
);
446 SDValue
visitFCEIL(SDNode
*N
);
447 SDValue
visitFTRUNC(SDNode
*N
);
448 SDValue
visitFFLOOR(SDNode
*N
);
449 SDValue
visitFMINNUM(SDNode
*N
);
450 SDValue
visitFMAXNUM(SDNode
*N
);
451 SDValue
visitFMINIMUM(SDNode
*N
);
452 SDValue
visitFMAXIMUM(SDNode
*N
);
453 SDValue
visitBRCOND(SDNode
*N
);
454 SDValue
visitBR_CC(SDNode
*N
);
455 SDValue
visitLOAD(SDNode
*N
);
457 SDValue
replaceStoreChain(StoreSDNode
*ST
, SDValue BetterChain
);
458 SDValue
replaceStoreOfFPConstant(StoreSDNode
*ST
);
460 SDValue
visitSTORE(SDNode
*N
);
461 SDValue
visitLIFETIME_END(SDNode
*N
);
462 SDValue
visitINSERT_VECTOR_ELT(SDNode
*N
);
463 SDValue
visitEXTRACT_VECTOR_ELT(SDNode
*N
);
464 SDValue
visitBUILD_VECTOR(SDNode
*N
);
465 SDValue
visitCONCAT_VECTORS(SDNode
*N
);
466 SDValue
visitEXTRACT_SUBVECTOR(SDNode
*N
);
467 SDValue
visitVECTOR_SHUFFLE(SDNode
*N
);
468 SDValue
visitSCALAR_TO_VECTOR(SDNode
*N
);
469 SDValue
visitINSERT_SUBVECTOR(SDNode
*N
);
470 SDValue
visitMLOAD(SDNode
*N
);
471 SDValue
visitMSTORE(SDNode
*N
);
472 SDValue
visitMGATHER(SDNode
*N
);
473 SDValue
visitMSCATTER(SDNode
*N
);
474 SDValue
visitFP_TO_FP16(SDNode
*N
);
475 SDValue
visitFP16_TO_FP(SDNode
*N
);
476 SDValue
visitVECREDUCE(SDNode
*N
);
478 SDValue
visitFADDForFMACombine(SDNode
*N
);
479 SDValue
visitFSUBForFMACombine(SDNode
*N
);
480 SDValue
visitFMULForFMADistributiveCombine(SDNode
*N
);
482 SDValue
XformToShuffleWithZero(SDNode
*N
);
483 bool reassociationCanBreakAddressingModePattern(unsigned Opc
,
484 const SDLoc
&DL
, SDValue N0
,
486 SDValue
reassociateOpsCommutative(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
488 SDValue
reassociateOps(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
489 SDValue N1
, SDNodeFlags Flags
);
491 SDValue
visitShiftByConstant(SDNode
*N
);
493 SDValue
foldSelectOfConstants(SDNode
*N
);
494 SDValue
foldVSelectOfConstants(SDNode
*N
);
495 SDValue
foldBinOpIntoSelect(SDNode
*BO
);
496 bool SimplifySelectOps(SDNode
*SELECT
, SDValue LHS
, SDValue RHS
);
497 SDValue
hoistLogicOpWithSameOpcodeHands(SDNode
*N
);
498 SDValue
SimplifySelect(const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
);
499 SDValue
SimplifySelectCC(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
500 SDValue N2
, SDValue N3
, ISD::CondCode CC
,
501 bool NotExtCompare
= false);
502 SDValue
convertSelectOfFPConstantsToLoadOffset(
503 const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
, SDValue N3
,
505 SDValue
foldSelectCCToShiftAnd(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
506 SDValue N2
, SDValue N3
, ISD::CondCode CC
);
507 SDValue
foldLogicOfSetCCs(bool IsAnd
, SDValue N0
, SDValue N1
,
509 SDValue
unfoldMaskedMerge(SDNode
*N
);
510 SDValue
unfoldExtremeBitClearingToShifts(SDNode
*N
);
511 SDValue
SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
,
512 const SDLoc
&DL
, bool foldBooleans
);
513 SDValue
rebuildSetCC(SDValue N
);
515 bool isSetCCEquivalent(SDValue N
, SDValue
&LHS
, SDValue
&RHS
,
517 bool isOneUseSetCC(SDValue N
) const;
518 bool isCheaperToUseNegatedFPOps(SDValue X
, SDValue Y
);
520 SDValue
SimplifyNodeWithTwoResults(SDNode
*N
, unsigned LoOp
,
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
BuildDivEstimate(SDValue N
, 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
,
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
,
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
579 /// Notice that other chains may still be replaced even if the function
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.
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
,
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
,
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
,
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
646 void getStoreMergeCandidates(StoreSDNode
*St
,
647 SmallVectorImpl
<MemOpLink
> &StoreNodes
,
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
,
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
) {
679 return TLI
.isOperationLegal(Opcode
, VT
);
680 return TLI
.isOperationLegalOrCustom(Opcode
, VT
);
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
{
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
{
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 //===----------------------------------------------------------------------===//
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());
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
,
795 unsigned Depth
= 0) {
796 // fneg is removable even if it has multiple uses.
797 if (Op
.getOpcode() == ISD::FNEG
)
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())))
808 // Don't recurse exponentially.
812 switch (Op
.getOpcode()) {
813 default: return false;
814 case ISD::ConstantFP
: {
815 if (!LegalOperations
)
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
,
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
);
830 if (!LegalOperations
)
832 if (TLI
.isOperationLegal(ISD::ConstantFP
, VT
) &&
833 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
835 return llvm::all_of(Op
->op_values(), [&](SDValue N
) {
836 return N
.isUndef() ||
837 TLI
.isFPImmLegal(neg(cast
<ConstantFPSDNode
>(N
)->getValueAPF()), VT
,
842 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
845 // After operation legalization, it might not be legal to create new FSUBs.
846 if (LegalOperations
&& !TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
))
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))
853 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
854 return isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
, Options
,
855 ForCodeSize
, Depth
+ 1);
857 // We can't turn -(A-B) into B-A when we honor signed zeros.
858 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
861 // fold (fneg (fsub A, B)) -> (fsub B, A)
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))
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
)
876 return isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
, Options
,
877 ForCodeSize
, Depth
+ 1);
881 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
884 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
885 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
886 char V2
= isNegatibleForFree(Op
.getOperand(2), LegalOperations
, TLI
,
887 Options
, ForCodeSize
, Depth
+ 1);
891 // One of Op0/Op1 must be cheaply negatible, then select the cheapest.
892 char V0
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
,
893 Options
, ForCodeSize
, Depth
+ 1);
894 char V1
= isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
,
895 Options
, ForCodeSize
, Depth
+ 1);
896 char V01
= std::max(V0
, V1
);
897 return V01
? std::max(V01
, V2
) : 0;
903 return isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
, Options
,
904 ForCodeSize
, Depth
+ 1);
908 /// If isNegatibleForFree returns true, return the newly negated expression.
909 static SDValue
GetNegatedExpression(SDValue Op
, SelectionDAG
&DAG
,
910 bool LegalOperations
, bool ForCodeSize
,
911 unsigned Depth
= 0) {
912 // fneg is removable even if it has multiple uses.
913 if (Op
.getOpcode() == ISD::FNEG
)
914 return Op
.getOperand(0);
916 assert(Depth
<= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
917 const TargetOptions
&Options
= DAG
.getTarget().Options
;
918 const SDNodeFlags Flags
= Op
->getFlags();
920 switch (Op
.getOpcode()) {
921 default: llvm_unreachable("Unknown code");
922 case ISD::ConstantFP
: {
923 APFloat V
= cast
<ConstantFPSDNode
>(Op
)->getValueAPF();
925 return DAG
.getConstantFP(V
, SDLoc(Op
), Op
.getValueType());
927 case ISD::BUILD_VECTOR
: {
928 SmallVector
<SDValue
, 4> Ops
;
929 for (SDValue C
: Op
->op_values()) {
934 APFloat V
= cast
<ConstantFPSDNode
>(C
)->getValueAPF();
936 Ops
.push_back(DAG
.getConstantFP(V
, SDLoc(Op
), C
.getValueType()));
938 return DAG
.getBuildVector(Op
.getValueType(), SDLoc(Op
), Ops
);
941 assert((Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros()) &&
942 "Expected NSZ fp-flag");
944 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
945 if (isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
946 DAG
.getTargetLoweringInfo(), &Options
, ForCodeSize
,
948 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
949 GetNegatedExpression(Op
.getOperand(0), DAG
,
950 LegalOperations
, ForCodeSize
,
952 Op
.getOperand(1), Flags
);
953 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
954 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
955 GetNegatedExpression(Op
.getOperand(1), DAG
,
956 LegalOperations
, ForCodeSize
,
958 Op
.getOperand(0), Flags
);
960 // fold (fneg (fsub 0, B)) -> B
961 if (ConstantFPSDNode
*N0CFP
=
962 isConstOrConstSplatFP(Op
.getOperand(0), /*AllowUndefs*/ true))
964 return Op
.getOperand(1);
966 // fold (fneg (fsub A, B)) -> (fsub B, A)
967 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
968 Op
.getOperand(1), Op
.getOperand(0), Flags
);
972 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
973 if (isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
974 DAG
.getTargetLoweringInfo(), &Options
, ForCodeSize
,
976 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
977 GetNegatedExpression(Op
.getOperand(0), DAG
,
978 LegalOperations
, ForCodeSize
,
980 Op
.getOperand(1), Flags
);
982 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
983 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
985 GetNegatedExpression(Op
.getOperand(1), DAG
,
986 LegalOperations
, ForCodeSize
,
991 assert((Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros()) &&
992 "Expected NSZ fp-flag");
994 SDValue Neg2
= GetNegatedExpression(Op
.getOperand(2), DAG
, LegalOperations
,
995 ForCodeSize
, Depth
+ 1);
997 char V0
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
998 DAG
.getTargetLoweringInfo(), &Options
,
999 ForCodeSize
, Depth
+ 1);
1000 char V1
= isNegatibleForFree(Op
.getOperand(1), LegalOperations
,
1001 DAG
.getTargetLoweringInfo(), &Options
,
1002 ForCodeSize
, Depth
+ 1);
1004 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
1005 SDValue Neg0
= GetNegatedExpression(
1006 Op
.getOperand(0), DAG
, LegalOperations
, ForCodeSize
, Depth
+ 1);
1007 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(), Neg0
,
1008 Op
.getOperand(1), Neg2
, Flags
);
1011 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
1012 SDValue Neg1
= GetNegatedExpression(Op
.getOperand(1), DAG
, LegalOperations
,
1013 ForCodeSize
, Depth
+ 1);
1014 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
1015 Op
.getOperand(0), Neg1
, Neg2
, Flags
);
1018 case ISD::FP_EXTEND
:
1020 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
1021 GetNegatedExpression(Op
.getOperand(0), DAG
,
1022 LegalOperations
, ForCodeSize
,
1025 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(Op
), Op
.getValueType(),
1026 GetNegatedExpression(Op
.getOperand(0), DAG
,
1027 LegalOperations
, ForCodeSize
,
1033 // APInts must be the same size for most operations, this helper
1034 // function zero extends the shorter of the pair so that they match.
1035 // We provide an Offset so that we can create bitwidths that won't overflow.
1036 static void zeroExtendToMatch(APInt
&LHS
, APInt
&RHS
, unsigned Offset
= 0) {
1037 unsigned Bits
= Offset
+ std::max(LHS
.getBitWidth(), RHS
.getBitWidth());
1038 LHS
= LHS
.zextOrSelf(Bits
);
1039 RHS
= RHS
.zextOrSelf(Bits
);
1042 // Return true if this node is a setcc, or is a select_cc
1043 // that selects between the target values used for true and false, making it
1044 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
1045 // the appropriate nodes based on the type of node we are checking. This
1046 // simplifies life a bit for the callers.
1047 bool DAGCombiner::isSetCCEquivalent(SDValue N
, SDValue
&LHS
, SDValue
&RHS
,
1048 SDValue
&CC
) const {
1049 if (N
.getOpcode() == ISD::SETCC
) {
1050 LHS
= N
.getOperand(0);
1051 RHS
= N
.getOperand(1);
1052 CC
= N
.getOperand(2);
1056 if (N
.getOpcode() != ISD::SELECT_CC
||
1057 !TLI
.isConstTrueVal(N
.getOperand(2).getNode()) ||
1058 !TLI
.isConstFalseVal(N
.getOperand(3).getNode()))
1061 if (TLI
.getBooleanContents(N
.getValueType()) ==
1062 TargetLowering::UndefinedBooleanContent
)
1065 LHS
= N
.getOperand(0);
1066 RHS
= N
.getOperand(1);
1067 CC
= N
.getOperand(4);
1071 /// Return true if this is a SetCC-equivalent operation with only one use.
1072 /// If this is true, it allows the users to invert the operation for free when
1073 /// it is profitable to do so.
1074 bool DAGCombiner::isOneUseSetCC(SDValue N
) const {
1076 if (isSetCCEquivalent(N
, N0
, N1
, N2
) && N
.getNode()->hasOneUse())
1081 // Returns the SDNode if it is a constant float BuildVector
1082 // or constant float.
1083 static SDNode
*isConstantFPBuildVectorOrConstantFP(SDValue N
) {
1084 if (isa
<ConstantFPSDNode
>(N
))
1086 if (ISD::isBuildVectorOfConstantFPSDNodes(N
.getNode()))
1091 // Determines if it is a constant integer or a build vector of constant
1092 // integers (and undefs).
1093 // Do not permit build vector implicit truncation.
1094 static bool isConstantOrConstantVector(SDValue N
, bool NoOpaques
= false) {
1095 if (ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(N
))
1096 return !(Const
->isOpaque() && NoOpaques
);
1097 if (N
.getOpcode() != ISD::BUILD_VECTOR
)
1099 unsigned BitWidth
= N
.getScalarValueSizeInBits();
1100 for (const SDValue
&Op
: N
->op_values()) {
1103 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(Op
);
1104 if (!Const
|| Const
->getAPIntValue().getBitWidth() != BitWidth
||
1105 (Const
->isOpaque() && NoOpaques
))
1111 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1113 static bool isAnyConstantBuildVector(SDValue V
, bool NoOpaques
= false) {
1114 if (V
.getOpcode() != ISD::BUILD_VECTOR
)
1116 return isConstantOrConstantVector(V
, NoOpaques
) ||
1117 ISD::isBuildVectorOfConstantFPSDNodes(V
.getNode());
1120 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc
,
1124 // Currently this only tries to ensure we don't undo the GEP splits done by
1125 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1126 // we check if the following transformation would be problematic:
1127 // (load/store (add, (add, x, offset1), offset2)) ->
1128 // (load/store (add, x, offset1+offset2)).
1130 if (Opc
!= ISD::ADD
|| N0
.getOpcode() != ISD::ADD
)
1136 auto *C1
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
1137 auto *C2
= dyn_cast
<ConstantSDNode
>(N1
);
1141 const APInt
&C1APIntVal
= C1
->getAPIntValue();
1142 const APInt
&C2APIntVal
= C2
->getAPIntValue();
1143 if (C1APIntVal
.getBitWidth() > 64 || C2APIntVal
.getBitWidth() > 64)
1146 const APInt CombinedValueIntVal
= C1APIntVal
+ C2APIntVal
;
1147 if (CombinedValueIntVal
.getBitWidth() > 64)
1149 const int64_t CombinedValue
= CombinedValueIntVal
.getSExtValue();
1151 for (SDNode
*Node
: N0
->uses()) {
1152 auto LoadStore
= dyn_cast
<MemSDNode
>(Node
);
1154 // Is x[offset2] already not a legal addressing mode? If so then
1155 // reassociating the constants breaks nothing (we test offset2 because
1156 // that's the one we hope to fold into the load or store).
1157 TargetLoweringBase::AddrMode AM
;
1158 AM
.HasBaseReg
= true;
1159 AM
.BaseOffs
= C2APIntVal
.getSExtValue();
1160 EVT VT
= LoadStore
->getMemoryVT();
1161 unsigned AS
= LoadStore
->getAddressSpace();
1162 Type
*AccessTy
= VT
.getTypeForEVT(*DAG
.getContext());
1163 if (!TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
, AccessTy
, AS
))
1166 // Would x[offset1+offset2] still be a legal addressing mode?
1167 AM
.BaseOffs
= CombinedValue
;
1168 if (!TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
, AccessTy
, AS
))
1176 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
1177 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
1178 SDValue
DAGCombiner::reassociateOpsCommutative(unsigned Opc
, const SDLoc
&DL
,
1179 SDValue N0
, SDValue N1
) {
1180 EVT VT
= N0
.getValueType();
1182 if (N0
.getOpcode() != Opc
)
1185 // Don't reassociate reductions.
1186 if (N0
->getFlags().hasVectorReduction())
1189 if (SDNode
*C1
= DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1))) {
1190 if (SDNode
*C2
= DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
1191 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1192 if (SDValue OpNode
= DAG
.FoldConstantArithmetic(Opc
, DL
, VT
, C1
, C2
))
1193 return DAG
.getNode(Opc
, DL
, VT
, N0
.getOperand(0), OpNode
);
1196 if (N0
.hasOneUse()) {
1197 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1198 // iff (op x, c1) has one use
1199 SDValue OpNode
= DAG
.getNode(Opc
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
1200 if (!OpNode
.getNode())
1202 return DAG
.getNode(Opc
, DL
, VT
, OpNode
, N0
.getOperand(1));
1208 // Try to reassociate commutative binops.
1209 SDValue
DAGCombiner::reassociateOps(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
1210 SDValue N1
, SDNodeFlags Flags
) {
1211 assert(TLI
.isCommutativeBinOp(Opc
) && "Operation not commutative.");
1212 // Don't reassociate reductions.
1213 if (Flags
.hasVectorReduction())
1216 // Floating-point reassociation is not allowed without loose FP math.
1217 if (N0
.getValueType().isFloatingPoint() ||
1218 N1
.getValueType().isFloatingPoint())
1219 if (!Flags
.hasAllowReassociation() || !Flags
.hasNoSignedZeros())
1222 if (SDValue Combined
= reassociateOpsCommutative(Opc
, DL
, N0
, N1
))
1224 if (SDValue Combined
= reassociateOpsCommutative(Opc
, DL
, N1
, N0
))
1229 SDValue
DAGCombiner::CombineTo(SDNode
*N
, const SDValue
*To
, unsigned NumTo
,
1231 assert(N
->getNumValues() == NumTo
&& "Broken CombineTo call!");
1233 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N
->dump(&DAG
); dbgs() << "\nWith: ";
1234 To
[0].getNode()->dump(&DAG
);
1235 dbgs() << " and " << NumTo
- 1 << " other values\n");
1236 for (unsigned i
= 0, e
= NumTo
; i
!= e
; ++i
)
1237 assert((!To
[i
].getNode() ||
1238 N
->getValueType(i
) == To
[i
].getValueType()) &&
1239 "Cannot combine value to value of different type!");
1241 WorklistRemover
DeadNodes(*this);
1242 DAG
.ReplaceAllUsesWith(N
, To
);
1244 // Push the new nodes and any users onto the worklist
1245 for (unsigned i
= 0, e
= NumTo
; i
!= e
; ++i
) {
1246 if (To
[i
].getNode()) {
1247 AddToWorklist(To
[i
].getNode());
1248 AddUsersToWorklist(To
[i
].getNode());
1253 // Finally, if the node is now dead, remove it from the graph. The node
1254 // may not be dead if the replacement process recursively simplified to
1255 // something else needing this node.
1257 deleteAndRecombine(N
);
1258 return SDValue(N
, 0);
1262 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt
&TLO
) {
1263 // Replace all uses. If any nodes become isomorphic to other nodes and
1264 // are deleted, make sure to remove them from our worklist.
1265 WorklistRemover
DeadNodes(*this);
1266 DAG
.ReplaceAllUsesOfValueWith(TLO
.Old
, TLO
.New
);
1268 // Push the new node and any (possibly new) users onto the worklist.
1269 AddToWorklist(TLO
.New
.getNode());
1270 AddUsersToWorklist(TLO
.New
.getNode());
1272 // Finally, if the node is now dead, remove it from the graph. The node
1273 // may not be dead if the replacement process recursively simplified to
1274 // something else needing this node.
1275 if (TLO
.Old
.getNode()->use_empty())
1276 deleteAndRecombine(TLO
.Old
.getNode());
1279 /// Check the specified integer node value to see if it can be simplified or if
1280 /// things it uses can be simplified by bit propagation. If so, return true.
1281 bool DAGCombiner::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
1282 const APInt
&DemandedElts
) {
1283 TargetLowering::TargetLoweringOpt
TLO(DAG
, LegalTypes
, LegalOperations
);
1285 if (!TLI
.SimplifyDemandedBits(Op
, DemandedBits
, DemandedElts
, Known
, TLO
))
1288 // Revisit the node.
1289 AddToWorklist(Op
.getNode());
1291 // Replace the old value with the new one.
1293 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO
.Old
.getNode()->dump(&DAG
);
1294 dbgs() << "\nWith: "; TLO
.New
.getNode()->dump(&DAG
);
1297 CommitTargetLoweringOpt(TLO
);
1301 /// Check the specified vector node value to see if it can be simplified or
1302 /// if things it uses can be simplified as it only uses some of the elements.
1303 /// If so, return true.
1304 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op
,
1305 const APInt
&DemandedElts
,
1306 bool AssumeSingleUse
) {
1307 TargetLowering::TargetLoweringOpt
TLO(DAG
, LegalTypes
, LegalOperations
);
1308 APInt KnownUndef
, KnownZero
;
1309 if (!TLI
.SimplifyDemandedVectorElts(Op
, DemandedElts
, KnownUndef
, KnownZero
,
1310 TLO
, 0, AssumeSingleUse
))
1313 // Revisit the node.
1314 AddToWorklist(Op
.getNode());
1316 // Replace the old value with the new one.
1318 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO
.Old
.getNode()->dump(&DAG
);
1319 dbgs() << "\nWith: "; TLO
.New
.getNode()->dump(&DAG
);
1322 CommitTargetLoweringOpt(TLO
);
1326 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode
*Load
, SDNode
*ExtLoad
) {
1328 EVT VT
= Load
->getValueType(0);
1329 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, SDValue(ExtLoad
, 0));
1331 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load
->dump(&DAG
); dbgs() << "\nWith: ";
1332 Trunc
.getNode()->dump(&DAG
); dbgs() << '\n');
1333 WorklistRemover
DeadNodes(*this);
1334 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 0), Trunc
);
1335 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 1), SDValue(ExtLoad
, 1));
1336 deleteAndRecombine(Load
);
1337 AddToWorklist(Trunc
.getNode());
1340 SDValue
DAGCombiner::PromoteOperand(SDValue Op
, EVT PVT
, bool &Replace
) {
1343 if (ISD::isUNINDEXEDLoad(Op
.getNode())) {
1344 LoadSDNode
*LD
= cast
<LoadSDNode
>(Op
);
1345 EVT MemVT
= LD
->getMemoryVT();
1346 ISD::LoadExtType ExtType
= ISD::isNON_EXTLoad(LD
) ? ISD::EXTLOAD
1347 : LD
->getExtensionType();
1349 return DAG
.getExtLoad(ExtType
, DL
, PVT
,
1350 LD
->getChain(), LD
->getBasePtr(),
1351 MemVT
, LD
->getMemOperand());
1354 unsigned Opc
= Op
.getOpcode();
1357 case ISD::AssertSext
:
1358 if (SDValue Op0
= SExtPromoteOperand(Op
.getOperand(0), PVT
))
1359 return DAG
.getNode(ISD::AssertSext
, DL
, PVT
, Op0
, Op
.getOperand(1));
1361 case ISD::AssertZext
:
1362 if (SDValue Op0
= ZExtPromoteOperand(Op
.getOperand(0), PVT
))
1363 return DAG
.getNode(ISD::AssertZext
, DL
, PVT
, Op0
, Op
.getOperand(1));
1365 case ISD::Constant
: {
1367 Op
.getValueType().isByteSized() ? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
1368 return DAG
.getNode(ExtOpc
, DL
, PVT
, Op
);
1372 if (!TLI
.isOperationLegal(ISD::ANY_EXTEND
, PVT
))
1374 return DAG
.getNode(ISD::ANY_EXTEND
, DL
, PVT
, Op
);
1377 SDValue
DAGCombiner::SExtPromoteOperand(SDValue Op
, EVT PVT
) {
1378 if (!TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
, PVT
))
1380 EVT OldVT
= Op
.getValueType();
1382 bool Replace
= false;
1383 SDValue NewOp
= PromoteOperand(Op
, PVT
, Replace
);
1384 if (!NewOp
.getNode())
1386 AddToWorklist(NewOp
.getNode());
1389 ReplaceLoadWithPromotedLoad(Op
.getNode(), NewOp
.getNode());
1390 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, DL
, NewOp
.getValueType(), NewOp
,
1391 DAG
.getValueType(OldVT
));
1394 SDValue
DAGCombiner::ZExtPromoteOperand(SDValue Op
, EVT PVT
) {
1395 EVT OldVT
= Op
.getValueType();
1397 bool Replace
= false;
1398 SDValue NewOp
= PromoteOperand(Op
, PVT
, Replace
);
1399 if (!NewOp
.getNode())
1401 AddToWorklist(NewOp
.getNode());
1404 ReplaceLoadWithPromotedLoad(Op
.getNode(), NewOp
.getNode());
1405 return DAG
.getZeroExtendInReg(NewOp
, DL
, OldVT
);
1408 /// Promote the specified integer binary operation if the target indicates it is
1409 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1410 /// i32 since i16 instructions are longer.
1411 SDValue
DAGCombiner::PromoteIntBinOp(SDValue Op
) {
1412 if (!LegalOperations
)
1415 EVT VT
= Op
.getValueType();
1416 if (VT
.isVector() || !VT
.isInteger())
1419 // If operation type is 'undesirable', e.g. i16 on x86, consider
1421 unsigned Opc
= Op
.getOpcode();
1422 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1426 // Consult target whether it is a good idea to promote this operation and
1427 // what's the right type to promote it to.
1428 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1429 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1431 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1433 bool Replace0
= false;
1434 SDValue N0
= Op
.getOperand(0);
1435 SDValue NN0
= PromoteOperand(N0
, PVT
, Replace0
);
1437 bool Replace1
= false;
1438 SDValue N1
= Op
.getOperand(1);
1439 SDValue NN1
= PromoteOperand(N1
, PVT
, Replace1
);
1443 DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, DAG
.getNode(Opc
, DL
, PVT
, NN0
, NN1
));
1445 // We are always replacing N0/N1's use in N and only need
1446 // additional replacements if there are additional uses.
1447 Replace0
&= !N0
->hasOneUse();
1448 Replace1
&= (N0
!= N1
) && !N1
->hasOneUse();
1450 // Combine Op here so it is preserved past replacements.
1451 CombineTo(Op
.getNode(), RV
);
1453 // If operands have a use ordering, make sure we deal with
1454 // predecessor first.
1455 if (Replace0
&& Replace1
&& N0
.getNode()->isPredecessorOf(N1
.getNode())) {
1457 std::swap(NN0
, NN1
);
1461 AddToWorklist(NN0
.getNode());
1462 ReplaceLoadWithPromotedLoad(N0
.getNode(), NN0
.getNode());
1465 AddToWorklist(NN1
.getNode());
1466 ReplaceLoadWithPromotedLoad(N1
.getNode(), NN1
.getNode());
1473 /// Promote the specified integer shift operation if the target indicates it is
1474 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1475 /// i32 since i16 instructions are longer.
1476 SDValue
DAGCombiner::PromoteIntShiftOp(SDValue Op
) {
1477 if (!LegalOperations
)
1480 EVT VT
= Op
.getValueType();
1481 if (VT
.isVector() || !VT
.isInteger())
1484 // If operation type is 'undesirable', e.g. i16 on x86, consider
1486 unsigned Opc
= Op
.getOpcode();
1487 if (TLI
.isTypeDesirableForOp(Opc
, 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!");
1496 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1498 bool Replace
= false;
1499 SDValue N0
= Op
.getOperand(0);
1500 SDValue N1
= Op
.getOperand(1);
1501 if (Opc
== ISD::SRA
)
1502 N0
= SExtPromoteOperand(N0
, PVT
);
1503 else if (Opc
== ISD::SRL
)
1504 N0
= ZExtPromoteOperand(N0
, PVT
);
1506 N0
= PromoteOperand(N0
, PVT
, Replace
);
1513 DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, DAG
.getNode(Opc
, DL
, PVT
, N0
, N1
));
1516 ReplaceLoadWithPromotedLoad(Op
.getOperand(0).getNode(), N0
.getNode());
1518 // Deal with Op being deleted.
1519 if (Op
&& Op
.getOpcode() != ISD::DELETED_NODE
)
1525 SDValue
DAGCombiner::PromoteExtend(SDValue Op
) {
1526 if (!LegalOperations
)
1529 EVT VT
= Op
.getValueType();
1530 if (VT
.isVector() || !VT
.isInteger())
1533 // If operation type is 'undesirable', e.g. i16 on x86, consider
1535 unsigned Opc
= Op
.getOpcode();
1536 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1540 // Consult target whether it is a good idea to promote this operation and
1541 // what's the right type to promote it to.
1542 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1543 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1544 // fold (aext (aext x)) -> (aext x)
1545 // fold (aext (zext x)) -> (zext x)
1546 // fold (aext (sext x)) -> (sext x)
1547 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1548 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), VT
, Op
.getOperand(0));
1553 bool DAGCombiner::PromoteLoad(SDValue Op
) {
1554 if (!LegalOperations
)
1557 if (!ISD::isUNINDEXEDLoad(Op
.getNode()))
1560 EVT VT
= Op
.getValueType();
1561 if (VT
.isVector() || !VT
.isInteger())
1564 // If operation type is 'undesirable', e.g. i16 on x86, consider
1566 unsigned Opc
= Op
.getOpcode();
1567 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1571 // Consult target whether it is a good idea to promote this operation and
1572 // what's the right type to promote it to.
1573 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1574 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1577 SDNode
*N
= Op
.getNode();
1578 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
1579 EVT MemVT
= LD
->getMemoryVT();
1580 ISD::LoadExtType ExtType
= ISD::isNON_EXTLoad(LD
) ? ISD::EXTLOAD
1581 : LD
->getExtensionType();
1582 SDValue NewLD
= DAG
.getExtLoad(ExtType
, DL
, PVT
,
1583 LD
->getChain(), LD
->getBasePtr(),
1584 MemVT
, LD
->getMemOperand());
1585 SDValue Result
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, NewLD
);
1587 LLVM_DEBUG(dbgs() << "\nPromoting "; N
->dump(&DAG
); dbgs() << "\nTo: ";
1588 Result
.getNode()->dump(&DAG
); dbgs() << '\n');
1589 WorklistRemover
DeadNodes(*this);
1590 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
);
1591 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), NewLD
.getValue(1));
1592 deleteAndRecombine(N
);
1593 AddToWorklist(Result
.getNode());
1599 /// Recursively delete a node which has no uses and any operands for
1600 /// which it is the only use.
1602 /// Note that this both deletes the nodes and removes them from the worklist.
1603 /// It also adds any nodes who have had a user deleted to the worklist as they
1604 /// may now have only one use and subject to other combines.
1605 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode
*N
) {
1606 if (!N
->use_empty())
1609 SmallSetVector
<SDNode
*, 16> Nodes
;
1612 N
= Nodes
.pop_back_val();
1616 if (N
->use_empty()) {
1617 for (const SDValue
&ChildN
: N
->op_values())
1618 Nodes
.insert(ChildN
.getNode());
1620 removeFromWorklist(N
);
1625 } while (!Nodes
.empty());
1629 //===----------------------------------------------------------------------===//
1630 // Main DAG Combiner implementation
1631 //===----------------------------------------------------------------------===//
1633 void DAGCombiner::Run(CombineLevel AtLevel
) {
1634 // set the instance variables, so that the various visit routines may use it.
1636 LegalOperations
= Level
>= AfterLegalizeVectorOps
;
1637 LegalTypes
= Level
>= AfterLegalizeTypes
;
1639 WorklistInserter
AddNodes(*this);
1641 // Add all the dag nodes to the worklist.
1642 for (SDNode
&Node
: DAG
.allnodes())
1643 AddToWorklist(&Node
);
1645 // Create a dummy node (which is not added to allnodes), that adds a reference
1646 // to the root node, preventing it from being deleted, and tracking any
1647 // changes of the root.
1648 HandleSDNode
Dummy(DAG
.getRoot());
1650 // While we have a valid worklist entry node, try to combine it.
1651 while (SDNode
*N
= getNextWorklistEntry()) {
1652 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1653 // N is deleted from the DAG, since they too may now be dead or may have a
1654 // reduced number of uses, allowing other xforms.
1655 if (recursivelyDeleteUnusedNodes(N
))
1658 WorklistRemover
DeadNodes(*this);
1660 // If this combine is running after legalizing the DAG, re-legalize any
1661 // nodes pulled off the worklist.
1662 if (Level
== AfterLegalizeDAG
) {
1663 SmallSetVector
<SDNode
*, 16> UpdatedNodes
;
1664 bool NIsValid
= DAG
.LegalizeOp(N
, UpdatedNodes
);
1666 for (SDNode
*LN
: UpdatedNodes
) {
1667 AddUsersToWorklist(LN
);
1674 LLVM_DEBUG(dbgs() << "\nCombining: "; N
->dump(&DAG
));
1676 // Add any operands of the new node which have not yet been combined to the
1677 // worklist as well. Because the worklist uniques things already, this
1678 // won't repeatedly process the same operand.
1679 CombinedNodes
.insert(N
);
1680 for (const SDValue
&ChildN
: N
->op_values())
1681 if (!CombinedNodes
.count(ChildN
.getNode()))
1682 AddToWorklist(ChildN
.getNode());
1684 SDValue RV
= combine(N
);
1691 // If we get back the same node we passed in, rather than a new node or
1692 // zero, we know that the node must have defined multiple values and
1693 // CombineTo was used. Since CombineTo takes care of the worklist
1694 // mechanics for us, we have no work to do in this case.
1695 if (RV
.getNode() == N
)
1698 assert(N
->getOpcode() != ISD::DELETED_NODE
&&
1699 RV
.getOpcode() != ISD::DELETED_NODE
&&
1700 "Node was deleted but visit returned new node!");
1702 LLVM_DEBUG(dbgs() << " ... into: "; RV
.getNode()->dump(&DAG
));
1704 if (N
->getNumValues() == RV
.getNode()->getNumValues())
1705 DAG
.ReplaceAllUsesWith(N
, RV
.getNode());
1707 assert(N
->getValueType(0) == RV
.getValueType() &&
1708 N
->getNumValues() == 1 && "Type mismatch");
1709 DAG
.ReplaceAllUsesWith(N
, &RV
);
1712 // Push the new node and any users onto the worklist
1713 AddToWorklist(RV
.getNode());
1714 AddUsersToWorklist(RV
.getNode());
1716 // Finally, if the node is now dead, remove it from the graph. The node
1717 // may not be dead if the replacement process recursively simplified to
1718 // something else needing this node. This will also take care of adding any
1719 // operands which have lost a user to the worklist.
1720 recursivelyDeleteUnusedNodes(N
);
1723 // If the root changed (e.g. it was a dead load, update the root).
1724 DAG
.setRoot(Dummy
.getValue());
1725 DAG
.RemoveDeadNodes();
1728 SDValue
DAGCombiner::visit(SDNode
*N
) {
1729 switch (N
->getOpcode()) {
1731 case ISD::TokenFactor
: return visitTokenFactor(N
);
1732 case ISD::MERGE_VALUES
: return visitMERGE_VALUES(N
);
1733 case ISD::ADD
: return visitADD(N
);
1734 case ISD::SUB
: return visitSUB(N
);
1736 case ISD::UADDSAT
: return visitADDSAT(N
);
1738 case ISD::USUBSAT
: return visitSUBSAT(N
);
1739 case ISD::ADDC
: return visitADDC(N
);
1741 case ISD::UADDO
: return visitADDO(N
);
1742 case ISD::SUBC
: return visitSUBC(N
);
1744 case ISD::USUBO
: return visitSUBO(N
);
1745 case ISD::ADDE
: return visitADDE(N
);
1746 case ISD::ADDCARRY
: return visitADDCARRY(N
);
1747 case ISD::SUBE
: return visitSUBE(N
);
1748 case ISD::SUBCARRY
: return visitSUBCARRY(N
);
1750 case ISD::SMULFIXSAT
:
1752 case ISD::UMULFIXSAT
: return visitMULFIX(N
);
1753 case ISD::MUL
: return visitMUL(N
);
1754 case ISD::SDIV
: return visitSDIV(N
);
1755 case ISD::UDIV
: return visitUDIV(N
);
1757 case ISD::UREM
: return visitREM(N
);
1758 case ISD::MULHU
: return visitMULHU(N
);
1759 case ISD::MULHS
: return visitMULHS(N
);
1760 case ISD::SMUL_LOHI
: return visitSMUL_LOHI(N
);
1761 case ISD::UMUL_LOHI
: return visitUMUL_LOHI(N
);
1763 case ISD::UMULO
: return visitMULO(N
);
1767 case ISD::UMAX
: return visitIMINMAX(N
);
1768 case ISD::AND
: return visitAND(N
);
1769 case ISD::OR
: return visitOR(N
);
1770 case ISD::XOR
: return visitXOR(N
);
1771 case ISD::SHL
: return visitSHL(N
);
1772 case ISD::SRA
: return visitSRA(N
);
1773 case ISD::SRL
: return visitSRL(N
);
1775 case ISD::ROTL
: return visitRotate(N
);
1777 case ISD::FSHR
: return visitFunnelShift(N
);
1778 case ISD::ABS
: return visitABS(N
);
1779 case ISD::BSWAP
: return visitBSWAP(N
);
1780 case ISD::BITREVERSE
: return visitBITREVERSE(N
);
1781 case ISD::CTLZ
: return visitCTLZ(N
);
1782 case ISD::CTLZ_ZERO_UNDEF
: return visitCTLZ_ZERO_UNDEF(N
);
1783 case ISD::CTTZ
: return visitCTTZ(N
);
1784 case ISD::CTTZ_ZERO_UNDEF
: return visitCTTZ_ZERO_UNDEF(N
);
1785 case ISD::CTPOP
: return visitCTPOP(N
);
1786 case ISD::SELECT
: return visitSELECT(N
);
1787 case ISD::VSELECT
: return visitVSELECT(N
);
1788 case ISD::SELECT_CC
: return visitSELECT_CC(N
);
1789 case ISD::SETCC
: return visitSETCC(N
);
1790 case ISD::SETCCCARRY
: return visitSETCCCARRY(N
);
1791 case ISD::SIGN_EXTEND
: return visitSIGN_EXTEND(N
);
1792 case ISD::ZERO_EXTEND
: return visitZERO_EXTEND(N
);
1793 case ISD::ANY_EXTEND
: return visitANY_EXTEND(N
);
1794 case ISD::AssertSext
:
1795 case ISD::AssertZext
: return visitAssertExt(N
);
1796 case ISD::SIGN_EXTEND_INREG
: return visitSIGN_EXTEND_INREG(N
);
1797 case ISD::SIGN_EXTEND_VECTOR_INREG
: return visitSIGN_EXTEND_VECTOR_INREG(N
);
1798 case ISD::ZERO_EXTEND_VECTOR_INREG
: return visitZERO_EXTEND_VECTOR_INREG(N
);
1799 case ISD::TRUNCATE
: return visitTRUNCATE(N
);
1800 case ISD::BITCAST
: return visitBITCAST(N
);
1801 case ISD::BUILD_PAIR
: return visitBUILD_PAIR(N
);
1802 case ISD::FADD
: return visitFADD(N
);
1803 case ISD::FSUB
: return visitFSUB(N
);
1804 case ISD::FMUL
: return visitFMUL(N
);
1805 case ISD::FMA
: return visitFMA(N
);
1806 case ISD::FDIV
: return visitFDIV(N
);
1807 case ISD::FREM
: return visitFREM(N
);
1808 case ISD::FSQRT
: return visitFSQRT(N
);
1809 case ISD::FCOPYSIGN
: return visitFCOPYSIGN(N
);
1810 case ISD::FPOW
: return visitFPOW(N
);
1811 case ISD::SINT_TO_FP
: return visitSINT_TO_FP(N
);
1812 case ISD::UINT_TO_FP
: return visitUINT_TO_FP(N
);
1813 case ISD::FP_TO_SINT
: return visitFP_TO_SINT(N
);
1814 case ISD::FP_TO_UINT
: return visitFP_TO_UINT(N
);
1815 case ISD::FP_ROUND
: return visitFP_ROUND(N
);
1816 case ISD::FP_EXTEND
: return visitFP_EXTEND(N
);
1817 case ISD::FNEG
: return visitFNEG(N
);
1818 case ISD::FABS
: return visitFABS(N
);
1819 case ISD::FFLOOR
: return visitFFLOOR(N
);
1820 case ISD::FMINNUM
: return visitFMINNUM(N
);
1821 case ISD::FMAXNUM
: return visitFMAXNUM(N
);
1822 case ISD::FMINIMUM
: return visitFMINIMUM(N
);
1823 case ISD::FMAXIMUM
: return visitFMAXIMUM(N
);
1824 case ISD::FCEIL
: return visitFCEIL(N
);
1825 case ISD::FTRUNC
: return visitFTRUNC(N
);
1826 case ISD::BRCOND
: return visitBRCOND(N
);
1827 case ISD::BR_CC
: return visitBR_CC(N
);
1828 case ISD::LOAD
: return visitLOAD(N
);
1829 case ISD::STORE
: return visitSTORE(N
);
1830 case ISD::INSERT_VECTOR_ELT
: return visitINSERT_VECTOR_ELT(N
);
1831 case ISD::EXTRACT_VECTOR_ELT
: return visitEXTRACT_VECTOR_ELT(N
);
1832 case ISD::BUILD_VECTOR
: return visitBUILD_VECTOR(N
);
1833 case ISD::CONCAT_VECTORS
: return visitCONCAT_VECTORS(N
);
1834 case ISD::EXTRACT_SUBVECTOR
: return visitEXTRACT_SUBVECTOR(N
);
1835 case ISD::VECTOR_SHUFFLE
: return visitVECTOR_SHUFFLE(N
);
1836 case ISD::SCALAR_TO_VECTOR
: return visitSCALAR_TO_VECTOR(N
);
1837 case ISD::INSERT_SUBVECTOR
: return visitINSERT_SUBVECTOR(N
);
1838 case ISD::MGATHER
: return visitMGATHER(N
);
1839 case ISD::MLOAD
: return visitMLOAD(N
);
1840 case ISD::MSCATTER
: return visitMSCATTER(N
);
1841 case ISD::MSTORE
: return visitMSTORE(N
);
1842 case ISD::LIFETIME_END
: return visitLIFETIME_END(N
);
1843 case ISD::FP_TO_FP16
: return visitFP_TO_FP16(N
);
1844 case ISD::FP16_TO_FP
: return visitFP16_TO_FP(N
);
1845 case ISD::VECREDUCE_FADD
:
1846 case ISD::VECREDUCE_FMUL
:
1847 case ISD::VECREDUCE_ADD
:
1848 case ISD::VECREDUCE_MUL
:
1849 case ISD::VECREDUCE_AND
:
1850 case ISD::VECREDUCE_OR
:
1851 case ISD::VECREDUCE_XOR
:
1852 case ISD::VECREDUCE_SMAX
:
1853 case ISD::VECREDUCE_SMIN
:
1854 case ISD::VECREDUCE_UMAX
:
1855 case ISD::VECREDUCE_UMIN
:
1856 case ISD::VECREDUCE_FMAX
:
1857 case ISD::VECREDUCE_FMIN
: return visitVECREDUCE(N
);
1862 SDValue
DAGCombiner::combine(SDNode
*N
) {
1863 SDValue RV
= visit(N
);
1865 // If nothing happened, try a target-specific DAG combine.
1866 if (!RV
.getNode()) {
1867 assert(N
->getOpcode() != ISD::DELETED_NODE
&&
1868 "Node was deleted but visit returned NULL!");
1870 if (N
->getOpcode() >= ISD::BUILTIN_OP_END
||
1871 TLI
.hasTargetDAGCombine((ISD::NodeType
)N
->getOpcode())) {
1873 // Expose the DAG combiner to the target combiner impls.
1874 TargetLowering::DAGCombinerInfo
1875 DagCombineInfo(DAG
, Level
, false, this);
1877 RV
= TLI
.PerformDAGCombine(N
, DagCombineInfo
);
1881 // If nothing happened still, try promoting the operation.
1882 if (!RV
.getNode()) {
1883 switch (N
->getOpcode()) {
1891 RV
= PromoteIntBinOp(SDValue(N
, 0));
1896 RV
= PromoteIntShiftOp(SDValue(N
, 0));
1898 case ISD::SIGN_EXTEND
:
1899 case ISD::ZERO_EXTEND
:
1900 case ISD::ANY_EXTEND
:
1901 RV
= PromoteExtend(SDValue(N
, 0));
1904 if (PromoteLoad(SDValue(N
, 0)))
1910 // If N is a commutative binary node, try to eliminate it if the commuted
1911 // version is already present in the DAG.
1912 if (!RV
.getNode() && TLI
.isCommutativeBinOp(N
->getOpcode()) &&
1913 N
->getNumValues() == 1) {
1914 SDValue N0
= N
->getOperand(0);
1915 SDValue N1
= N
->getOperand(1);
1917 // Constant operands are canonicalized to RHS.
1918 if (N0
!= N1
&& (isa
<ConstantSDNode
>(N0
) || !isa
<ConstantSDNode
>(N1
))) {
1919 SDValue Ops
[] = {N1
, N0
};
1920 SDNode
*CSENode
= DAG
.getNodeIfExists(N
->getOpcode(), N
->getVTList(), Ops
,
1923 return SDValue(CSENode
, 0);
1930 /// Given a node, return its input chain if it has one, otherwise return a null
1932 static SDValue
getInputChainForNode(SDNode
*N
) {
1933 if (unsigned NumOps
= N
->getNumOperands()) {
1934 if (N
->getOperand(0).getValueType() == MVT::Other
)
1935 return N
->getOperand(0);
1936 if (N
->getOperand(NumOps
-1).getValueType() == MVT::Other
)
1937 return N
->getOperand(NumOps
-1);
1938 for (unsigned i
= 1; i
< NumOps
-1; ++i
)
1939 if (N
->getOperand(i
).getValueType() == MVT::Other
)
1940 return N
->getOperand(i
);
1945 SDValue
DAGCombiner::visitTokenFactor(SDNode
*N
) {
1946 // If N has two operands, where one has an input chain equal to the other,
1947 // the 'other' chain is redundant.
1948 if (N
->getNumOperands() == 2) {
1949 if (getInputChainForNode(N
->getOperand(0).getNode()) == N
->getOperand(1))
1950 return N
->getOperand(0);
1951 if (getInputChainForNode(N
->getOperand(1).getNode()) == N
->getOperand(0))
1952 return N
->getOperand(1);
1955 // Don't simplify token factors if optnone.
1956 if (OptLevel
== CodeGenOpt::None
)
1959 // If the sole user is a token factor, we should make sure we have a
1960 // chance to merge them together. This prevents TF chains from inhibiting
1962 if (N
->hasOneUse() && N
->use_begin()->getOpcode() == ISD::TokenFactor
)
1963 AddToWorklist(*(N
->use_begin()));
1965 SmallVector
<SDNode
*, 8> TFs
; // List of token factors to visit.
1966 SmallVector
<SDValue
, 8> Ops
; // Ops for replacing token factor.
1967 SmallPtrSet
<SDNode
*, 16> SeenOps
;
1968 bool Changed
= false; // If we should replace this token factor.
1970 // Start out with this token factor.
1973 // Iterate through token factors. The TFs grows when new token factors are
1975 for (unsigned i
= 0; i
< TFs
.size(); ++i
) {
1976 // Limit number of nodes to inline, to avoid quadratic compile times.
1977 // We have to add the outstanding Token Factors to Ops, otherwise we might
1978 // drop Ops from the resulting Token Factors.
1979 if (Ops
.size() > TokenFactorInlineLimit
) {
1980 for (unsigned j
= i
; j
< TFs
.size(); j
++)
1981 Ops
.emplace_back(TFs
[j
], 0);
1982 // Drop unprocessed Token Factors from TFs, so we do not add them to the
1983 // combiner worklist later.
1988 SDNode
*TF
= TFs
[i
];
1989 // Check each of the operands.
1990 for (const SDValue
&Op
: TF
->op_values()) {
1991 switch (Op
.getOpcode()) {
1992 case ISD::EntryToken
:
1993 // Entry tokens don't need to be added to the list. They are
1998 case ISD::TokenFactor
:
1999 if (Op
.hasOneUse() && !is_contained(TFs
, Op
.getNode())) {
2000 // Queue up for processing.
2001 TFs
.push_back(Op
.getNode());
2008 // Only add if it isn't already in the list.
2009 if (SeenOps
.insert(Op
.getNode()).second
)
2018 // Re-visit inlined Token Factors, to clean them up in case they have been
2019 // removed. Skip the first Token Factor, as this is the current node.
2020 for (unsigned i
= 1, e
= TFs
.size(); i
< e
; i
++)
2021 AddToWorklist(TFs
[i
]);
2023 // Remove Nodes that are chained to another node in the list. Do so
2024 // by walking up chains breath-first stopping when we've seen
2025 // another operand. In general we must climb to the EntryNode, but we can exit
2026 // early if we find all remaining work is associated with just one operand as
2027 // no further pruning is possible.
2029 // List of nodes to search through and original Ops from which they originate.
2030 SmallVector
<std::pair
<SDNode
*, unsigned>, 8> Worklist
;
2031 SmallVector
<unsigned, 8> OpWorkCount
; // Count of work for each Op.
2032 SmallPtrSet
<SDNode
*, 16> SeenChains
;
2033 bool DidPruneOps
= false;
2035 unsigned NumLeftToConsider
= 0;
2036 for (const SDValue
&Op
: Ops
) {
2037 Worklist
.push_back(std::make_pair(Op
.getNode(), NumLeftToConsider
++));
2038 OpWorkCount
.push_back(1);
2041 auto AddToWorklist
= [&](unsigned CurIdx
, SDNode
*Op
, unsigned OpNumber
) {
2042 // If this is an Op, we can remove the op from the list. Remark any
2043 // search associated with it as from the current OpNumber.
2044 if (SeenOps
.count(Op
) != 0) {
2047 unsigned OrigOpNumber
= 0;
2048 while (OrigOpNumber
< Ops
.size() && Ops
[OrigOpNumber
].getNode() != Op
)
2050 assert((OrigOpNumber
!= Ops
.size()) &&
2051 "expected to find TokenFactor Operand");
2052 // Re-mark worklist from OrigOpNumber to OpNumber
2053 for (unsigned i
= CurIdx
+ 1; i
< Worklist
.size(); ++i
) {
2054 if (Worklist
[i
].second
== OrigOpNumber
) {
2055 Worklist
[i
].second
= OpNumber
;
2058 OpWorkCount
[OpNumber
] += OpWorkCount
[OrigOpNumber
];
2059 OpWorkCount
[OrigOpNumber
] = 0;
2060 NumLeftToConsider
--;
2062 // Add if it's a new chain
2063 if (SeenChains
.insert(Op
).second
) {
2064 OpWorkCount
[OpNumber
]++;
2065 Worklist
.push_back(std::make_pair(Op
, OpNumber
));
2069 for (unsigned i
= 0; i
< Worklist
.size() && i
< 1024; ++i
) {
2070 // We need at least be consider at least 2 Ops to prune.
2071 if (NumLeftToConsider
<= 1)
2073 auto CurNode
= Worklist
[i
].first
;
2074 auto CurOpNumber
= Worklist
[i
].second
;
2075 assert((OpWorkCount
[CurOpNumber
] > 0) &&
2076 "Node should not appear in worklist");
2077 switch (CurNode
->getOpcode()) {
2078 case ISD::EntryToken
:
2079 // Hitting EntryToken is the only way for the search to terminate without
2081 // another operand's search. Prevent us from marking this operand
2083 NumLeftToConsider
++;
2085 case ISD::TokenFactor
:
2086 for (const SDValue
&Op
: CurNode
->op_values())
2087 AddToWorklist(i
, Op
.getNode(), CurOpNumber
);
2089 case ISD::LIFETIME_START
:
2090 case ISD::LIFETIME_END
:
2091 case ISD::CopyFromReg
:
2092 case ISD::CopyToReg
:
2093 AddToWorklist(i
, CurNode
->getOperand(0).getNode(), CurOpNumber
);
2096 if (auto *MemNode
= dyn_cast
<MemSDNode
>(CurNode
))
2097 AddToWorklist(i
, MemNode
->getChain().getNode(), CurOpNumber
);
2100 OpWorkCount
[CurOpNumber
]--;
2101 if (OpWorkCount
[CurOpNumber
] == 0)
2102 NumLeftToConsider
--;
2105 // If we've changed things around then replace token factor.
2109 // The entry token is the only possible outcome.
2110 Result
= DAG
.getEntryNode();
2113 SmallVector
<SDValue
, 8> PrunedOps
;
2115 for (const SDValue
&Op
: Ops
) {
2116 if (SeenChains
.count(Op
.getNode()) == 0)
2117 PrunedOps
.push_back(Op
);
2119 Result
= DAG
.getTokenFactor(SDLoc(N
), PrunedOps
);
2121 Result
= DAG
.getTokenFactor(SDLoc(N
), Ops
);
2129 /// MERGE_VALUES can always be eliminated.
2130 SDValue
DAGCombiner::visitMERGE_VALUES(SDNode
*N
) {
2131 WorklistRemover
DeadNodes(*this);
2132 // Replacing results may cause a different MERGE_VALUES to suddenly
2133 // be CSE'd with N, and carry its uses with it. Iterate until no
2134 // uses remain, to ensure that the node can be safely deleted.
2135 // First add the users of this node to the work list so that they
2136 // can be tried again once they have new operands.
2137 AddUsersToWorklist(N
);
2139 // Do as a single replacement to avoid rewalking use lists.
2140 SmallVector
<SDValue
, 8> Ops
;
2141 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
)
2142 Ops
.push_back(N
->getOperand(i
));
2143 DAG
.ReplaceAllUsesWith(N
, Ops
.data());
2144 } while (!N
->use_empty());
2145 deleteAndRecombine(N
);
2146 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
2149 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2150 /// ConstantSDNode pointer else nullptr.
2151 static ConstantSDNode
*getAsNonOpaqueConstant(SDValue N
) {
2152 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(N
);
2153 return Const
!= nullptr && !Const
->isOpaque() ? Const
: nullptr;
2156 SDValue
DAGCombiner::foldBinOpIntoSelect(SDNode
*BO
) {
2157 assert(TLI
.isBinOp(BO
->getOpcode()) && BO
->getNumValues() == 1 &&
2158 "Unexpected binary operator");
2160 // Don't do this unless the old select is going away. We want to eliminate the
2161 // binary operator, not replace a binop with a select.
2162 // TODO: Handle ISD::SELECT_CC.
2163 unsigned SelOpNo
= 0;
2164 SDValue Sel
= BO
->getOperand(0);
2165 if (Sel
.getOpcode() != ISD::SELECT
|| !Sel
.hasOneUse()) {
2167 Sel
= BO
->getOperand(1);
2170 if (Sel
.getOpcode() != ISD::SELECT
|| !Sel
.hasOneUse())
2173 SDValue CT
= Sel
.getOperand(1);
2174 if (!isConstantOrConstantVector(CT
, true) &&
2175 !isConstantFPBuildVectorOrConstantFP(CT
))
2178 SDValue CF
= Sel
.getOperand(2);
2179 if (!isConstantOrConstantVector(CF
, true) &&
2180 !isConstantFPBuildVectorOrConstantFP(CF
))
2183 // Bail out if any constants are opaque because we can't constant fold those.
2184 // The exception is "and" and "or" with either 0 or -1 in which case we can
2185 // propagate non constant operands into select. I.e.:
2186 // and (select Cond, 0, -1), X --> select Cond, 0, X
2187 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2188 auto BinOpcode
= BO
->getOpcode();
2189 bool CanFoldNonConst
=
2190 (BinOpcode
== ISD::AND
|| BinOpcode
== ISD::OR
) &&
2191 (isNullOrNullSplat(CT
) || isAllOnesOrAllOnesSplat(CT
)) &&
2192 (isNullOrNullSplat(CF
) || isAllOnesOrAllOnesSplat(CF
));
2194 SDValue CBO
= BO
->getOperand(SelOpNo
^ 1);
2195 if (!CanFoldNonConst
&&
2196 !isConstantOrConstantVector(CBO
, true) &&
2197 !isConstantFPBuildVectorOrConstantFP(CBO
))
2200 EVT VT
= Sel
.getValueType();
2202 // In case of shift value and shift amount may have different VT. For instance
2203 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
2204 // swapped operands and value types do not match. NB: x86 is fine if operands
2205 // are not swapped with shift amount VT being not bigger than shifted value.
2206 // TODO: that is possible to check for a shift operation, correct VTs and
2207 // still perform optimization on x86 if needed.
2208 if (SelOpNo
&& VT
!= CBO
.getValueType())
2211 // We have a select-of-constants followed by a binary operator with a
2212 // constant. Eliminate the binop by pulling the constant math into the select.
2213 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2215 SDValue NewCT
= SelOpNo
? DAG
.getNode(BinOpcode
, DL
, VT
, CBO
, CT
)
2216 : DAG
.getNode(BinOpcode
, DL
, VT
, CT
, CBO
);
2217 if (!CanFoldNonConst
&& !NewCT
.isUndef() &&
2218 !isConstantOrConstantVector(NewCT
, true) &&
2219 !isConstantFPBuildVectorOrConstantFP(NewCT
))
2222 SDValue NewCF
= SelOpNo
? DAG
.getNode(BinOpcode
, DL
, VT
, CBO
, CF
)
2223 : DAG
.getNode(BinOpcode
, DL
, VT
, CF
, CBO
);
2224 if (!CanFoldNonConst
&& !NewCF
.isUndef() &&
2225 !isConstantOrConstantVector(NewCF
, true) &&
2226 !isConstantFPBuildVectorOrConstantFP(NewCF
))
2229 SDValue SelectOp
= DAG
.getSelect(DL
, VT
, Sel
.getOperand(0), NewCT
, NewCF
);
2230 SelectOp
->setFlags(BO
->getFlags());
2234 static SDValue
foldAddSubBoolOfMaskedVal(SDNode
*N
, SelectionDAG
&DAG
) {
2235 assert((N
->getOpcode() == ISD::ADD
|| N
->getOpcode() == ISD::SUB
) &&
2236 "Expecting add or sub");
2238 // Match a constant operand and a zext operand for the math instruction:
2241 bool IsAdd
= N
->getOpcode() == ISD::ADD
;
2242 SDValue C
= IsAdd
? N
->getOperand(1) : N
->getOperand(0);
2243 SDValue Z
= IsAdd
? N
->getOperand(0) : N
->getOperand(1);
2244 auto *CN
= dyn_cast
<ConstantSDNode
>(C
);
2245 if (!CN
|| Z
.getOpcode() != ISD::ZERO_EXTEND
)
2248 // Match the zext operand as a setcc of a boolean.
2249 if (Z
.getOperand(0).getOpcode() != ISD::SETCC
||
2250 Z
.getOperand(0).getValueType() != MVT::i1
)
2253 // Match the compare as: setcc (X & 1), 0, eq.
2254 SDValue SetCC
= Z
.getOperand(0);
2255 ISD::CondCode CC
= cast
<CondCodeSDNode
>(SetCC
->getOperand(2))->get();
2256 if (CC
!= ISD::SETEQ
|| !isNullConstant(SetCC
.getOperand(1)) ||
2257 SetCC
.getOperand(0).getOpcode() != ISD::AND
||
2258 !isOneConstant(SetCC
.getOperand(0).getOperand(1)))
2261 // We are adding/subtracting a constant and an inverted low bit. Turn that
2262 // into a subtract/add of the low bit with incremented/decremented constant:
2263 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2264 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2265 EVT VT
= C
.getValueType();
2267 SDValue LowBit
= DAG
.getZExtOrTrunc(SetCC
.getOperand(0), DL
, VT
);
2268 SDValue C1
= IsAdd
? DAG
.getConstant(CN
->getAPIntValue() + 1, DL
, VT
) :
2269 DAG
.getConstant(CN
->getAPIntValue() - 1, DL
, VT
);
2270 return DAG
.getNode(IsAdd
? ISD::SUB
: ISD::ADD
, DL
, VT
, C1
, LowBit
);
2273 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2274 /// a shift and add with a different constant.
2275 static SDValue
foldAddSubOfSignBit(SDNode
*N
, SelectionDAG
&DAG
) {
2276 assert((N
->getOpcode() == ISD::ADD
|| N
->getOpcode() == ISD::SUB
) &&
2277 "Expecting add or sub");
2279 // We need a constant operand for the add/sub, and the other operand is a
2280 // logical shift right: add (srl), C or sub C, (srl).
2281 // TODO - support non-uniform vector amounts.
2282 bool IsAdd
= N
->getOpcode() == ISD::ADD
;
2283 SDValue ConstantOp
= IsAdd
? N
->getOperand(1) : N
->getOperand(0);
2284 SDValue ShiftOp
= IsAdd
? N
->getOperand(0) : N
->getOperand(1);
2285 ConstantSDNode
*C
= isConstOrConstSplat(ConstantOp
);
2286 if (!C
|| ShiftOp
.getOpcode() != ISD::SRL
)
2289 // The shift must be of a 'not' value.
2290 SDValue Not
= ShiftOp
.getOperand(0);
2291 if (!Not
.hasOneUse() || !isBitwiseNot(Not
))
2294 // The shift must be moving the sign bit to the least-significant-bit.
2295 EVT VT
= ShiftOp
.getValueType();
2296 SDValue ShAmt
= ShiftOp
.getOperand(1);
2297 ConstantSDNode
*ShAmtC
= isConstOrConstSplat(ShAmt
);
2298 if (!ShAmtC
|| ShAmtC
->getAPIntValue() != (VT
.getScalarSizeInBits() - 1))
2301 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2302 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2303 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2305 auto ShOpcode
= IsAdd
? ISD::SRA
: ISD::SRL
;
2306 SDValue NewShift
= DAG
.getNode(ShOpcode
, DL
, VT
, Not
.getOperand(0), ShAmt
);
2307 APInt NewC
= IsAdd
? C
->getAPIntValue() + 1 : C
->getAPIntValue() - 1;
2308 return DAG
.getNode(ISD::ADD
, DL
, VT
, NewShift
, DAG
.getConstant(NewC
, DL
, VT
));
2311 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2312 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2313 /// are no common bits set in the operands).
2314 SDValue
DAGCombiner::visitADDLike(SDNode
*N
) {
2315 SDValue N0
= N
->getOperand(0);
2316 SDValue N1
= N
->getOperand(1);
2317 EVT VT
= N0
.getValueType();
2321 if (VT
.isVector()) {
2322 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
2325 // fold (add x, 0) -> x, vector edition
2326 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
2328 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
2332 // fold (add x, undef) -> undef
2339 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
2340 // canonicalize constant to RHS
2341 if (!DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2342 return DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, N0
);
2343 // fold (add c1, c2) -> c1+c2
2344 return DAG
.FoldConstantArithmetic(ISD::ADD
, DL
, VT
, N0
.getNode(),
2348 // fold (add x, 0) -> x
2349 if (isNullConstant(N1
))
2352 if (isConstantOrConstantVector(N1
, /* NoOpaque */ true)) {
2353 // fold ((A-c1)+c2) -> (A+(c2-c1))
2354 if (N0
.getOpcode() == ISD::SUB
&&
2355 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaque */ true)) {
2356 SDValue Sub
= DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N1
.getNode(),
2357 N0
.getOperand(1).getNode());
2358 assert(Sub
&& "Constant folding failed");
2359 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), Sub
);
2362 // fold ((c1-A)+c2) -> (c1+c2)-A
2363 if (N0
.getOpcode() == ISD::SUB
&&
2364 isConstantOrConstantVector(N0
.getOperand(0), /* NoOpaque */ true)) {
2365 SDValue Add
= DAG
.FoldConstantArithmetic(ISD::ADD
, DL
, VT
, N1
.getNode(),
2366 N0
.getOperand(0).getNode());
2367 assert(Add
&& "Constant folding failed");
2368 return DAG
.getNode(ISD::SUB
, DL
, VT
, Add
, N0
.getOperand(1));
2371 // add (sext i1 X), 1 -> zext (not i1 X)
2372 // We don't transform this pattern:
2373 // add (zext i1 X), -1 -> sext (not i1 X)
2374 // because most (?) targets generate better code for the zext form.
2375 if (N0
.getOpcode() == ISD::SIGN_EXTEND
&& N0
.hasOneUse() &&
2376 isOneOrOneSplat(N1
)) {
2377 SDValue X
= N0
.getOperand(0);
2378 if ((!LegalOperations
||
2379 (TLI
.isOperationLegal(ISD::XOR
, X
.getValueType()) &&
2380 TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
))) &&
2381 X
.getScalarValueSizeInBits() == 1) {
2382 SDValue Not
= DAG
.getNOT(DL
, X
, X
.getValueType());
2383 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Not
);
2387 // Undo the add -> or combine to merge constant offsets from a frame index.
2388 if (N0
.getOpcode() == ISD::OR
&&
2389 isa
<FrameIndexSDNode
>(N0
.getOperand(0)) &&
2390 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
2391 DAG
.haveNoCommonBitsSet(N0
.getOperand(0), N0
.getOperand(1))) {
2392 SDValue Add0
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, N0
.getOperand(1));
2393 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), Add0
);
2397 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
2401 if (!reassociationCanBreakAddressingModePattern(ISD::ADD
, DL
, N0
, N1
)) {
2402 if (SDValue RADD
= reassociateOps(ISD::ADD
, DL
, N0
, N1
, N
->getFlags()))
2405 // fold ((0-A) + B) -> B-A
2406 if (N0
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N0
.getOperand(0)))
2407 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, N0
.getOperand(1));
2409 // fold (A + (0-B)) -> A-B
2410 if (N1
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N1
.getOperand(0)))
2411 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
.getOperand(1));
2413 // fold (A+(B-A)) -> B
2414 if (N1
.getOpcode() == ISD::SUB
&& N0
== N1
.getOperand(1))
2415 return N1
.getOperand(0);
2417 // fold ((B-A)+A) -> B
2418 if (N0
.getOpcode() == ISD::SUB
&& N1
== N0
.getOperand(1))
2419 return N0
.getOperand(0);
2421 // fold ((A-B)+(C-A)) -> (C-B)
2422 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
&&
2423 N0
.getOperand(0) == N1
.getOperand(1))
2424 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2427 // fold ((A-B)+(B-C)) -> (A-C)
2428 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
&&
2429 N0
.getOperand(1) == N1
.getOperand(0))
2430 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0),
2433 // fold (A+(B-(A+C))) to (B-C)
2434 if (N1
.getOpcode() == ISD::SUB
&& N1
.getOperand(1).getOpcode() == ISD::ADD
&&
2435 N0
== N1
.getOperand(1).getOperand(0))
2436 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2437 N1
.getOperand(1).getOperand(1));
2439 // fold (A+(B-(C+A))) to (B-C)
2440 if (N1
.getOpcode() == ISD::SUB
&& N1
.getOperand(1).getOpcode() == ISD::ADD
&&
2441 N0
== N1
.getOperand(1).getOperand(1))
2442 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2443 N1
.getOperand(1).getOperand(0));
2445 // fold (A+((B-A)+or-C)) to (B+or-C)
2446 if ((N1
.getOpcode() == ISD::SUB
|| N1
.getOpcode() == ISD::ADD
) &&
2447 N1
.getOperand(0).getOpcode() == ISD::SUB
&&
2448 N0
== N1
.getOperand(0).getOperand(1))
2449 return DAG
.getNode(N1
.getOpcode(), DL
, VT
, N1
.getOperand(0).getOperand(0),
2452 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2453 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
) {
2454 SDValue N00
= N0
.getOperand(0);
2455 SDValue N01
= N0
.getOperand(1);
2456 SDValue N10
= N1
.getOperand(0);
2457 SDValue N11
= N1
.getOperand(1);
2459 if (isConstantOrConstantVector(N00
) || isConstantOrConstantVector(N10
))
2460 return DAG
.getNode(ISD::SUB
, DL
, VT
,
2461 DAG
.getNode(ISD::ADD
, SDLoc(N0
), VT
, N00
, N10
),
2462 DAG
.getNode(ISD::ADD
, SDLoc(N1
), VT
, N01
, N11
));
2465 // fold (add (umax X, C), -C) --> (usubsat X, C)
2466 if (N0
.getOpcode() == ISD::UMAX
&& hasOperation(ISD::USUBSAT
, VT
)) {
2467 auto MatchUSUBSAT
= [](ConstantSDNode
*Max
, ConstantSDNode
*Op
) {
2468 return (!Max
&& !Op
) ||
2469 (Max
&& Op
&& Max
->getAPIntValue() == (-Op
->getAPIntValue()));
2471 if (ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchUSUBSAT
,
2472 /*AllowUndefs*/ true))
2473 return DAG
.getNode(ISD::USUBSAT
, DL
, VT
, N0
.getOperand(0),
2477 if (SimplifyDemandedBits(SDValue(N
, 0)))
2478 return SDValue(N
, 0);
2480 if (isOneOrOneSplat(N1
)) {
2481 // fold (add (xor a, -1), 1) -> (sub 0, a)
2482 if (isBitwiseNot(N0
))
2483 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
),
2486 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2487 if (N0
.getOpcode() == ISD::ADD
||
2488 N0
.getOpcode() == ISD::UADDO
||
2489 N0
.getOpcode() == ISD::SADDO
) {
2492 if (isBitwiseNot(N0
.getOperand(0))) {
2493 A
= N0
.getOperand(1);
2494 Xor
= N0
.getOperand(0);
2495 } else if (isBitwiseNot(N0
.getOperand(1))) {
2496 A
= N0
.getOperand(0);
2497 Xor
= N0
.getOperand(1);
2501 return DAG
.getNode(ISD::SUB
, DL
, VT
, A
, Xor
.getOperand(0));
2505 // add (add x, y), 1
2506 // And if the target does not like this form then turn into:
2507 // sub y, (xor x, -1)
2508 if (!TLI
.preferIncOfAddToSubOfNot(VT
) && N0
.hasOneUse() &&
2509 N0
.getOpcode() == ISD::ADD
) {
2510 SDValue Not
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(0),
2511 DAG
.getAllOnesConstant(DL
, VT
));
2512 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(1), Not
);
2516 // (x - y) + -1 -> add (xor y, -1), x
2517 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2518 isAllOnesOrAllOnesSplat(N1
)) {
2519 SDValue Xor
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(1), N1
);
2520 return DAG
.getNode(ISD::ADD
, DL
, VT
, Xor
, N0
.getOperand(0));
2523 if (SDValue Combined
= visitADDLikeCommutative(N0
, N1
, N
))
2526 if (SDValue Combined
= visitADDLikeCommutative(N1
, N0
, N
))
2532 SDValue
DAGCombiner::visitADD(SDNode
*N
) {
2533 SDValue N0
= N
->getOperand(0);
2534 SDValue N1
= N
->getOperand(1);
2535 EVT VT
= N0
.getValueType();
2538 if (SDValue Combined
= visitADDLike(N
))
2541 if (SDValue V
= foldAddSubBoolOfMaskedVal(N
, DAG
))
2544 if (SDValue V
= foldAddSubOfSignBit(N
, DAG
))
2547 // fold (a+b) -> (a|b) iff a and b share no bits.
2548 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::OR
, VT
)) &&
2549 DAG
.haveNoCommonBitsSet(N0
, N1
))
2550 return DAG
.getNode(ISD::OR
, DL
, VT
, N0
, N1
);
2555 SDValue
DAGCombiner::visitADDSAT(SDNode
*N
) {
2556 unsigned Opcode
= N
->getOpcode();
2557 SDValue N0
= N
->getOperand(0);
2558 SDValue N1
= N
->getOperand(1);
2559 EVT VT
= N0
.getValueType();
2563 if (VT
.isVector()) {
2564 // TODO SimplifyVBinOp
2566 // fold (add_sat x, 0) -> x, vector edition
2567 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
2569 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
2573 // fold (add_sat x, undef) -> -1
2574 if (N0
.isUndef() || N1
.isUndef())
2575 return DAG
.getAllOnesConstant(DL
, VT
);
2577 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
2578 // canonicalize constant to RHS
2579 if (!DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2580 return DAG
.getNode(Opcode
, DL
, VT
, N1
, N0
);
2581 // fold (add_sat c1, c2) -> c3
2582 return DAG
.FoldConstantArithmetic(Opcode
, DL
, VT
, N0
.getNode(),
2586 // fold (add_sat x, 0) -> x
2587 if (isNullConstant(N1
))
2590 // If it cannot overflow, transform into an add.
2591 if (Opcode
== ISD::UADDSAT
)
2592 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2593 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
);
2598 static SDValue
getAsCarry(const TargetLowering
&TLI
, SDValue V
) {
2599 bool Masked
= false;
2601 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2603 if (V
.getOpcode() == ISD::TRUNCATE
|| V
.getOpcode() == ISD::ZERO_EXTEND
) {
2604 V
= V
.getOperand(0);
2608 if (V
.getOpcode() == ISD::AND
&& isOneConstant(V
.getOperand(1))) {
2610 V
= V
.getOperand(0);
2617 // If this is not a carry, return.
2618 if (V
.getResNo() != 1)
2621 if (V
.getOpcode() != ISD::ADDCARRY
&& V
.getOpcode() != ISD::SUBCARRY
&&
2622 V
.getOpcode() != ISD::UADDO
&& V
.getOpcode() != ISD::USUBO
)
2625 EVT VT
= V
.getNode()->getValueType(0);
2626 if (!TLI
.isOperationLegalOrCustom(V
.getOpcode(), VT
))
2629 // If the result is masked, then no matter what kind of bool it is we can
2630 // return. If it isn't, then we need to make sure the bool type is either 0 or
2631 // 1 and not other values.
2633 TLI
.getBooleanContents(V
.getValueType()) ==
2634 TargetLoweringBase::ZeroOrOneBooleanContent
)
2640 /// Given the operands of an add/sub operation, see if the 2nd operand is a
2641 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2642 /// the opcode and bypass the mask operation.
2643 static SDValue
foldAddSubMasked1(bool IsAdd
, SDValue N0
, SDValue N1
,
2644 SelectionDAG
&DAG
, const SDLoc
&DL
) {
2645 if (N1
.getOpcode() != ISD::AND
|| !isOneOrOneSplat(N1
->getOperand(1)))
2648 EVT VT
= N0
.getValueType();
2649 if (DAG
.ComputeNumSignBits(N1
.getOperand(0)) != VT
.getScalarSizeInBits())
2652 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2653 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2654 return DAG
.getNode(IsAdd
? ISD::SUB
: ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(0));
2657 /// Helper for doing combines based on N0 and N1 being added to each other.
2658 SDValue
DAGCombiner::visitADDLikeCommutative(SDValue N0
, SDValue N1
,
2659 SDNode
*LocReference
) {
2660 EVT VT
= N0
.getValueType();
2661 SDLoc
DL(LocReference
);
2663 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2664 if (N1
.getOpcode() == ISD::SHL
&& N1
.getOperand(0).getOpcode() == ISD::SUB
&&
2665 isNullOrNullSplat(N1
.getOperand(0).getOperand(0)))
2666 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
,
2667 DAG
.getNode(ISD::SHL
, DL
, VT
,
2668 N1
.getOperand(0).getOperand(1),
2671 if (SDValue V
= foldAddSubMasked1(true, N0
, N1
, DAG
, DL
))
2675 // add (add x, 1), y
2676 // And if the target does not like this form then turn into:
2677 // sub y, (xor x, -1)
2678 if (!TLI
.preferIncOfAddToSubOfNot(VT
) && N0
.hasOneUse() &&
2679 N0
.getOpcode() == ISD::ADD
&& isOneOrOneSplat(N0
.getOperand(1))) {
2680 SDValue Not
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(0),
2681 DAG
.getAllOnesConstant(DL
, VT
));
2682 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, Not
);
2685 // Hoist one-use subtraction by non-opaque constant:
2686 // (x - C) + y -> (x + y) - C
2687 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2688 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2689 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
2690 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), N1
);
2691 return DAG
.getNode(ISD::SUB
, DL
, VT
, Add
, N0
.getOperand(1));
2693 // Hoist one-use subtraction from non-opaque constant:
2694 // (C - x) + y -> (y - x) + C
2695 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2696 isConstantOrConstantVector(N0
.getOperand(0), /*NoOpaques=*/true)) {
2697 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, N0
.getOperand(1));
2698 return DAG
.getNode(ISD::ADD
, DL
, VT
, Sub
, N0
.getOperand(0));
2701 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2702 // rather than 'add 0/-1' (the zext should get folded).
2703 // add (sext i1 Y), X --> sub X, (zext i1 Y)
2704 if (N0
.getOpcode() == ISD::SIGN_EXTEND
&&
2705 N0
.getOperand(0).getScalarValueSizeInBits() == 1 &&
2706 TLI
.getBooleanContents(VT
) == TargetLowering::ZeroOrOneBooleanContent
) {
2707 SDValue ZExt
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
.getOperand(0));
2708 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, ZExt
);
2711 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2712 if (N1
.getOpcode() == ISD::SIGN_EXTEND_INREG
) {
2713 VTSDNode
*TN
= cast
<VTSDNode
>(N1
.getOperand(1));
2714 if (TN
->getVT() == MVT::i1
) {
2715 SDValue ZExt
= DAG
.getNode(ISD::AND
, DL
, VT
, N1
.getOperand(0),
2716 DAG
.getConstant(1, DL
, VT
));
2717 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, ZExt
);
2721 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2722 if (N1
.getOpcode() == ISD::ADDCARRY
&& isNullConstant(N1
.getOperand(1)) &&
2724 return DAG
.getNode(ISD::ADDCARRY
, DL
, N1
->getVTList(),
2725 N0
, N1
.getOperand(0), N1
.getOperand(2));
2727 // (add X, Carry) -> (addcarry X, 0, Carry)
2728 if (TLI
.isOperationLegalOrCustom(ISD::ADDCARRY
, VT
))
2729 if (SDValue Carry
= getAsCarry(TLI
, N1
))
2730 return DAG
.getNode(ISD::ADDCARRY
, DL
,
2731 DAG
.getVTList(VT
, Carry
.getValueType()), N0
,
2732 DAG
.getConstant(0, DL
, VT
), Carry
);
2737 SDValue
DAGCombiner::visitADDC(SDNode
*N
) {
2738 SDValue N0
= N
->getOperand(0);
2739 SDValue N1
= N
->getOperand(1);
2740 EVT VT
= N0
.getValueType();
2743 // If the flag result is dead, turn this into an ADD.
2744 if (!N
->hasAnyUseOfValue(1))
2745 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2746 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
2748 // canonicalize constant to RHS.
2749 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2750 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2752 return DAG
.getNode(ISD::ADDC
, DL
, N
->getVTList(), N1
, N0
);
2754 // fold (addc x, 0) -> x + no carry out
2755 if (isNullConstant(N1
))
2756 return CombineTo(N
, N0
, DAG
.getNode(ISD::CARRY_FALSE
,
2759 // If it cannot overflow, transform into an add.
2760 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2761 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2762 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
2767 static SDValue
flipBoolean(SDValue V
, const SDLoc
&DL
,
2768 SelectionDAG
&DAG
, const TargetLowering
&TLI
) {
2769 EVT VT
= V
.getValueType();
2772 switch (TLI
.getBooleanContents(VT
)) {
2773 case TargetLowering::ZeroOrOneBooleanContent
:
2774 case TargetLowering::UndefinedBooleanContent
:
2775 Cst
= DAG
.getConstant(1, DL
, VT
);
2777 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2778 Cst
= DAG
.getAllOnesConstant(DL
, VT
);
2782 return DAG
.getNode(ISD::XOR
, DL
, VT
, V
, Cst
);
2786 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2787 * then the flip also occurs if computing the inverse is the same cost.
2788 * This function returns an empty SDValue in case it cannot flip the boolean
2789 * without increasing the cost of the computation. If you want to flip a boolean
2790 * no matter what, use flipBoolean.
2792 static SDValue
extractBooleanFlip(SDValue V
, SelectionDAG
&DAG
,
2793 const TargetLowering
&TLI
,
2795 if (Force
&& isa
<ConstantSDNode
>(V
))
2796 return flipBoolean(V
, SDLoc(V
), DAG
, TLI
);
2798 if (V
.getOpcode() != ISD::XOR
)
2801 ConstantSDNode
*Const
= isConstOrConstSplat(V
.getOperand(1), false);
2805 EVT VT
= V
.getValueType();
2807 bool IsFlip
= false;
2808 switch(TLI
.getBooleanContents(VT
)) {
2809 case TargetLowering::ZeroOrOneBooleanContent
:
2810 IsFlip
= Const
->isOne();
2812 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2813 IsFlip
= Const
->isAllOnesValue();
2815 case TargetLowering::UndefinedBooleanContent
:
2816 IsFlip
= (Const
->getAPIntValue() & 0x01) == 1;
2821 return V
.getOperand(0);
2823 return flipBoolean(V
, SDLoc(V
), DAG
, TLI
);
2827 SDValue
DAGCombiner::visitADDO(SDNode
*N
) {
2828 SDValue N0
= N
->getOperand(0);
2829 SDValue N1
= N
->getOperand(1);
2830 EVT VT
= N0
.getValueType();
2831 bool IsSigned
= (ISD::SADDO
== N
->getOpcode());
2833 EVT CarryVT
= N
->getValueType(1);
2836 // If the flag result is dead, turn this into an ADD.
2837 if (!N
->hasAnyUseOfValue(1))
2838 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2839 DAG
.getUNDEF(CarryVT
));
2841 // canonicalize constant to RHS.
2842 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
2843 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2844 return DAG
.getNode(N
->getOpcode(), DL
, N
->getVTList(), N1
, N0
);
2846 // fold (addo x, 0) -> x + no carry out
2847 if (isNullOrNullSplat(N1
))
2848 return CombineTo(N
, N0
, DAG
.getConstant(0, DL
, CarryVT
));
2851 // If it cannot overflow, transform into an add.
2852 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2853 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2854 DAG
.getConstant(0, DL
, CarryVT
));
2856 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2857 if (isBitwiseNot(N0
) && isOneOrOneSplat(N1
)) {
2858 SDValue Sub
= DAG
.getNode(ISD::USUBO
, DL
, N
->getVTList(),
2859 DAG
.getConstant(0, DL
, VT
), N0
.getOperand(0));
2860 return CombineTo(N
, Sub
,
2861 flipBoolean(Sub
.getValue(1), DL
, DAG
, TLI
));
2864 if (SDValue Combined
= visitUADDOLike(N0
, N1
, N
))
2867 if (SDValue Combined
= visitUADDOLike(N1
, N0
, N
))
2874 SDValue
DAGCombiner::visitUADDOLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
2875 EVT VT
= N0
.getValueType();
2879 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2880 // If Y + 1 cannot overflow.
2881 if (N1
.getOpcode() == ISD::ADDCARRY
&& isNullConstant(N1
.getOperand(1))) {
2882 SDValue Y
= N1
.getOperand(0);
2883 SDValue One
= DAG
.getConstant(1, SDLoc(N
), Y
.getValueType());
2884 if (DAG
.computeOverflowKind(Y
, One
) == SelectionDAG::OFK_Never
)
2885 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(), N0
, Y
,
2889 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2890 if (TLI
.isOperationLegalOrCustom(ISD::ADDCARRY
, VT
))
2891 if (SDValue Carry
= getAsCarry(TLI
, N1
))
2892 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(), N0
,
2893 DAG
.getConstant(0, SDLoc(N
), VT
), Carry
);
2898 SDValue
DAGCombiner::visitADDE(SDNode
*N
) {
2899 SDValue N0
= N
->getOperand(0);
2900 SDValue N1
= N
->getOperand(1);
2901 SDValue CarryIn
= N
->getOperand(2);
2903 // canonicalize constant to RHS
2904 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2905 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2907 return DAG
.getNode(ISD::ADDE
, SDLoc(N
), N
->getVTList(),
2910 // fold (adde x, y, false) -> (addc x, y)
2911 if (CarryIn
.getOpcode() == ISD::CARRY_FALSE
)
2912 return DAG
.getNode(ISD::ADDC
, SDLoc(N
), N
->getVTList(), N0
, N1
);
2917 SDValue
DAGCombiner::visitADDCARRY(SDNode
*N
) {
2918 SDValue N0
= N
->getOperand(0);
2919 SDValue N1
= N
->getOperand(1);
2920 SDValue CarryIn
= N
->getOperand(2);
2923 // canonicalize constant to RHS
2924 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2925 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2927 return DAG
.getNode(ISD::ADDCARRY
, DL
, N
->getVTList(), N1
, N0
, CarryIn
);
2929 // fold (addcarry x, y, false) -> (uaddo x, y)
2930 if (isNullConstant(CarryIn
)) {
2931 if (!LegalOperations
||
2932 TLI
.isOperationLegalOrCustom(ISD::UADDO
, N
->getValueType(0)))
2933 return DAG
.getNode(ISD::UADDO
, DL
, N
->getVTList(), N0
, N1
);
2936 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2937 if (isNullConstant(N0
) && isNullConstant(N1
)) {
2938 EVT VT
= N0
.getValueType();
2939 EVT CarryVT
= CarryIn
.getValueType();
2940 SDValue CarryExt
= DAG
.getBoolExtOrTrunc(CarryIn
, DL
, VT
, CarryVT
);
2941 AddToWorklist(CarryExt
.getNode());
2942 return CombineTo(N
, DAG
.getNode(ISD::AND
, DL
, VT
, CarryExt
,
2943 DAG
.getConstant(1, DL
, VT
)),
2944 DAG
.getConstant(0, DL
, CarryVT
));
2947 if (SDValue Combined
= visitADDCARRYLike(N0
, N1
, CarryIn
, N
))
2950 if (SDValue Combined
= visitADDCARRYLike(N1
, N0
, CarryIn
, N
))
2957 * If we are facing some sort of diamond carry propapagtion pattern try to
2958 * break it up to generate something like:
2959 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2961 * The end result is usually an increase in operation required, but because the
2962 * carry is now linearized, other tranforms can kick in and optimize the DAG.
2964 * Patterns typically look something like
2969 * | (addcarry *, 0, Z)
2973 * (addcarry X, *, *)
2975 * But numerous variation exist. Our goal is to identify A, B, X and Z and
2976 * produce a combine with a single path for carry propagation.
2978 static SDValue
combineADDCARRYDiamond(DAGCombiner
&Combiner
, SelectionDAG
&DAG
,
2979 SDValue X
, SDValue Carry0
, SDValue Carry1
,
2981 if (Carry1
.getResNo() != 1 || Carry0
.getResNo() != 1)
2983 if (Carry1
.getOpcode() != ISD::UADDO
)
2989 * First look for a suitable Z. It will present itself in the form of
2990 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2992 if (Carry0
.getOpcode() == ISD::ADDCARRY
&&
2993 isNullConstant(Carry0
.getOperand(1))) {
2994 Z
= Carry0
.getOperand(2);
2995 } else if (Carry0
.getOpcode() == ISD::UADDO
&&
2996 isOneConstant(Carry0
.getOperand(1))) {
2997 EVT VT
= Combiner
.getSetCCResultType(Carry0
.getValueType());
2998 Z
= DAG
.getConstant(1, SDLoc(Carry0
.getOperand(1)), VT
);
3000 // We couldn't find a suitable Z.
3005 auto cancelDiamond
= [&](SDValue A
,SDValue B
) {
3007 SDValue NewY
= DAG
.getNode(ISD::ADDCARRY
, DL
, Carry0
->getVTList(), A
, B
, Z
);
3008 Combiner
.AddToWorklist(NewY
.getNode());
3009 return DAG
.getNode(ISD::ADDCARRY
, DL
, N
->getVTList(), X
,
3010 DAG
.getConstant(0, DL
, X
.getValueType()),
3019 * (addcarry *, 0, Z)
3021 if (Carry0
.getOperand(0) == Carry1
.getValue(0)) {
3022 return cancelDiamond(Carry1
.getOperand(0), Carry1
.getOperand(1));
3026 * (addcarry A, 0, Z)
3032 if (Carry1
.getOperand(0) == Carry0
.getValue(0)) {
3033 return cancelDiamond(Carry0
.getOperand(0), Carry1
.getOperand(1));
3036 if (Carry1
.getOperand(1) == Carry0
.getValue(0)) {
3037 return cancelDiamond(Carry1
.getOperand(0), Carry0
.getOperand(0));
3043 SDValue
DAGCombiner::visitADDCARRYLike(SDValue N0
, SDValue N1
, SDValue CarryIn
,
3045 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
3046 if (isBitwiseNot(N0
))
3047 if (SDValue NotC
= extractBooleanFlip(CarryIn
, DAG
, TLI
, true)) {
3049 SDValue Sub
= DAG
.getNode(ISD::SUBCARRY
, DL
, N
->getVTList(), N1
,
3050 N0
.getOperand(0), NotC
);
3051 return CombineTo(N
, Sub
,
3052 flipBoolean(Sub
.getValue(1), DL
, DAG
, TLI
));
3055 // Iff the flag result is dead:
3056 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
3057 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3058 // or the dependency between the instructions.
3059 if ((N0
.getOpcode() == ISD::ADD
||
3060 (N0
.getOpcode() == ISD::UADDO
&& N0
.getResNo() == 0 &&
3061 N0
.getValue(1) != CarryIn
)) &&
3062 isNullConstant(N1
) && !N
->hasAnyUseOfValue(1))
3063 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(),
3064 N0
.getOperand(0), N0
.getOperand(1), CarryIn
);
3067 * When one of the addcarry argument is itself a carry, we may be facing
3068 * a diamond carry propagation. In which case we try to transform the DAG
3069 * to ensure linear carry propagation if that is possible.
3071 if (auto Y
= getAsCarry(TLI
, N1
)) {
3072 // Because both are carries, Y and Z can be swapped.
3073 if (auto R
= combineADDCARRYDiamond(*this, DAG
, N0
, Y
, CarryIn
, N
))
3075 if (auto R
= combineADDCARRYDiamond(*this, DAG
, N0
, CarryIn
, Y
, N
))
3082 // Since it may not be valid to emit a fold to zero for vector initializers
3083 // check if we can before folding.
3084 static SDValue
tryFoldToZero(const SDLoc
&DL
, const TargetLowering
&TLI
, EVT VT
,
3085 SelectionDAG
&DAG
, bool LegalOperations
) {
3087 return DAG
.getConstant(0, DL
, VT
);
3088 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
3089 return DAG
.getConstant(0, DL
, VT
);
3093 SDValue
DAGCombiner::visitSUB(SDNode
*N
) {
3094 SDValue N0
= N
->getOperand(0);
3095 SDValue N1
= N
->getOperand(1);
3096 EVT VT
= N0
.getValueType();
3100 if (VT
.isVector()) {
3101 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3104 // fold (sub x, 0) -> x, vector edition
3105 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
3109 // fold (sub x, x) -> 0
3110 // FIXME: Refactor this and xor and other similar operations together.
3112 return tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
3113 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3114 DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
3115 // fold (sub c1, c2) -> c1-c2
3116 return DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N0
.getNode(),
3120 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3123 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
3125 // fold (sub x, c) -> (add x, -c)
3127 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
,
3128 DAG
.getConstant(-N1C
->getAPIntValue(), DL
, VT
));
3131 if (isNullOrNullSplat(N0
)) {
3132 unsigned BitWidth
= VT
.getScalarSizeInBits();
3133 // Right-shifting everything out but the sign bit followed by negation is
3134 // the same as flipping arithmetic/logical shift type without the negation:
3135 // -(X >>u 31) -> (X >>s 31)
3136 // -(X >>s 31) -> (X >>u 31)
3137 if (N1
->getOpcode() == ISD::SRA
|| N1
->getOpcode() == ISD::SRL
) {
3138 ConstantSDNode
*ShiftAmt
= isConstOrConstSplat(N1
.getOperand(1));
3139 if (ShiftAmt
&& ShiftAmt
->getAPIntValue() == (BitWidth
- 1)) {
3140 auto NewSh
= N1
->getOpcode() == ISD::SRA
? ISD::SRL
: ISD::SRA
;
3141 if (!LegalOperations
|| TLI
.isOperationLegal(NewSh
, VT
))
3142 return DAG
.getNode(NewSh
, DL
, VT
, N1
.getOperand(0), N1
.getOperand(1));
3146 // 0 - X --> 0 if the sub is NUW.
3147 if (N
->getFlags().hasNoUnsignedWrap())
3150 if (DAG
.MaskedValueIsZero(N1
, ~APInt::getSignMask(BitWidth
))) {
3151 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3152 // N1 must be 0 because negating the minimum signed value is undefined.
3153 if (N
->getFlags().hasNoSignedWrap())
3156 // 0 - X --> X if X is 0 or the minimum signed value.
3161 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3162 if (isAllOnesOrAllOnesSplat(N0
))
3163 return DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
);
3165 // fold (A - (0-B)) -> A+B
3166 if (N1
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N1
.getOperand(0)))
3167 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(1));
3169 // fold A-(A-B) -> B
3170 if (N1
.getOpcode() == ISD::SUB
&& N0
== N1
.getOperand(0))
3171 return N1
.getOperand(1);
3173 // fold (A+B)-A -> B
3174 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(0) == N1
)
3175 return N0
.getOperand(1);
3177 // fold (A+B)-B -> A
3178 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1) == N1
)
3179 return N0
.getOperand(0);
3181 // fold (A+C1)-C2 -> A+(C1-C2)
3182 if (N0
.getOpcode() == ISD::ADD
&&
3183 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3184 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3185 SDValue NewC
= DAG
.FoldConstantArithmetic(
3186 ISD::SUB
, DL
, VT
, N0
.getOperand(1).getNode(), N1
.getNode());
3187 assert(NewC
&& "Constant folding failed");
3188 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), NewC
);
3191 // fold C2-(A+C1) -> (C2-C1)-A
3192 if (N1
.getOpcode() == ISD::ADD
) {
3193 SDValue N11
= N1
.getOperand(1);
3194 if (isConstantOrConstantVector(N0
, /* NoOpaques */ true) &&
3195 isConstantOrConstantVector(N11
, /* NoOpaques */ true)) {
3196 SDValue NewC
= DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N0
.getNode(),
3198 assert(NewC
&& "Constant folding failed");
3199 return DAG
.getNode(ISD::SUB
, DL
, VT
, NewC
, N1
.getOperand(0));
3203 // fold (A-C1)-C2 -> A-(C1+C2)
3204 if (N0
.getOpcode() == ISD::SUB
&&
3205 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3206 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3207 SDValue NewC
= DAG
.FoldConstantArithmetic(
3208 ISD::ADD
, DL
, VT
, N0
.getOperand(1).getNode(), N1
.getNode());
3209 assert(NewC
&& "Constant folding failed");
3210 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), NewC
);
3213 // fold (c1-A)-c2 -> (c1-c2)-A
3214 if (N0
.getOpcode() == ISD::SUB
&&
3215 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3216 isConstantOrConstantVector(N0
.getOperand(0), /* NoOpaques */ true)) {
3217 SDValue NewC
= DAG
.FoldConstantArithmetic(
3218 ISD::SUB
, DL
, VT
, N0
.getOperand(0).getNode(), N1
.getNode());
3219 assert(NewC
&& "Constant folding failed");
3220 return DAG
.getNode(ISD::SUB
, DL
, VT
, NewC
, N0
.getOperand(1));
3223 // fold ((A+(B+or-C))-B) -> A+or-C
3224 if (N0
.getOpcode() == ISD::ADD
&&
3225 (N0
.getOperand(1).getOpcode() == ISD::SUB
||
3226 N0
.getOperand(1).getOpcode() == ISD::ADD
) &&
3227 N0
.getOperand(1).getOperand(0) == N1
)
3228 return DAG
.getNode(N0
.getOperand(1).getOpcode(), DL
, VT
, N0
.getOperand(0),
3229 N0
.getOperand(1).getOperand(1));
3231 // fold ((A+(C+B))-B) -> A+C
3232 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1).getOpcode() == ISD::ADD
&&
3233 N0
.getOperand(1).getOperand(1) == N1
)
3234 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0),
3235 N0
.getOperand(1).getOperand(0));
3237 // fold ((A-(B-C))-C) -> A-B
3238 if (N0
.getOpcode() == ISD::SUB
&& N0
.getOperand(1).getOpcode() == ISD::SUB
&&
3239 N0
.getOperand(1).getOperand(1) == N1
)
3240 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0),
3241 N0
.getOperand(1).getOperand(0));
3243 // fold (A-(B-C)) -> A+(C-B)
3244 if (N1
.getOpcode() == ISD::SUB
&& N1
.hasOneUse())
3245 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
,
3246 DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(1),
3249 // fold (X - (-Y * Z)) -> (X + (Y * Z))
3250 if (N1
.getOpcode() == ISD::MUL
&& N1
.hasOneUse()) {
3251 if (N1
.getOperand(0).getOpcode() == ISD::SUB
&&
3252 isNullOrNullSplat(N1
.getOperand(0).getOperand(0))) {
3253 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
,
3254 N1
.getOperand(0).getOperand(1),
3256 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Mul
);
3258 if (N1
.getOperand(1).getOpcode() == ISD::SUB
&&
3259 isNullOrNullSplat(N1
.getOperand(1).getOperand(0))) {
3260 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
,
3262 N1
.getOperand(1).getOperand(1));
3263 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Mul
);
3267 // If either operand of a sub is undef, the result is undef
3273 if (SDValue V
= foldAddSubBoolOfMaskedVal(N
, DAG
))
3276 if (SDValue V
= foldAddSubOfSignBit(N
, DAG
))
3279 if (SDValue V
= foldAddSubMasked1(false, N0
, N1
, DAG
, SDLoc(N
)))
3282 // (x - y) - 1 -> add (xor y, -1), x
3283 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&& isOneOrOneSplat(N1
)) {
3284 SDValue Xor
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(1),
3285 DAG
.getAllOnesConstant(DL
, VT
));
3286 return DAG
.getNode(ISD::ADD
, DL
, VT
, Xor
, N0
.getOperand(0));
3290 // sub y, (xor x, -1)
3291 // And if the target does not like this form then turn into:
3292 // add (add x, y), 1
3293 if (TLI
.preferIncOfAddToSubOfNot(VT
) && N1
.hasOneUse() && isBitwiseNot(N1
)) {
3294 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(0));
3295 return DAG
.getNode(ISD::ADD
, DL
, VT
, Add
, DAG
.getConstant(1, DL
, VT
));
3298 // Hoist one-use addition by non-opaque constant:
3299 // (x + C) - y -> (x - y) + C
3300 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::ADD
&&
3301 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
3302 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), N1
);
3303 return DAG
.getNode(ISD::ADD
, DL
, VT
, Sub
, N0
.getOperand(1));
3305 // y - (x + C) -> (y - x) - C
3306 if (N1
.hasOneUse() && N1
.getOpcode() == ISD::ADD
&&
3307 isConstantOrConstantVector(N1
.getOperand(1), /*NoOpaques=*/true)) {
3308 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
.getOperand(0));
3309 return DAG
.getNode(ISD::SUB
, DL
, VT
, Sub
, N1
.getOperand(1));
3311 // (x - C) - y -> (x - y) - C
3312 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3313 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
3314 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
3315 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), N1
);
3316 return DAG
.getNode(ISD::SUB
, DL
, VT
, Sub
, N0
.getOperand(1));
3318 // (C - x) - y -> C - (x + y)
3319 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
3320 isConstantOrConstantVector(N0
.getOperand(0), /*NoOpaques=*/true)) {
3321 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(1), N1
);
3322 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), Add
);
3325 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3326 // rather than 'sub 0/1' (the sext should get folded).
3327 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3328 if (N1
.getOpcode() == ISD::ZERO_EXTEND
&&
3329 N1
.getOperand(0).getScalarValueSizeInBits() == 1 &&
3330 TLI
.getBooleanContents(VT
) ==
3331 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
3332 SDValue SExt
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, N1
.getOperand(0));
3333 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, SExt
);
3336 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3337 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
)) {
3338 if (N0
.getOpcode() == ISD::XOR
&& N1
.getOpcode() == ISD::SRA
) {
3339 SDValue X0
= N0
.getOperand(0), X1
= N0
.getOperand(1);
3340 SDValue S0
= N1
.getOperand(0);
3341 if ((X0
== S0
&& X1
== N1
) || (X0
== N1
&& X1
== S0
)) {
3342 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
3343 if (ConstantSDNode
*C
= isConstOrConstSplat(N1
.getOperand(1)))
3344 if (C
->getAPIntValue() == (OpSizeInBits
- 1))
3345 return DAG
.getNode(ISD::ABS
, SDLoc(N
), VT
, S0
);
3350 // If the relocation model supports it, consider symbol offsets.
3351 if (GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(N0
))
3352 if (!LegalOperations
&& TLI
.isOffsetFoldingLegal(GA
)) {
3353 // fold (sub Sym, c) -> Sym-c
3354 if (N1C
&& GA
->getOpcode() == ISD::GlobalAddress
)
3355 return DAG
.getGlobalAddress(GA
->getGlobal(), SDLoc(N1C
), VT
,
3357 (uint64_t)N1C
->getSExtValue());
3358 // fold (sub Sym+c1, Sym+c2) -> c1-c2
3359 if (GlobalAddressSDNode
*GB
= dyn_cast
<GlobalAddressSDNode
>(N1
))
3360 if (GA
->getGlobal() == GB
->getGlobal())
3361 return DAG
.getConstant((uint64_t)GA
->getOffset() - GB
->getOffset(),
3365 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3366 if (N1
.getOpcode() == ISD::SIGN_EXTEND_INREG
) {
3367 VTSDNode
*TN
= cast
<VTSDNode
>(N1
.getOperand(1));
3368 if (TN
->getVT() == MVT::i1
) {
3369 SDValue ZExt
= DAG
.getNode(ISD::AND
, DL
, VT
, N1
.getOperand(0),
3370 DAG
.getConstant(1, DL
, VT
));
3371 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, ZExt
);
3375 // Prefer an add for more folding potential and possibly better codegen:
3376 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3377 if (!LegalOperations
&& N1
.getOpcode() == ISD::SRL
&& N1
.hasOneUse()) {
3378 SDValue ShAmt
= N1
.getOperand(1);
3379 ConstantSDNode
*ShAmtC
= isConstOrConstSplat(ShAmt
);
3381 ShAmtC
->getAPIntValue() == (N1
.getScalarValueSizeInBits() - 1)) {
3382 SDValue SRA
= DAG
.getNode(ISD::SRA
, DL
, VT
, N1
.getOperand(0), ShAmt
);
3383 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, SRA
);
3390 SDValue
DAGCombiner::visitSUBSAT(SDNode
*N
) {
3391 SDValue N0
= N
->getOperand(0);
3392 SDValue N1
= N
->getOperand(1);
3393 EVT VT
= N0
.getValueType();
3397 if (VT
.isVector()) {
3398 // TODO SimplifyVBinOp
3400 // fold (sub_sat x, 0) -> x, vector edition
3401 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
3405 // fold (sub_sat x, undef) -> 0
3406 if (N0
.isUndef() || N1
.isUndef())
3407 return DAG
.getConstant(0, DL
, VT
);
3409 // fold (sub_sat x, x) -> 0
3411 return DAG
.getConstant(0, DL
, VT
);
3413 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3414 DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
3415 // fold (sub_sat c1, c2) -> c3
3416 return DAG
.FoldConstantArithmetic(N
->getOpcode(), DL
, VT
, N0
.getNode(),
3420 // fold (sub_sat x, 0) -> x
3421 if (isNullConstant(N1
))
3427 SDValue
DAGCombiner::visitSUBC(SDNode
*N
) {
3428 SDValue N0
= N
->getOperand(0);
3429 SDValue N1
= N
->getOperand(1);
3430 EVT VT
= N0
.getValueType();
3433 // If the flag result is dead, turn this into an SUB.
3434 if (!N
->hasAnyUseOfValue(1))
3435 return CombineTo(N
, DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
),
3436 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3438 // fold (subc x, x) -> 0 + no borrow
3440 return CombineTo(N
, DAG
.getConstant(0, DL
, VT
),
3441 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3443 // fold (subc x, 0) -> x + no borrow
3444 if (isNullConstant(N1
))
3445 return CombineTo(N
, N0
, DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3447 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3448 if (isAllOnesConstant(N0
))
3449 return CombineTo(N
, DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
),
3450 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3455 SDValue
DAGCombiner::visitSUBO(SDNode
*N
) {
3456 SDValue N0
= N
->getOperand(0);
3457 SDValue N1
= N
->getOperand(1);
3458 EVT VT
= N0
.getValueType();
3459 bool IsSigned
= (ISD::SSUBO
== N
->getOpcode());
3461 EVT CarryVT
= N
->getValueType(1);
3464 // If the flag result is dead, turn this into an SUB.
3465 if (!N
->hasAnyUseOfValue(1))
3466 return CombineTo(N
, DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
),
3467 DAG
.getUNDEF(CarryVT
));
3469 // fold (subo x, x) -> 0 + no borrow
3471 return CombineTo(N
, DAG
.getConstant(0, DL
, VT
),
3472 DAG
.getConstant(0, DL
, CarryVT
));
3474 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
3476 // fold (subox, c) -> (addo x, -c)
3477 if (IsSigned
&& N1C
&& !N1C
->getAPIntValue().isMinSignedValue()) {
3478 return DAG
.getNode(ISD::SADDO
, DL
, N
->getVTList(), N0
,
3479 DAG
.getConstant(-N1C
->getAPIntValue(), DL
, VT
));
3482 // fold (subo x, 0) -> x + no borrow
3483 if (isNullOrNullSplat(N1
))
3484 return CombineTo(N
, N0
, DAG
.getConstant(0, DL
, CarryVT
));
3486 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3487 if (!IsSigned
&& isAllOnesOrAllOnesSplat(N0
))
3488 return CombineTo(N
, DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
),
3489 DAG
.getConstant(0, DL
, CarryVT
));
3494 SDValue
DAGCombiner::visitSUBE(SDNode
*N
) {
3495 SDValue N0
= N
->getOperand(0);
3496 SDValue N1
= N
->getOperand(1);
3497 SDValue CarryIn
= N
->getOperand(2);
3499 // fold (sube x, y, false) -> (subc x, y)
3500 if (CarryIn
.getOpcode() == ISD::CARRY_FALSE
)
3501 return DAG
.getNode(ISD::SUBC
, SDLoc(N
), N
->getVTList(), N0
, N1
);
3506 SDValue
DAGCombiner::visitSUBCARRY(SDNode
*N
) {
3507 SDValue N0
= N
->getOperand(0);
3508 SDValue N1
= N
->getOperand(1);
3509 SDValue CarryIn
= N
->getOperand(2);
3511 // fold (subcarry x, y, false) -> (usubo x, y)
3512 if (isNullConstant(CarryIn
)) {
3513 if (!LegalOperations
||
3514 TLI
.isOperationLegalOrCustom(ISD::USUBO
, N
->getValueType(0)))
3515 return DAG
.getNode(ISD::USUBO
, SDLoc(N
), N
->getVTList(), N0
, N1
);
3521 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
3523 SDValue
DAGCombiner::visitMULFIX(SDNode
*N
) {
3524 SDValue N0
= N
->getOperand(0);
3525 SDValue N1
= N
->getOperand(1);
3526 SDValue Scale
= N
->getOperand(2);
3527 EVT VT
= N0
.getValueType();
3529 // fold (mulfix x, undef, scale) -> 0
3530 if (N0
.isUndef() || N1
.isUndef())
3531 return DAG
.getConstant(0, SDLoc(N
), VT
);
3533 // Canonicalize constant to RHS (vector doesn't have to splat)
3534 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3535 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
3536 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
, Scale
);
3538 // fold (mulfix x, 0, scale) -> 0
3539 if (isNullConstant(N1
))
3540 return DAG
.getConstant(0, SDLoc(N
), VT
);
3545 SDValue
DAGCombiner::visitMUL(SDNode
*N
) {
3546 SDValue N0
= N
->getOperand(0);
3547 SDValue N1
= N
->getOperand(1);
3548 EVT VT
= N0
.getValueType();
3550 // fold (mul x, undef) -> 0
3551 if (N0
.isUndef() || N1
.isUndef())
3552 return DAG
.getConstant(0, SDLoc(N
), VT
);
3554 bool N0IsConst
= false;
3555 bool N1IsConst
= false;
3556 bool N1IsOpaqueConst
= false;
3557 bool N0IsOpaqueConst
= false;
3558 APInt ConstValue0
, ConstValue1
;
3560 if (VT
.isVector()) {
3561 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3564 N0IsConst
= ISD::isConstantSplatVector(N0
.getNode(), ConstValue0
);
3565 N1IsConst
= ISD::isConstantSplatVector(N1
.getNode(), ConstValue1
);
3566 assert((!N0IsConst
||
3567 ConstValue0
.getBitWidth() == VT
.getScalarSizeInBits()) &&
3568 "Splat APInt should be element width");
3569 assert((!N1IsConst
||
3570 ConstValue1
.getBitWidth() == VT
.getScalarSizeInBits()) &&
3571 "Splat APInt should be element width");
3573 N0IsConst
= isa
<ConstantSDNode
>(N0
);
3575 ConstValue0
= cast
<ConstantSDNode
>(N0
)->getAPIntValue();
3576 N0IsOpaqueConst
= cast
<ConstantSDNode
>(N0
)->isOpaque();
3578 N1IsConst
= isa
<ConstantSDNode
>(N1
);
3580 ConstValue1
= cast
<ConstantSDNode
>(N1
)->getAPIntValue();
3581 N1IsOpaqueConst
= cast
<ConstantSDNode
>(N1
)->isOpaque();
3585 // fold (mul c1, c2) -> c1*c2
3586 if (N0IsConst
&& N1IsConst
&& !N0IsOpaqueConst
&& !N1IsOpaqueConst
)
3587 return DAG
.FoldConstantArithmetic(ISD::MUL
, SDLoc(N
), VT
,
3588 N0
.getNode(), N1
.getNode());
3590 // canonicalize constant to RHS (vector doesn't have to splat)
3591 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3592 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
3593 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N1
, N0
);
3594 // fold (mul x, 0) -> 0
3595 if (N1IsConst
&& ConstValue1
.isNullValue())
3597 // fold (mul x, 1) -> x
3598 if (N1IsConst
&& ConstValue1
.isOneValue())
3601 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3604 // fold (mul x, -1) -> 0-x
3605 if (N1IsConst
&& ConstValue1
.isAllOnesValue()) {
3607 return DAG
.getNode(ISD::SUB
, DL
, VT
,
3608 DAG
.getConstant(0, DL
, VT
), N0
);
3610 // fold (mul x, (1 << c)) -> x << c
3611 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
3612 DAG
.isKnownToBeAPowerOfTwo(N1
) &&
3613 (!VT
.isVector() || Level
<= AfterLegalizeVectorOps
)) {
3615 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
3616 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
3617 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ShiftVT
);
3618 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
, Trunc
);
3620 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3621 if (N1IsConst
&& !N1IsOpaqueConst
&& (-ConstValue1
).isPowerOf2()) {
3622 unsigned Log2Val
= (-ConstValue1
).logBase2();
3624 // FIXME: If the input is something that is easily negated (e.g. a
3625 // single-use add), we should put the negate there.
3626 return DAG
.getNode(ISD::SUB
, DL
, VT
,
3627 DAG
.getConstant(0, DL
, VT
),
3628 DAG
.getNode(ISD::SHL
, DL
, VT
, N0
,
3629 DAG
.getConstant(Log2Val
, DL
,
3630 getShiftAmountTy(N0
.getValueType()))));
3633 // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3634 // mul x, (2^N + 1) --> add (shl x, N), x
3635 // mul x, (2^N - 1) --> sub (shl x, N), x
3636 // Examples: x * 33 --> (x << 5) + x
3637 // x * 15 --> (x << 4) - x
3638 // x * -33 --> -((x << 5) + x)
3639 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3640 if (N1IsConst
&& TLI
.decomposeMulByConstant(*DAG
.getContext(), VT
, N1
)) {
3641 // TODO: We could handle more general decomposition of any constant by
3642 // having the target set a limit on number of ops and making a
3643 // callback to determine that sequence (similar to sqrt expansion).
3644 unsigned MathOp
= ISD::DELETED_NODE
;
3645 APInt MulC
= ConstValue1
.abs();
3646 if ((MulC
- 1).isPowerOf2())
3648 else if ((MulC
+ 1).isPowerOf2())
3651 if (MathOp
!= ISD::DELETED_NODE
) {
3653 MathOp
== ISD::ADD
? (MulC
- 1).logBase2() : (MulC
+ 1).logBase2();
3654 assert(ShAmt
< VT
.getScalarSizeInBits() &&
3655 "multiply-by-constant generated out of bounds shift");
3658 DAG
.getNode(ISD::SHL
, DL
, VT
, N0
, DAG
.getConstant(ShAmt
, DL
, VT
));
3659 SDValue R
= DAG
.getNode(MathOp
, DL
, VT
, Shl
, N0
);
3660 if (ConstValue1
.isNegative())
3661 R
= DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), R
);
3666 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3667 if (N0
.getOpcode() == ISD::SHL
&&
3668 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3669 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3670 SDValue C3
= DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N1
, N0
.getOperand(1));
3671 if (isConstantOrConstantVector(C3
))
3672 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N0
.getOperand(0), C3
);
3675 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3678 SDValue
Sh(nullptr, 0), Y(nullptr, 0);
3680 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3681 if (N0
.getOpcode() == ISD::SHL
&&
3682 isConstantOrConstantVector(N0
.getOperand(1)) &&
3683 N0
.getNode()->hasOneUse()) {
3685 } else if (N1
.getOpcode() == ISD::SHL
&&
3686 isConstantOrConstantVector(N1
.getOperand(1)) &&
3687 N1
.getNode()->hasOneUse()) {
3692 SDValue Mul
= DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, Sh
.getOperand(0), Y
);
3693 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, Mul
, Sh
.getOperand(1));
3697 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3698 if (DAG
.isConstantIntBuildVectorOrConstantInt(N1
) &&
3699 N0
.getOpcode() == ISD::ADD
&&
3700 DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1)) &&
3701 isMulAddWithConstProfitable(N
, N0
, N1
))
3702 return DAG
.getNode(ISD::ADD
, SDLoc(N
), VT
,
3703 DAG
.getNode(ISD::MUL
, SDLoc(N0
), VT
,
3704 N0
.getOperand(0), N1
),
3705 DAG
.getNode(ISD::MUL
, SDLoc(N1
), VT
,
3706 N0
.getOperand(1), N1
));
3709 if (SDValue RMUL
= reassociateOps(ISD::MUL
, SDLoc(N
), N0
, N1
, N
->getFlags()))
3715 /// Return true if divmod libcall is available.
3716 static bool isDivRemLibcallAvailable(SDNode
*Node
, bool isSigned
,
3717 const TargetLowering
&TLI
) {
3719 EVT NodeType
= Node
->getValueType(0);
3720 if (!NodeType
.isSimple())
3722 switch (NodeType
.getSimpleVT().SimpleTy
) {
3723 default: return false; // No libcall for vector types.
3724 case MVT::i8
: LC
= isSigned
? RTLIB::SDIVREM_I8
: RTLIB::UDIVREM_I8
; break;
3725 case MVT::i16
: LC
= isSigned
? RTLIB::SDIVREM_I16
: RTLIB::UDIVREM_I16
; break;
3726 case MVT::i32
: LC
= isSigned
? RTLIB::SDIVREM_I32
: RTLIB::UDIVREM_I32
; break;
3727 case MVT::i64
: LC
= isSigned
? RTLIB::SDIVREM_I64
: RTLIB::UDIVREM_I64
; break;
3728 case MVT::i128
: LC
= isSigned
? RTLIB::SDIVREM_I128
:RTLIB::UDIVREM_I128
; break;
3731 return TLI
.getLibcallName(LC
) != nullptr;
3734 /// Issue divrem if both quotient and remainder are needed.
3735 SDValue
DAGCombiner::useDivRem(SDNode
*Node
) {
3736 if (Node
->use_empty())
3737 return SDValue(); // This is a dead node, leave it alone.
3739 unsigned Opcode
= Node
->getOpcode();
3740 bool isSigned
= (Opcode
== ISD::SDIV
) || (Opcode
== ISD::SREM
);
3741 unsigned DivRemOpc
= isSigned
? ISD::SDIVREM
: ISD::UDIVREM
;
3743 // DivMod lib calls can still work on non-legal types if using lib-calls.
3744 EVT VT
= Node
->getValueType(0);
3745 if (VT
.isVector() || !VT
.isInteger())
3748 if (!TLI
.isTypeLegal(VT
) && !TLI
.isOperationCustom(DivRemOpc
, VT
))
3751 // If DIVREM is going to get expanded into a libcall,
3752 // but there is no libcall available, then don't combine.
3753 if (!TLI
.isOperationLegalOrCustom(DivRemOpc
, VT
) &&
3754 !isDivRemLibcallAvailable(Node
, isSigned
, TLI
))
3757 // If div is legal, it's better to do the normal expansion
3758 unsigned OtherOpcode
= 0;
3759 if ((Opcode
== ISD::SDIV
) || (Opcode
== ISD::UDIV
)) {
3760 OtherOpcode
= isSigned
? ISD::SREM
: ISD::UREM
;
3761 if (TLI
.isOperationLegalOrCustom(Opcode
, VT
))
3764 OtherOpcode
= isSigned
? ISD::SDIV
: ISD::UDIV
;
3765 if (TLI
.isOperationLegalOrCustom(OtherOpcode
, VT
))
3769 SDValue Op0
= Node
->getOperand(0);
3770 SDValue Op1
= Node
->getOperand(1);
3772 for (SDNode::use_iterator UI
= Op0
.getNode()->use_begin(),
3773 UE
= Op0
.getNode()->use_end(); UI
!= UE
; ++UI
) {
3775 if (User
== Node
|| User
->getOpcode() == ISD::DELETED_NODE
||
3778 // Convert the other matching node(s), too;
3779 // otherwise, the DIVREM may get target-legalized into something
3780 // target-specific that we won't be able to recognize.
3781 unsigned UserOpc
= User
->getOpcode();
3782 if ((UserOpc
== Opcode
|| UserOpc
== OtherOpcode
|| UserOpc
== DivRemOpc
) &&
3783 User
->getOperand(0) == Op0
&&
3784 User
->getOperand(1) == Op1
) {
3786 if (UserOpc
== OtherOpcode
) {
3787 SDVTList VTs
= DAG
.getVTList(VT
, VT
);
3788 combined
= DAG
.getNode(DivRemOpc
, SDLoc(Node
), VTs
, Op0
, Op1
);
3789 } else if (UserOpc
== DivRemOpc
) {
3790 combined
= SDValue(User
, 0);
3792 assert(UserOpc
== Opcode
);
3796 if (UserOpc
== ISD::SDIV
|| UserOpc
== ISD::UDIV
)
3797 CombineTo(User
, combined
);
3798 else if (UserOpc
== ISD::SREM
|| UserOpc
== ISD::UREM
)
3799 CombineTo(User
, combined
.getValue(1));
3805 static SDValue
simplifyDivRem(SDNode
*N
, SelectionDAG
&DAG
) {
3806 SDValue N0
= N
->getOperand(0);
3807 SDValue N1
= N
->getOperand(1);
3808 EVT VT
= N
->getValueType(0);
3811 unsigned Opc
= N
->getOpcode();
3812 bool IsDiv
= (ISD::SDIV
== Opc
) || (ISD::UDIV
== Opc
);
3813 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
3815 // X / undef -> undef
3816 // X % undef -> undef
3819 // NOTE: This includes vectors where any divisor element is zero/undef.
3820 if (DAG
.isUndef(Opc
, {N0
, N1
}))
3821 return DAG
.getUNDEF(VT
);
3826 return DAG
.getConstant(0, DL
, VT
);
3830 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
3831 if (N0C
&& N0C
->isNullValue())
3837 return DAG
.getConstant(IsDiv
? 1 : 0, DL
, VT
);
3841 // If this is a boolean op (single-bit element type), we can't have
3842 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
3843 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
3845 if ((N1C
&& N1C
->isOne()) || (VT
.getScalarType() == MVT::i1
))
3846 return IsDiv
? N0
: DAG
.getConstant(0, DL
, VT
);
3851 SDValue
DAGCombiner::visitSDIV(SDNode
*N
) {
3852 SDValue N0
= N
->getOperand(0);
3853 SDValue N1
= N
->getOperand(1);
3854 EVT VT
= N
->getValueType(0);
3855 EVT CCVT
= getSetCCResultType(VT
);
3859 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3864 // fold (sdiv c1, c2) -> c1/c2
3865 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
3866 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
3867 if (N0C
&& N1C
&& !N0C
->isOpaque() && !N1C
->isOpaque())
3868 return DAG
.FoldConstantArithmetic(ISD::SDIV
, DL
, VT
, N0C
, N1C
);
3869 // fold (sdiv X, -1) -> 0-X
3870 if (N1C
&& N1C
->isAllOnesValue())
3871 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), N0
);
3872 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3873 if (N1C
&& N1C
->getAPIntValue().isMinSignedValue())
3874 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
3875 DAG
.getConstant(1, DL
, VT
),
3876 DAG
.getConstant(0, DL
, VT
));
3878 if (SDValue V
= simplifyDivRem(N
, DAG
))
3881 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3884 // If we know the sign bits of both operands are zero, strength reduce to a
3885 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
3886 if (DAG
.SignBitIsZero(N1
) && DAG
.SignBitIsZero(N0
))
3887 return DAG
.getNode(ISD::UDIV
, DL
, N1
.getValueType(), N0
, N1
);
3889 if (SDValue V
= visitSDIVLike(N0
, N1
, N
)) {
3890 // If the corresponding remainder node exists, update its users with
3891 // (Dividend - (Quotient * Divisor).
3892 if (SDNode
*RemNode
= DAG
.getNodeIfExists(ISD::SREM
, N
->getVTList(),
3894 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, V
, N1
);
3895 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
3896 AddToWorklist(Mul
.getNode());
3897 AddToWorklist(Sub
.getNode());
3898 CombineTo(RemNode
, Sub
);
3903 // sdiv, srem -> sdivrem
3904 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3905 // true. Otherwise, we break the simplification logic in visitREM().
3906 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3907 if (!N1C
|| TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
3908 if (SDValue DivRem
= useDivRem(N
))
3914 SDValue
DAGCombiner::visitSDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
3916 EVT VT
= N
->getValueType(0);
3917 EVT CCVT
= getSetCCResultType(VT
);
3918 unsigned BitWidth
= VT
.getScalarSizeInBits();
3920 // Helper for determining whether a value is a power-2 constant scalar or a
3921 // vector of such elements.
3922 auto IsPowerOfTwo
= [](ConstantSDNode
*C
) {
3923 if (C
->isNullValue() || C
->isOpaque())
3925 if (C
->getAPIntValue().isPowerOf2())
3927 if ((-C
->getAPIntValue()).isPowerOf2())
3932 // fold (sdiv X, pow2) -> simple ops after legalize
3933 // FIXME: We check for the exact bit here because the generic lowering gives
3934 // better results in that case. The target-specific lowering should learn how
3935 // to handle exact sdivs efficiently.
3936 if (!N
->getFlags().hasExact() && ISD::matchUnaryPredicate(N1
, IsPowerOfTwo
)) {
3937 // Target-specific implementation of sdiv x, pow2.
3938 if (SDValue Res
= BuildSDIVPow2(N
))
3941 // Create constants that are functions of the shift amount value.
3942 EVT ShiftAmtTy
= getShiftAmountTy(N0
.getValueType());
3943 SDValue Bits
= DAG
.getConstant(BitWidth
, DL
, ShiftAmtTy
);
3944 SDValue C1
= DAG
.getNode(ISD::CTTZ
, DL
, VT
, N1
);
3945 C1
= DAG
.getZExtOrTrunc(C1
, DL
, ShiftAmtTy
);
3946 SDValue Inexact
= DAG
.getNode(ISD::SUB
, DL
, ShiftAmtTy
, Bits
, C1
);
3947 if (!isConstantOrConstantVector(Inexact
))
3950 // Splat the sign bit into the register
3951 SDValue Sign
= DAG
.getNode(ISD::SRA
, DL
, VT
, N0
,
3952 DAG
.getConstant(BitWidth
- 1, DL
, ShiftAmtTy
));
3953 AddToWorklist(Sign
.getNode());
3955 // Add (N0 < 0) ? abs2 - 1 : 0;
3956 SDValue Srl
= DAG
.getNode(ISD::SRL
, DL
, VT
, Sign
, Inexact
);
3957 AddToWorklist(Srl
.getNode());
3958 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Srl
);
3959 AddToWorklist(Add
.getNode());
3960 SDValue Sra
= DAG
.getNode(ISD::SRA
, DL
, VT
, Add
, C1
);
3961 AddToWorklist(Sra
.getNode());
3963 // Special case: (sdiv X, 1) -> X
3964 // Special Case: (sdiv X, -1) -> 0-X
3965 SDValue One
= DAG
.getConstant(1, DL
, VT
);
3966 SDValue AllOnes
= DAG
.getAllOnesConstant(DL
, VT
);
3967 SDValue IsOne
= DAG
.getSetCC(DL
, CCVT
, N1
, One
, ISD::SETEQ
);
3968 SDValue IsAllOnes
= DAG
.getSetCC(DL
, CCVT
, N1
, AllOnes
, ISD::SETEQ
);
3969 SDValue IsOneOrAllOnes
= DAG
.getNode(ISD::OR
, DL
, CCVT
, IsOne
, IsAllOnes
);
3970 Sra
= DAG
.getSelect(DL
, VT
, IsOneOrAllOnes
, N0
, Sra
);
3972 // If dividing by a positive value, we're done. Otherwise, the result must
3974 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
3975 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, Zero
, Sra
);
3977 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3978 SDValue IsNeg
= DAG
.getSetCC(DL
, CCVT
, N1
, Zero
, ISD::SETLT
);
3979 SDValue Res
= DAG
.getSelect(DL
, VT
, IsNeg
, Sub
, Sra
);
3983 // If integer divide is expensive and we satisfy the requirements, emit an
3984 // alternate sequence. Targets may check function attributes for size/speed
3986 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3987 if (isConstantOrConstantVector(N1
) &&
3988 !TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
3989 if (SDValue Op
= BuildSDIV(N
))
3995 SDValue
DAGCombiner::visitUDIV(SDNode
*N
) {
3996 SDValue N0
= N
->getOperand(0);
3997 SDValue N1
= N
->getOperand(1);
3998 EVT VT
= N
->getValueType(0);
3999 EVT CCVT
= getSetCCResultType(VT
);
4003 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
4008 // fold (udiv c1, c2) -> c1/c2
4009 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
4010 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
4012 if (SDValue Folded
= DAG
.FoldConstantArithmetic(ISD::UDIV
, DL
, VT
,
4015 // fold (udiv X, -1) -> select(X == -1, 1, 0)
4016 if (N1C
&& N1C
->getAPIntValue().isAllOnesValue())
4017 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
4018 DAG
.getConstant(1, DL
, VT
),
4019 DAG
.getConstant(0, DL
, VT
));
4021 if (SDValue V
= simplifyDivRem(N
, DAG
))
4024 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
4027 if (SDValue V
= visitUDIVLike(N0
, N1
, N
)) {
4028 // If the corresponding remainder node exists, update its users with
4029 // (Dividend - (Quotient * Divisor).
4030 if (SDNode
*RemNode
= DAG
.getNodeIfExists(ISD::UREM
, N
->getVTList(),
4032 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, V
, N1
);
4033 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
4034 AddToWorklist(Mul
.getNode());
4035 AddToWorklist(Sub
.getNode());
4036 CombineTo(RemNode
, Sub
);
4041 // sdiv, srem -> sdivrem
4042 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4043 // true. Otherwise, we break the simplification logic in visitREM().
4044 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4045 if (!N1C
|| TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4046 if (SDValue DivRem
= useDivRem(N
))
4052 SDValue
DAGCombiner::visitUDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
4054 EVT VT
= N
->getValueType(0);
4056 // fold (udiv x, (1 << c)) -> x >>u c
4057 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
4058 DAG
.isKnownToBeAPowerOfTwo(N1
)) {
4059 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
4060 AddToWorklist(LogBase2
.getNode());
4062 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
4063 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ShiftVT
);
4064 AddToWorklist(Trunc
.getNode());
4065 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Trunc
);
4068 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
4069 if (N1
.getOpcode() == ISD::SHL
) {
4070 SDValue N10
= N1
.getOperand(0);
4071 if (isConstantOrConstantVector(N10
, /*NoOpaques*/ true) &&
4072 DAG
.isKnownToBeAPowerOfTwo(N10
)) {
4073 SDValue LogBase2
= BuildLogBase2(N10
, DL
);
4074 AddToWorklist(LogBase2
.getNode());
4076 EVT ADDVT
= N1
.getOperand(1).getValueType();
4077 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ADDVT
);
4078 AddToWorklist(Trunc
.getNode());
4079 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, ADDVT
, N1
.getOperand(1), Trunc
);
4080 AddToWorklist(Add
.getNode());
4081 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Add
);
4085 // fold (udiv x, c) -> alternate
4086 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4087 if (isConstantOrConstantVector(N1
) &&
4088 !TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4089 if (SDValue Op
= BuildUDIV(N
))
4095 // handles ISD::SREM and ISD::UREM
4096 SDValue
DAGCombiner::visitREM(SDNode
*N
) {
4097 unsigned Opcode
= N
->getOpcode();
4098 SDValue N0
= N
->getOperand(0);
4099 SDValue N1
= N
->getOperand(1);
4100 EVT VT
= N
->getValueType(0);
4101 EVT CCVT
= getSetCCResultType(VT
);
4103 bool isSigned
= (Opcode
== ISD::SREM
);
4106 // fold (rem c1, c2) -> c1%c2
4107 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
4108 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
4110 if (SDValue Folded
= DAG
.FoldConstantArithmetic(Opcode
, DL
, VT
, N0C
, N1C
))
4112 // fold (urem X, -1) -> select(X == -1, 0, x)
4113 if (!isSigned
&& N1C
&& N1C
->getAPIntValue().isAllOnesValue())
4114 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
4115 DAG
.getConstant(0, DL
, VT
), N0
);
4117 if (SDValue V
= simplifyDivRem(N
, DAG
))
4120 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
4124 // If we know the sign bits of both operands are zero, strength reduce to a
4125 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4126 if (DAG
.SignBitIsZero(N1
) && DAG
.SignBitIsZero(N0
))
4127 return DAG
.getNode(ISD::UREM
, DL
, VT
, N0
, N1
);
4129 SDValue NegOne
= DAG
.getAllOnesConstant(DL
, VT
);
4130 if (DAG
.isKnownToBeAPowerOfTwo(N1
)) {
4131 // fold (urem x, pow2) -> (and x, pow2-1)
4132 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, NegOne
);
4133 AddToWorklist(Add
.getNode());
4134 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, Add
);
4136 if (N1
.getOpcode() == ISD::SHL
&&
4137 DAG
.isKnownToBeAPowerOfTwo(N1
.getOperand(0))) {
4138 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4139 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, NegOne
);
4140 AddToWorklist(Add
.getNode());
4141 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, Add
);
4145 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4147 // If X/C can be simplified by the division-by-constant logic, lower
4148 // X%C to the equivalent of X-X/C*C.
4149 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4150 // speculative DIV must not cause a DIVREM conversion. We guard against this
4151 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
4152 // combine will not return a DIVREM. Regardless, checking cheapness here
4153 // makes sense since the simplification results in fatter code.
4154 if (DAG
.isKnownNeverZero(N1
) && !TLI
.isIntDivCheap(VT
, Attr
)) {
4155 SDValue OptimizedDiv
=
4156 isSigned
? visitSDIVLike(N0
, N1
, N
) : visitUDIVLike(N0
, N1
, N
);
4157 if (OptimizedDiv
.getNode()) {
4158 // If the equivalent Div node also exists, update its users.
4159 unsigned DivOpcode
= isSigned
? ISD::SDIV
: ISD::UDIV
;
4160 if (SDNode
*DivNode
= DAG
.getNodeIfExists(DivOpcode
, N
->getVTList(),
4162 CombineTo(DivNode
, OptimizedDiv
);
4163 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, OptimizedDiv
, N1
);
4164 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
4165 AddToWorklist(OptimizedDiv
.getNode());
4166 AddToWorklist(Mul
.getNode());
4171 // sdiv, srem -> sdivrem
4172 if (SDValue DivRem
= useDivRem(N
))
4173 return DivRem
.getValue(1);
4178 SDValue
DAGCombiner::visitMULHS(SDNode
*N
) {
4179 SDValue N0
= N
->getOperand(0);
4180 SDValue N1
= N
->getOperand(1);
4181 EVT VT
= N
->getValueType(0);
4184 if (VT
.isVector()) {
4185 // fold (mulhs x, 0) -> 0
4186 // do not return N0/N1, because undef node may exist.
4187 if (ISD::isBuildVectorAllZeros(N0
.getNode()) ||
4188 ISD::isBuildVectorAllZeros(N1
.getNode()))
4189 return DAG
.getConstant(0, DL
, VT
);
4192 // fold (mulhs x, 0) -> 0
4193 if (isNullConstant(N1
))
4195 // fold (mulhs x, 1) -> (sra x, size(x)-1)
4196 if (isOneConstant(N1
))
4197 return DAG
.getNode(ISD::SRA
, DL
, N0
.getValueType(), N0
,
4198 DAG
.getConstant(N0
.getScalarValueSizeInBits() - 1, DL
,
4199 getShiftAmountTy(N0
.getValueType())));
4201 // fold (mulhs x, undef) -> 0
4202 if (N0
.isUndef() || N1
.isUndef())
4203 return DAG
.getConstant(0, DL
, VT
);
4205 // If the type twice as wide is legal, transform the mulhs to a wider multiply
4207 if (VT
.isSimple() && !VT
.isVector()) {
4208 MVT Simple
= VT
.getSimpleVT();
4209 unsigned SimpleSize
= Simple
.getSizeInBits();
4210 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4211 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4212 N0
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N0
);
4213 N1
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N1
);
4214 N1
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, N0
, N1
);
4215 N1
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, N1
,
4216 DAG
.getConstant(SimpleSize
, DL
,
4217 getShiftAmountTy(N1
.getValueType())));
4218 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N1
);
4225 SDValue
DAGCombiner::visitMULHU(SDNode
*N
) {
4226 SDValue N0
= N
->getOperand(0);
4227 SDValue N1
= N
->getOperand(1);
4228 EVT VT
= N
->getValueType(0);
4231 if (VT
.isVector()) {
4232 // fold (mulhu x, 0) -> 0
4233 // do not return N0/N1, because undef node may exist.
4234 if (ISD::isBuildVectorAllZeros(N0
.getNode()) ||
4235 ISD::isBuildVectorAllZeros(N1
.getNode()))
4236 return DAG
.getConstant(0, DL
, VT
);
4239 // fold (mulhu x, 0) -> 0
4240 if (isNullConstant(N1
))
4242 // fold (mulhu x, 1) -> 0
4243 if (isOneConstant(N1
))
4244 return DAG
.getConstant(0, DL
, N0
.getValueType());
4245 // fold (mulhu x, undef) -> 0
4246 if (N0
.isUndef() || N1
.isUndef())
4247 return DAG
.getConstant(0, DL
, VT
);
4249 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4250 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
4251 DAG
.isKnownToBeAPowerOfTwo(N1
) && hasOperation(ISD::SRL
, VT
)) {
4252 unsigned NumEltBits
= VT
.getScalarSizeInBits();
4253 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
4254 SDValue SRLAmt
= DAG
.getNode(
4255 ISD::SUB
, DL
, VT
, DAG
.getConstant(NumEltBits
, DL
, VT
), LogBase2
);
4256 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
4257 SDValue Trunc
= DAG
.getZExtOrTrunc(SRLAmt
, DL
, ShiftVT
);
4258 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Trunc
);
4261 // If the type twice as wide is legal, transform the mulhu to a wider multiply
4263 if (VT
.isSimple() && !VT
.isVector()) {
4264 MVT Simple
= VT
.getSimpleVT();
4265 unsigned SimpleSize
= Simple
.getSizeInBits();
4266 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4267 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4268 N0
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N0
);
4269 N1
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N1
);
4270 N1
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, N0
, N1
);
4271 N1
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, N1
,
4272 DAG
.getConstant(SimpleSize
, DL
,
4273 getShiftAmountTy(N1
.getValueType())));
4274 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N1
);
4281 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4282 /// give the opcodes for the two computations that are being performed. Return
4283 /// true if a simplification was made.
4284 SDValue
DAGCombiner::SimplifyNodeWithTwoResults(SDNode
*N
, unsigned LoOp
,
4286 // If the high half is not needed, just compute the low half.
4287 bool HiExists
= N
->hasAnyUseOfValue(1);
4288 if (!HiExists
&& (!LegalOperations
||
4289 TLI
.isOperationLegalOrCustom(LoOp
, N
->getValueType(0)))) {
4290 SDValue Res
= DAG
.getNode(LoOp
, SDLoc(N
), N
->getValueType(0), N
->ops());
4291 return CombineTo(N
, Res
, Res
);
4294 // If the low half is not needed, just compute the high half.
4295 bool LoExists
= N
->hasAnyUseOfValue(0);
4296 if (!LoExists
&& (!LegalOperations
||
4297 TLI
.isOperationLegalOrCustom(HiOp
, N
->getValueType(1)))) {
4298 SDValue Res
= DAG
.getNode(HiOp
, SDLoc(N
), N
->getValueType(1), N
->ops());
4299 return CombineTo(N
, Res
, Res
);
4302 // If both halves are used, return as it is.
4303 if (LoExists
&& HiExists
)
4306 // If the two computed results can be simplified separately, separate them.
4308 SDValue Lo
= DAG
.getNode(LoOp
, SDLoc(N
), N
->getValueType(0), N
->ops());
4309 AddToWorklist(Lo
.getNode());
4310 SDValue LoOpt
= combine(Lo
.getNode());
4311 if (LoOpt
.getNode() && LoOpt
.getNode() != Lo
.getNode() &&
4312 (!LegalOperations
||
4313 TLI
.isOperationLegalOrCustom(LoOpt
.getOpcode(), LoOpt
.getValueType())))
4314 return CombineTo(N
, LoOpt
, LoOpt
);
4318 SDValue Hi
= DAG
.getNode(HiOp
, SDLoc(N
), N
->getValueType(1), N
->ops());
4319 AddToWorklist(Hi
.getNode());
4320 SDValue HiOpt
= combine(Hi
.getNode());
4321 if (HiOpt
.getNode() && HiOpt
!= Hi
&&
4322 (!LegalOperations
||
4323 TLI
.isOperationLegalOrCustom(HiOpt
.getOpcode(), HiOpt
.getValueType())))
4324 return CombineTo(N
, HiOpt
, HiOpt
);
4330 SDValue
DAGCombiner::visitSMUL_LOHI(SDNode
*N
) {
4331 if (SDValue Res
= SimplifyNodeWithTwoResults(N
, ISD::MUL
, ISD::MULHS
))
4334 EVT VT
= N
->getValueType(0);
4337 // If the type is twice as wide is legal, transform the mulhu to a wider
4338 // multiply plus a shift.
4339 if (VT
.isSimple() && !VT
.isVector()) {
4340 MVT Simple
= VT
.getSimpleVT();
4341 unsigned SimpleSize
= Simple
.getSizeInBits();
4342 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4343 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4344 SDValue Lo
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N
->getOperand(0));
4345 SDValue Hi
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N
->getOperand(1));
4346 Lo
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, Lo
, Hi
);
4347 // Compute the high part as N1.
4348 Hi
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, Lo
,
4349 DAG
.getConstant(SimpleSize
, DL
,
4350 getShiftAmountTy(Lo
.getValueType())));
4351 Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Hi
);
4352 // Compute the low part as N0.
4353 Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Lo
);
4354 return CombineTo(N
, Lo
, Hi
);
4361 SDValue
DAGCombiner::visitUMUL_LOHI(SDNode
*N
) {
4362 if (SDValue Res
= SimplifyNodeWithTwoResults(N
, ISD::MUL
, ISD::MULHU
))
4365 EVT VT
= N
->getValueType(0);
4368 // (umul_lohi N0, 0) -> (0, 0)
4369 if (isNullConstant(N
->getOperand(1))) {
4370 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
4371 return CombineTo(N
, Zero
, Zero
);
4374 // (umul_lohi N0, 1) -> (N0, 0)
4375 if (isOneConstant(N
->getOperand(1))) {
4376 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
4377 return CombineTo(N
, N
->getOperand(0), Zero
);
4380 // If the type is twice as wide is legal, transform the mulhu to a wider
4381 // multiply plus a shift.
4382 if (VT
.isSimple() && !VT
.isVector()) {
4383 MVT Simple
= VT
.getSimpleVT();
4384 unsigned SimpleSize
= Simple
.getSizeInBits();
4385 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4386 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4387 SDValue Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N
->getOperand(0));
4388 SDValue Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N
->getOperand(1));
4389 Lo
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, Lo
, Hi
);
4390 // Compute the high part as N1.
4391 Hi
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, Lo
,
4392 DAG
.getConstant(SimpleSize
, DL
,
4393 getShiftAmountTy(Lo
.getValueType())));
4394 Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Hi
);
4395 // Compute the low part as N0.
4396 Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Lo
);
4397 return CombineTo(N
, Lo
, Hi
);
4404 SDValue
DAGCombiner::visitMULO(SDNode
*N
) {
4405 SDValue N0
= N
->getOperand(0);
4406 SDValue N1
= N
->getOperand(1);
4407 EVT VT
= N0
.getValueType();
4408 bool IsSigned
= (ISD::SMULO
== N
->getOpcode());
4410 EVT CarryVT
= N
->getValueType(1);
4413 // canonicalize constant to RHS.
4414 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
4415 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
4416 return DAG
.getNode(N
->getOpcode(), DL
, N
->getVTList(), N1
, N0
);
4418 // fold (mulo x, 0) -> 0 + no carry out
4419 if (isNullOrNullSplat(N1
))
4420 return CombineTo(N
, DAG
.getConstant(0, DL
, VT
),
4421 DAG
.getConstant(0, DL
, CarryVT
));
4423 // (mulo x, 2) -> (addo x, x)
4424 if (ConstantSDNode
*C2
= isConstOrConstSplat(N1
))
4425 if (C2
->getAPIntValue() == 2)
4426 return DAG
.getNode(IsSigned
? ISD::SADDO
: ISD::UADDO
, DL
,
4427 N
->getVTList(), N0
, N0
);
4432 SDValue
DAGCombiner::visitIMINMAX(SDNode
*N
) {
4433 SDValue N0
= N
->getOperand(0);
4434 SDValue N1
= N
->getOperand(1);
4435 EVT VT
= N0
.getValueType();
4439 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
4442 // fold operation with constant operands.
4443 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
4444 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
4446 return DAG
.FoldConstantArithmetic(N
->getOpcode(), SDLoc(N
), VT
, N0C
, N1C
);
4448 // canonicalize constant to RHS
4449 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
4450 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
4451 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
);
4453 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4454 // Only do this if the current op isn't legal and the flipped is.
4455 unsigned Opcode
= N
->getOpcode();
4456 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4457 if (!TLI
.isOperationLegal(Opcode
, VT
) &&
4458 (N0
.isUndef() || DAG
.SignBitIsZero(N0
)) &&
4459 (N1
.isUndef() || DAG
.SignBitIsZero(N1
))) {
4462 case ISD::SMIN
: AltOpcode
= ISD::UMIN
; break;
4463 case ISD::SMAX
: AltOpcode
= ISD::UMAX
; break;
4464 case ISD::UMIN
: AltOpcode
= ISD::SMIN
; break;
4465 case ISD::UMAX
: AltOpcode
= ISD::SMAX
; break;
4466 default: llvm_unreachable("Unknown MINMAX opcode");
4468 if (TLI
.isOperationLegal(AltOpcode
, VT
))
4469 return DAG
.getNode(AltOpcode
, SDLoc(N
), VT
, N0
, N1
);
4475 /// If this is a bitwise logic instruction and both operands have the same
4476 /// opcode, try to sink the other opcode after the logic instruction.
4477 SDValue
DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode
*N
) {
4478 SDValue N0
= N
->getOperand(0), N1
= N
->getOperand(1);
4479 EVT VT
= N0
.getValueType();
4480 unsigned LogicOpcode
= N
->getOpcode();
4481 unsigned HandOpcode
= N0
.getOpcode();
4482 assert((LogicOpcode
== ISD::AND
|| LogicOpcode
== ISD::OR
||
4483 LogicOpcode
== ISD::XOR
) && "Expected logic opcode");
4484 assert(HandOpcode
== N1
.getOpcode() && "Bad input!");
4486 // Bail early if none of these transforms apply.
4487 if (N0
.getNumOperands() == 0)
4490 // FIXME: We should check number of uses of the operands to not increase
4491 // the instruction count for all transforms.
4493 // Handle size-changing casts.
4494 SDValue X
= N0
.getOperand(0);
4495 SDValue Y
= N1
.getOperand(0);
4496 EVT XVT
= X
.getValueType();
4498 if (HandOpcode
== ISD::ANY_EXTEND
|| HandOpcode
== ISD::ZERO_EXTEND
||
4499 HandOpcode
== ISD::SIGN_EXTEND
) {
4500 // If both operands have other uses, this transform would create extra
4501 // instructions without eliminating anything.
4502 if (!N0
.hasOneUse() && !N1
.hasOneUse())
4504 // We need matching integer source types.
4505 if (XVT
!= Y
.getValueType())
4507 // Don't create an illegal op during or after legalization. Don't ever
4508 // create an unsupported vector op.
4509 if ((VT
.isVector() || LegalOperations
) &&
4510 !TLI
.isOperationLegalOrCustom(LogicOpcode
, XVT
))
4512 // Avoid infinite looping with PromoteIntBinOp.
4513 // TODO: Should we apply desirable/legal constraints to all opcodes?
4514 if (HandOpcode
== ISD::ANY_EXTEND
&& LegalTypes
&&
4515 !TLI
.isTypeDesirableForOp(LogicOpcode
, XVT
))
4517 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
4518 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4519 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4522 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
4523 if (HandOpcode
== ISD::TRUNCATE
) {
4524 // If both operands have other uses, this transform would create extra
4525 // instructions without eliminating anything.
4526 if (!N0
.hasOneUse() && !N1
.hasOneUse())
4528 // We need matching source types.
4529 if (XVT
!= Y
.getValueType())
4531 // Don't create an illegal op during or after legalization.
4532 if (LegalOperations
&& !TLI
.isOperationLegal(LogicOpcode
, XVT
))
4534 // Be extra careful sinking truncate. If it's free, there's no benefit in
4535 // widening a binop. Also, don't create a logic op on an illegal type.
4536 if (TLI
.isZExtFree(VT
, XVT
) && TLI
.isTruncateFree(XVT
, VT
))
4538 if (!TLI
.isTypeLegal(XVT
))
4540 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4541 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4544 // For binops SHL/SRL/SRA/AND:
4545 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
4546 if ((HandOpcode
== ISD::SHL
|| HandOpcode
== ISD::SRL
||
4547 HandOpcode
== ISD::SRA
|| HandOpcode
== ISD::AND
) &&
4548 N0
.getOperand(1) == N1
.getOperand(1)) {
4549 // If either operand has other uses, this transform is not an improvement.
4550 if (!N0
.hasOneUse() || !N1
.hasOneUse())
4552 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4553 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
, N0
.getOperand(1));
4556 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
4557 if (HandOpcode
== ISD::BSWAP
) {
4558 // If either operand has other uses, this transform is not an improvement.
4559 if (!N0
.hasOneUse() || !N1
.hasOneUse())
4561 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4562 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4565 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4566 // Only perform this optimization up until type legalization, before
4567 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4568 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4569 // we don't want to undo this promotion.
4570 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4572 if ((HandOpcode
== ISD::BITCAST
|| HandOpcode
== ISD::SCALAR_TO_VECTOR
) &&
4573 Level
<= AfterLegalizeTypes
) {
4574 // Input types must be integer and the same.
4575 if (XVT
.isInteger() && XVT
== Y
.getValueType()) {
4576 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4577 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4581 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4582 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4583 // If both shuffles use the same mask, and both shuffle within a single
4584 // vector, then it is worthwhile to move the swizzle after the operation.
4585 // The type-legalizer generates this pattern when loading illegal
4586 // vector types from memory. In many cases this allows additional shuffle
4588 // There are other cases where moving the shuffle after the xor/and/or
4589 // is profitable even if shuffles don't perform a swizzle.
4590 // If both shuffles use the same mask, and both shuffles have the same first
4591 // or second operand, then it might still be profitable to move the shuffle
4592 // after the xor/and/or operation.
4593 if (HandOpcode
== ISD::VECTOR_SHUFFLE
&& Level
< AfterLegalizeDAG
) {
4594 auto *SVN0
= cast
<ShuffleVectorSDNode
>(N0
);
4595 auto *SVN1
= cast
<ShuffleVectorSDNode
>(N1
);
4596 assert(X
.getValueType() == Y
.getValueType() &&
4597 "Inputs to shuffles are not the same type");
4599 // Check that both shuffles use the same mask. The masks are known to be of
4600 // the same length because the result vector type is the same.
4601 // Check also that shuffles have only one use to avoid introducing extra
4603 if (!SVN0
->hasOneUse() || !SVN1
->hasOneUse() ||
4604 !SVN0
->getMask().equals(SVN1
->getMask()))
4607 // Don't try to fold this node if it requires introducing a
4608 // build vector of all zeros that might be illegal at this stage.
4609 SDValue ShOp
= N0
.getOperand(1);
4610 if (LogicOpcode
== ISD::XOR
&& !ShOp
.isUndef())
4611 ShOp
= tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
4613 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4614 if (N0
.getOperand(1) == N1
.getOperand(1) && ShOp
.getNode()) {
4615 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, VT
,
4616 N0
.getOperand(0), N1
.getOperand(0));
4617 return DAG
.getVectorShuffle(VT
, DL
, Logic
, ShOp
, SVN0
->getMask());
4620 // Don't try to fold this node if it requires introducing a
4621 // build vector of all zeros that might be illegal at this stage.
4622 ShOp
= N0
.getOperand(0);
4623 if (LogicOpcode
== ISD::XOR
&& !ShOp
.isUndef())
4624 ShOp
= tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
4626 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4627 if (N0
.getOperand(0) == N1
.getOperand(0) && ShOp
.getNode()) {
4628 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, VT
, N0
.getOperand(1),
4630 return DAG
.getVectorShuffle(VT
, DL
, ShOp
, Logic
, SVN0
->getMask());
4637 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4638 SDValue
DAGCombiner::foldLogicOfSetCCs(bool IsAnd
, SDValue N0
, SDValue N1
,
4640 SDValue LL
, LR
, RL
, RR
, N0CC
, N1CC
;
4641 if (!isSetCCEquivalent(N0
, LL
, LR
, N0CC
) ||
4642 !isSetCCEquivalent(N1
, RL
, RR
, N1CC
))
4645 assert(N0
.getValueType() == N1
.getValueType() &&
4646 "Unexpected operand types for bitwise logic op");
4647 assert(LL
.getValueType() == LR
.getValueType() &&
4648 RL
.getValueType() == RR
.getValueType() &&
4649 "Unexpected operand types for setcc");
4651 // If we're here post-legalization or the logic op type is not i1, the logic
4652 // op type must match a setcc result type. Also, all folds require new
4653 // operations on the left and right operands, so those types must match.
4654 EVT VT
= N0
.getValueType();
4655 EVT OpVT
= LL
.getValueType();
4656 if (LegalOperations
|| VT
.getScalarType() != MVT::i1
)
4657 if (VT
!= getSetCCResultType(OpVT
))
4659 if (OpVT
!= RL
.getValueType())
4662 ISD::CondCode CC0
= cast
<CondCodeSDNode
>(N0CC
)->get();
4663 ISD::CondCode CC1
= cast
<CondCodeSDNode
>(N1CC
)->get();
4664 bool IsInteger
= OpVT
.isInteger();
4665 if (LR
== RR
&& CC0
== CC1
&& IsInteger
) {
4666 bool IsZero
= isNullOrNullSplat(LR
);
4667 bool IsNeg1
= isAllOnesOrAllOnesSplat(LR
);
4670 bool AndEqZero
= IsAnd
&& CC1
== ISD::SETEQ
&& IsZero
;
4671 // All sign bits clear?
4672 bool AndGtNeg1
= IsAnd
&& CC1
== ISD::SETGT
&& IsNeg1
;
4674 bool OrNeZero
= !IsAnd
&& CC1
== ISD::SETNE
&& IsZero
;
4675 // Any sign bits set?
4676 bool OrLtZero
= !IsAnd
&& CC1
== ISD::SETLT
&& IsZero
;
4678 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
4679 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4680 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
4681 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
4682 if (AndEqZero
|| AndGtNeg1
|| OrNeZero
|| OrLtZero
) {
4683 SDValue Or
= DAG
.getNode(ISD::OR
, SDLoc(N0
), OpVT
, LL
, RL
);
4684 AddToWorklist(Or
.getNode());
4685 return DAG
.getSetCC(DL
, VT
, Or
, LR
, CC1
);
4689 bool AndEqNeg1
= IsAnd
&& CC1
== ISD::SETEQ
&& IsNeg1
;
4690 // All sign bits set?
4691 bool AndLtZero
= IsAnd
&& CC1
== ISD::SETLT
&& IsZero
;
4693 bool OrNeNeg1
= !IsAnd
&& CC1
== ISD::SETNE
&& IsNeg1
;
4694 // Any sign bits clear?
4695 bool OrGtNeg1
= !IsAnd
&& CC1
== ISD::SETGT
&& IsNeg1
;
4697 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
4698 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
4699 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
4700 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
4701 if (AndEqNeg1
|| AndLtZero
|| OrNeNeg1
|| OrGtNeg1
) {
4702 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(N0
), OpVT
, LL
, RL
);
4703 AddToWorklist(And
.getNode());
4704 return DAG
.getSetCC(DL
, VT
, And
, LR
, CC1
);
4708 // TODO: What is the 'or' equivalent of this fold?
4709 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
4710 if (IsAnd
&& LL
== RL
&& CC0
== CC1
&& OpVT
.getScalarSizeInBits() > 1 &&
4711 IsInteger
&& CC0
== ISD::SETNE
&&
4712 ((isNullConstant(LR
) && isAllOnesConstant(RR
)) ||
4713 (isAllOnesConstant(LR
) && isNullConstant(RR
)))) {
4714 SDValue One
= DAG
.getConstant(1, DL
, OpVT
);
4715 SDValue Two
= DAG
.getConstant(2, DL
, OpVT
);
4716 SDValue Add
= DAG
.getNode(ISD::ADD
, SDLoc(N0
), OpVT
, LL
, One
);
4717 AddToWorklist(Add
.getNode());
4718 return DAG
.getSetCC(DL
, VT
, Add
, Two
, ISD::SETUGE
);
4721 // Try more general transforms if the predicates match and the only user of
4722 // the compares is the 'and' or 'or'.
4723 if (IsInteger
&& TLI
.convertSetCCLogicToBitwiseLogic(OpVT
) && CC0
== CC1
&&
4724 N0
.hasOneUse() && N1
.hasOneUse()) {
4725 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
4726 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
4727 if ((IsAnd
&& CC1
== ISD::SETEQ
) || (!IsAnd
&& CC1
== ISD::SETNE
)) {
4728 SDValue XorL
= DAG
.getNode(ISD::XOR
, SDLoc(N0
), OpVT
, LL
, LR
);
4729 SDValue XorR
= DAG
.getNode(ISD::XOR
, SDLoc(N1
), OpVT
, RL
, RR
);
4730 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, OpVT
, XorL
, XorR
);
4731 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
4732 return DAG
.getSetCC(DL
, VT
, Or
, Zero
, CC1
);
4735 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
4736 // TODO - support non-uniform vector amounts.
4737 if ((IsAnd
&& CC1
== ISD::SETNE
) || (!IsAnd
&& CC1
== ISD::SETEQ
)) {
4738 // Match a shared variable operand and 2 non-opaque constant operands.
4739 ConstantSDNode
*C0
= isConstOrConstSplat(LR
);
4740 ConstantSDNode
*C1
= isConstOrConstSplat(RR
);
4741 if (LL
== RL
&& C0
&& C1
&& !C0
->isOpaque() && !C1
->isOpaque()) {
4742 // Canonicalize larger constant as C0.
4743 if (C1
->getAPIntValue().ugt(C0
->getAPIntValue()))
4746 // The difference of the constants must be a single bit.
4747 const APInt
&C0Val
= C0
->getAPIntValue();
4748 const APInt
&C1Val
= C1
->getAPIntValue();
4749 if ((C0Val
- C1Val
).isPowerOf2()) {
4750 // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) -->
4751 // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq
4752 SDValue OffsetC
= DAG
.getConstant(-C1Val
, DL
, OpVT
);
4753 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, OpVT
, LL
, OffsetC
);
4754 SDValue MaskC
= DAG
.getConstant(~(C0Val
- C1Val
), DL
, OpVT
);
4755 SDValue And
= DAG
.getNode(ISD::AND
, DL
, OpVT
, Add
, MaskC
);
4756 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
4757 return DAG
.getSetCC(DL
, VT
, And
, Zero
, CC0
);
4763 // Canonicalize equivalent operands to LL == RL.
4764 if (LL
== RR
&& LR
== RL
) {
4765 CC1
= ISD::getSetCCSwappedOperands(CC1
);
4769 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4770 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4771 if (LL
== RL
&& LR
== RR
) {
4772 ISD::CondCode NewCC
= IsAnd
? ISD::getSetCCAndOperation(CC0
, CC1
, IsInteger
)
4773 : ISD::getSetCCOrOperation(CC0
, CC1
, IsInteger
);
4774 if (NewCC
!= ISD::SETCC_INVALID
&&
4775 (!LegalOperations
||
4776 (TLI
.isCondCodeLegal(NewCC
, LL
.getSimpleValueType()) &&
4777 TLI
.isOperationLegal(ISD::SETCC
, OpVT
))))
4778 return DAG
.getSetCC(DL
, VT
, LL
, LR
, NewCC
);
4784 /// This contains all DAGCombine rules which reduce two values combined by
4785 /// an And operation to a single value. This makes them reusable in the context
4786 /// of visitSELECT(). Rules involving constants are not included as
4787 /// visitSELECT() already handles those cases.
4788 SDValue
DAGCombiner::visitANDLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
4789 EVT VT
= N1
.getValueType();
4792 // fold (and x, undef) -> 0
4793 if (N0
.isUndef() || N1
.isUndef())
4794 return DAG
.getConstant(0, DL
, VT
);
4796 if (SDValue V
= foldLogicOfSetCCs(true, N0
, N1
, DL
))
4799 if (N0
.getOpcode() == ISD::ADD
&& N1
.getOpcode() == ISD::SRL
&&
4800 VT
.getSizeInBits() <= 64) {
4801 if (ConstantSDNode
*ADDI
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
4802 if (ConstantSDNode
*SRLI
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1))) {
4803 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
4804 // immediate for an add, but it is legal if its top c2 bits are set,
4805 // transform the ADD so the immediate doesn't need to be materialized
4807 APInt ADDC
= ADDI
->getAPIntValue();
4808 APInt SRLC
= SRLI
->getAPIntValue();
4809 if (ADDC
.getMinSignedBits() <= 64 &&
4810 SRLC
.ult(VT
.getSizeInBits()) &&
4811 !TLI
.isLegalAddImmediate(ADDC
.getSExtValue())) {
4812 APInt Mask
= APInt::getHighBitsSet(VT
.getSizeInBits(),
4813 SRLC
.getZExtValue());
4814 if (DAG
.MaskedValueIsZero(N0
.getOperand(1), Mask
)) {
4816 if (TLI
.isLegalAddImmediate(ADDC
.getSExtValue())) {
4819 DAG
.getNode(ISD::ADD
, DL0
, VT
,
4820 N0
.getOperand(0), DAG
.getConstant(ADDC
, DL
, VT
));
4821 CombineTo(N0
.getNode(), NewAdd
);
4822 // Return N so it doesn't get rechecked!
4823 return SDValue(N
, 0);
4831 // Reduce bit extract of low half of an integer to the narrower type.
4832 // (and (srl i64:x, K), KMask) ->
4833 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
4834 if (N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse()) {
4835 if (ConstantSDNode
*CAnd
= dyn_cast
<ConstantSDNode
>(N1
)) {
4836 if (ConstantSDNode
*CShift
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
4837 unsigned Size
= VT
.getSizeInBits();
4838 const APInt
&AndMask
= CAnd
->getAPIntValue();
4839 unsigned ShiftBits
= CShift
->getZExtValue();
4841 // Bail out, this node will probably disappear anyway.
4845 unsigned MaskBits
= AndMask
.countTrailingOnes();
4846 EVT HalfVT
= EVT::getIntegerVT(*DAG
.getContext(), Size
/ 2);
4848 if (AndMask
.isMask() &&
4849 // Required bits must not span the two halves of the integer and
4850 // must fit in the half size type.
4851 (ShiftBits
+ MaskBits
<= Size
/ 2) &&
4852 TLI
.isNarrowingProfitable(VT
, HalfVT
) &&
4853 TLI
.isTypeDesirableForOp(ISD::AND
, HalfVT
) &&
4854 TLI
.isTypeDesirableForOp(ISD::SRL
, HalfVT
) &&
4855 TLI
.isTruncateFree(VT
, HalfVT
) &&
4856 TLI
.isZExtFree(HalfVT
, VT
)) {
4857 // The isNarrowingProfitable is to avoid regressions on PPC and
4858 // AArch64 which match a few 64-bit bit insert / bit extract patterns
4859 // on downstream users of this. Those patterns could probably be
4860 // extended to handle extensions mixed in.
4863 assert(MaskBits
<= Size
);
4865 // Extracting the highest bit of the low half.
4866 EVT ShiftVT
= TLI
.getShiftAmountTy(HalfVT
, DAG
.getDataLayout());
4867 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, HalfVT
,
4870 SDValue NewMask
= DAG
.getConstant(AndMask
.trunc(Size
/ 2), SL
, HalfVT
);
4871 SDValue ShiftK
= DAG
.getConstant(ShiftBits
, SL
, ShiftVT
);
4872 SDValue Shift
= DAG
.getNode(ISD::SRL
, SL
, HalfVT
, Trunc
, ShiftK
);
4873 SDValue And
= DAG
.getNode(ISD::AND
, SL
, HalfVT
, Shift
, NewMask
);
4874 return DAG
.getNode(ISD::ZERO_EXTEND
, SL
, VT
, And
);
4883 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode
*AndC
, LoadSDNode
*LoadN
,
4884 EVT LoadResultTy
, EVT
&ExtVT
) {
4885 if (!AndC
->getAPIntValue().isMask())
4888 unsigned ActiveBits
= AndC
->getAPIntValue().countTrailingOnes();
4890 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
4891 EVT LoadedVT
= LoadN
->getMemoryVT();
4893 if (ExtVT
== LoadedVT
&&
4894 (!LegalOperations
||
4895 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LoadResultTy
, ExtVT
))) {
4896 // ZEXTLOAD will match without needing to change the size of the value being
4901 // Do not change the width of a volatile or atomic loads.
4902 if (!LoadN
->isSimple())
4905 // Do not generate loads of non-round integer types since these can
4906 // be expensive (and would be wrong if the type is not byte sized).
4907 if (!LoadedVT
.bitsGT(ExtVT
) || !ExtVT
.isRound())
4910 if (LegalOperations
&&
4911 !TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LoadResultTy
, ExtVT
))
4914 if (!TLI
.shouldReduceLoadWidth(LoadN
, ISD::ZEXTLOAD
, ExtVT
))
4920 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode
*LDST
,
4921 ISD::LoadExtType ExtType
, EVT
&MemVT
,
4925 // Only allow byte offsets.
4929 // Do not generate loads of non-round integer types since these can
4930 // be expensive (and would be wrong if the type is not byte sized).
4931 if (!MemVT
.isRound())
4934 // Don't change the width of a volatile or atomic loads.
4935 if (!LDST
->isSimple())
4938 // Verify that we are actually reducing a load width here.
4939 if (LDST
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits())
4942 // Ensure that this isn't going to produce an unsupported unaligned access.
4944 !TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(), MemVT
,
4945 LDST
->getAddressSpace(), ShAmt
/ 8,
4946 LDST
->getMemOperand()->getFlags()))
4949 // It's not possible to generate a constant of extended or untyped type.
4950 EVT PtrType
= LDST
->getBasePtr().getValueType();
4951 if (PtrType
== MVT::Untyped
|| PtrType
.isExtended())
4954 if (isa
<LoadSDNode
>(LDST
)) {
4955 LoadSDNode
*Load
= cast
<LoadSDNode
>(LDST
);
4956 // Don't transform one with multiple uses, this would require adding a new
4958 if (!SDValue(Load
, 0).hasOneUse())
4961 if (LegalOperations
&&
4962 !TLI
.isLoadExtLegal(ExtType
, Load
->getValueType(0), MemVT
))
4965 // For the transform to be legal, the load must produce only two values
4966 // (the value loaded and the chain). Don't transform a pre-increment
4967 // load, for example, which produces an extra value. Otherwise the
4968 // transformation is not equivalent, and the downstream logic to replace
4969 // uses gets things wrong.
4970 if (Load
->getNumValues() > 2)
4973 // If the load that we're shrinking is an extload and we're not just
4974 // discarding the extension we can't simply shrink the load. Bail.
4975 // TODO: It would be possible to merge the extensions in some cases.
4976 if (Load
->getExtensionType() != ISD::NON_EXTLOAD
&&
4977 Load
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits() + ShAmt
)
4980 if (!TLI
.shouldReduceLoadWidth(Load
, ExtType
, MemVT
))
4983 assert(isa
<StoreSDNode
>(LDST
) && "It is not a Load nor a Store SDNode");
4984 StoreSDNode
*Store
= cast
<StoreSDNode
>(LDST
);
4985 // Can't write outside the original store
4986 if (Store
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits() + ShAmt
)
4989 if (LegalOperations
&&
4990 !TLI
.isTruncStoreLegal(Store
->getValue().getValueType(), MemVT
))
4996 bool DAGCombiner::SearchForAndLoads(SDNode
*N
,
4997 SmallVectorImpl
<LoadSDNode
*> &Loads
,
4998 SmallPtrSetImpl
<SDNode
*> &NodesWithConsts
,
4999 ConstantSDNode
*Mask
,
5000 SDNode
*&NodeToMask
) {
5001 // Recursively search for the operands, looking for loads which can be
5003 for (SDValue Op
: N
->op_values()) {
5004 if (Op
.getValueType().isVector())
5007 // Some constants may need fixing up later if they are too large.
5008 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
)) {
5009 if ((N
->getOpcode() == ISD::OR
|| N
->getOpcode() == ISD::XOR
) &&
5010 (Mask
->getAPIntValue() & C
->getAPIntValue()) != C
->getAPIntValue())
5011 NodesWithConsts
.insert(N
);
5015 if (!Op
.hasOneUse())
5018 switch(Op
.getOpcode()) {
5020 auto *Load
= cast
<LoadSDNode
>(Op
);
5022 if (isAndLoadExtLoad(Mask
, Load
, Load
->getValueType(0), ExtVT
) &&
5023 isLegalNarrowLdSt(Load
, ISD::ZEXTLOAD
, ExtVT
)) {
5025 // ZEXTLOAD is already small enough.
5026 if (Load
->getExtensionType() == ISD::ZEXTLOAD
&&
5027 ExtVT
.bitsGE(Load
->getMemoryVT()))
5030 // Use LE to convert equal sized loads to zext.
5031 if (ExtVT
.bitsLE(Load
->getMemoryVT()))
5032 Loads
.push_back(Load
);
5038 case ISD::ZERO_EXTEND
:
5039 case ISD::AssertZext
: {
5040 unsigned ActiveBits
= Mask
->getAPIntValue().countTrailingOnes();
5041 EVT ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
5042 EVT VT
= Op
.getOpcode() == ISD::AssertZext
?
5043 cast
<VTSDNode
>(Op
.getOperand(1))->getVT() :
5044 Op
.getOperand(0).getValueType();
5046 // We can accept extending nodes if the mask is wider or an equal
5047 // width to the original type.
5048 if (ExtVT
.bitsGE(VT
))
5055 if (!SearchForAndLoads(Op
.getNode(), Loads
, NodesWithConsts
, Mask
,
5061 // Allow one node which will masked along with any loads found.
5065 // Also ensure that the node to be masked only produces one data result.
5066 NodeToMask
= Op
.getNode();
5067 if (NodeToMask
->getNumValues() > 1) {
5068 bool HasValue
= false;
5069 for (unsigned i
= 0, e
= NodeToMask
->getNumValues(); i
< e
; ++i
) {
5070 MVT VT
= SDValue(NodeToMask
, i
).getSimpleValueType();
5071 if (VT
!= MVT::Glue
&& VT
!= MVT::Other
) {
5073 NodeToMask
= nullptr;
5079 assert(HasValue
&& "Node to be masked has no data result?");
5085 bool DAGCombiner::BackwardsPropagateMask(SDNode
*N
, SelectionDAG
&DAG
) {
5086 auto *Mask
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
5090 if (!Mask
->getAPIntValue().isMask())
5093 // No need to do anything if the and directly uses a load.
5094 if (isa
<LoadSDNode
>(N
->getOperand(0)))
5097 SmallVector
<LoadSDNode
*, 8> Loads
;
5098 SmallPtrSet
<SDNode
*, 2> NodesWithConsts
;
5099 SDNode
*FixupNode
= nullptr;
5100 if (SearchForAndLoads(N
, Loads
, NodesWithConsts
, Mask
, FixupNode
)) {
5101 if (Loads
.size() == 0)
5104 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N
->dump());
5105 SDValue MaskOp
= N
->getOperand(1);
5107 // If it exists, fixup the single node we allow in the tree that needs
5110 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode
->dump());
5111 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(FixupNode
),
5112 FixupNode
->getValueType(0),
5113 SDValue(FixupNode
, 0), MaskOp
);
5114 DAG
.ReplaceAllUsesOfValueWith(SDValue(FixupNode
, 0), And
);
5115 if (And
.getOpcode() == ISD ::AND
)
5116 DAG
.UpdateNodeOperands(And
.getNode(), SDValue(FixupNode
, 0), MaskOp
);
5119 // Narrow any constants that need it.
5120 for (auto *LogicN
: NodesWithConsts
) {
5121 SDValue Op0
= LogicN
->getOperand(0);
5122 SDValue Op1
= LogicN
->getOperand(1);
5124 if (isa
<ConstantSDNode
>(Op0
))
5125 std::swap(Op0
, Op1
);
5127 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(Op1
), Op1
.getValueType(),
5130 DAG
.UpdateNodeOperands(LogicN
, Op0
, And
);
5133 // Create narrow loads.
5134 for (auto *Load
: Loads
) {
5135 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load
->dump());
5136 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(Load
), Load
->getValueType(0),
5137 SDValue(Load
, 0), MaskOp
);
5138 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 0), And
);
5139 if (And
.getOpcode() == ISD ::AND
)
5141 DAG
.UpdateNodeOperands(And
.getNode(), SDValue(Load
, 0), MaskOp
), 0);
5142 SDValue NewLoad
= ReduceLoadWidth(And
.getNode());
5144 "Shouldn't be masking the load if it can't be narrowed");
5145 CombineTo(Load
, NewLoad
, NewLoad
.getValue(1));
5147 DAG
.ReplaceAllUsesWith(N
, N
->getOperand(0).getNode());
5154 // x & (-1 'logical shift' y)
5156 // (x 'opposite logical shift' y) 'logical shift' y
5157 // if it is better for performance.
5158 SDValue
DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode
*N
) {
5159 assert(N
->getOpcode() == ISD::AND
);
5161 SDValue N0
= N
->getOperand(0);
5162 SDValue N1
= N
->getOperand(1);
5164 // Do we actually prefer shifts over mask?
5165 if (!TLI
.shouldFoldMaskToVariableShiftPair(N0
))
5168 // Try to match (-1 '[outer] logical shift' y)
5169 unsigned OuterShift
;
5170 unsigned InnerShift
; // The opposite direction to the OuterShift.
5171 SDValue Y
; // Shift amount.
5172 auto matchMask
= [&OuterShift
, &InnerShift
, &Y
](SDValue M
) -> bool {
5175 OuterShift
= M
->getOpcode();
5176 if (OuterShift
== ISD::SHL
)
5177 InnerShift
= ISD::SRL
;
5178 else if (OuterShift
== ISD::SRL
)
5179 InnerShift
= ISD::SHL
;
5182 if (!isAllOnesConstant(M
->getOperand(0)))
5184 Y
= M
->getOperand(1);
5191 else if (matchMask(N0
))
5197 EVT VT
= N
->getValueType(0);
5199 // tmp = x 'opposite logical shift' y
5200 SDValue T0
= DAG
.getNode(InnerShift
, DL
, VT
, X
, Y
);
5201 // ret = tmp 'logical shift' y
5202 SDValue T1
= DAG
.getNode(OuterShift
, DL
, VT
, T0
, Y
);
5207 /// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
5208 /// For a target with a bit test, this is expected to become test + set and save
5209 /// at least 1 instruction.
5210 static SDValue
combineShiftAnd1ToBitTest(SDNode
*And
, SelectionDAG
&DAG
) {
5211 assert(And
->getOpcode() == ISD::AND
&& "Expected an 'and' op");
5213 // This is probably not worthwhile without a supported type.
5214 EVT VT
= And
->getValueType(0);
5215 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
5216 if (!TLI
.isTypeLegal(VT
))
5219 // Look through an optional extension and find a 'not'.
5220 // TODO: Should we favor test+set even without the 'not' op?
5221 SDValue Not
= And
->getOperand(0), And1
= And
->getOperand(1);
5222 if (Not
.getOpcode() == ISD::ANY_EXTEND
)
5223 Not
= Not
.getOperand(0);
5224 if (!isBitwiseNot(Not
) || !Not
.hasOneUse() || !isOneConstant(And1
))
5227 // Look though an optional truncation. The source operand may not be the same
5228 // type as the original 'and', but that is ok because we are masking off
5229 // everything but the low bit.
5230 SDValue Srl
= Not
.getOperand(0);
5231 if (Srl
.getOpcode() == ISD::TRUNCATE
)
5232 Srl
= Srl
.getOperand(0);
5234 // Match a shift-right by constant.
5235 if (Srl
.getOpcode() != ISD::SRL
|| !Srl
.hasOneUse() ||
5236 !isa
<ConstantSDNode
>(Srl
.getOperand(1)))
5239 // We might have looked through casts that make this transform invalid.
5240 // TODO: If the source type is wider than the result type, do the mask and
5241 // compare in the source type.
5242 const APInt
&ShiftAmt
= Srl
.getConstantOperandAPInt(1);
5243 unsigned VTBitWidth
= VT
.getSizeInBits();
5244 if (ShiftAmt
.uge(VTBitWidth
))
5247 // Turn this into a bit-test pattern using mask op + setcc:
5248 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
5250 SDValue X
= DAG
.getZExtOrTrunc(Srl
.getOperand(0), DL
, VT
);
5251 EVT CCVT
= TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5252 SDValue Mask
= DAG
.getConstant(
5253 APInt::getOneBitSet(VTBitWidth
, ShiftAmt
.getZExtValue()), DL
, VT
);
5254 SDValue NewAnd
= DAG
.getNode(ISD::AND
, DL
, VT
, X
, Mask
);
5255 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
5256 SDValue Setcc
= DAG
.getSetCC(DL
, CCVT
, NewAnd
, Zero
, ISD::SETEQ
);
5257 return DAG
.getZExtOrTrunc(Setcc
, DL
, VT
);
5260 SDValue
DAGCombiner::visitAND(SDNode
*N
) {
5261 SDValue N0
= N
->getOperand(0);
5262 SDValue N1
= N
->getOperand(1);
5263 EVT VT
= N1
.getValueType();
5270 if (VT
.isVector()) {
5271 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
5274 // fold (and x, 0) -> 0, vector edition
5275 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
5276 // do not return N0, because undef node may exist in N0
5277 return DAG
.getConstant(APInt::getNullValue(N0
.getScalarValueSizeInBits()),
5278 SDLoc(N
), N0
.getValueType());
5279 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
5280 // do not return N1, because undef node may exist in N1
5281 return DAG
.getConstant(APInt::getNullValue(N1
.getScalarValueSizeInBits()),
5282 SDLoc(N
), N1
.getValueType());
5284 // fold (and x, -1) -> x, vector edition
5285 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
5287 if (ISD::isBuildVectorAllOnes(N1
.getNode()))
5291 // fold (and c1, c2) -> c1&c2
5292 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
5293 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
5294 if (N0C
&& N1C
&& !N1C
->isOpaque())
5295 return DAG
.FoldConstantArithmetic(ISD::AND
, SDLoc(N
), VT
, N0C
, N1C
);
5296 // canonicalize constant to RHS
5297 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
5298 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
5299 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, N1
, N0
);
5300 // fold (and x, -1) -> x
5301 if (isAllOnesConstant(N1
))
5303 // if (and x, c) is known to be zero, return 0
5304 unsigned BitWidth
= VT
.getScalarSizeInBits();
5305 if (N1C
&& DAG
.MaskedValueIsZero(SDValue(N
, 0),
5306 APInt::getAllOnesValue(BitWidth
)))
5307 return DAG
.getConstant(0, SDLoc(N
), VT
);
5309 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
5313 if (SDValue RAND
= reassociateOps(ISD::AND
, SDLoc(N
), N0
, N1
, N
->getFlags()))
5316 // Try to convert a constant mask AND into a shuffle clear mask.
5318 if (SDValue Shuffle
= XformToShuffleWithZero(N
))
5321 // fold (and (or x, C), D) -> D if (C & D) == D
5322 auto MatchSubset
= [](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
5323 return RHS
->getAPIntValue().isSubsetOf(LHS
->getAPIntValue());
5325 if (N0
.getOpcode() == ISD::OR
&&
5326 ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchSubset
))
5328 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5329 if (N1C
&& N0
.getOpcode() == ISD::ANY_EXTEND
) {
5330 SDValue N0Op0
= N0
.getOperand(0);
5331 APInt Mask
= ~N1C
->getAPIntValue();
5332 Mask
= Mask
.trunc(N0Op0
.getScalarValueSizeInBits());
5333 if (DAG
.MaskedValueIsZero(N0Op0
, Mask
)) {
5334 SDValue Zext
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
),
5335 N0
.getValueType(), N0Op0
);
5337 // Replace uses of the AND with uses of the Zero extend node.
5340 // We actually want to replace all uses of the any_extend with the
5341 // zero_extend, to avoid duplicating things. This will later cause this
5342 // AND to be folded.
5343 CombineTo(N0
.getNode(), Zext
);
5344 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5348 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5349 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5350 // already be zero by virtue of the width of the base type of the load.
5352 // the 'X' node here can either be nothing or an extract_vector_elt to catch
5354 if ((N0
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
5355 N0
.getValueSizeInBits() == N0
.getOperand(0).getScalarValueSizeInBits() &&
5356 N0
.getOperand(0).getOpcode() == ISD::LOAD
&&
5357 N0
.getOperand(0).getResNo() == 0) ||
5358 (N0
.getOpcode() == ISD::LOAD
&& N0
.getResNo() == 0)) {
5359 LoadSDNode
*Load
= cast
<LoadSDNode
>( (N0
.getOpcode() == ISD::LOAD
) ?
5360 N0
: N0
.getOperand(0) );
5362 // Get the constant (if applicable) the zero'th operand is being ANDed with.
5363 // This can be a pure constant or a vector splat, in which case we treat the
5364 // vector as a scalar and use the splat value.
5365 APInt Constant
= APInt::getNullValue(1);
5366 if (const ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N1
)) {
5367 Constant
= C
->getAPIntValue();
5368 } else if (BuildVectorSDNode
*Vector
= dyn_cast
<BuildVectorSDNode
>(N1
)) {
5369 APInt SplatValue
, SplatUndef
;
5370 unsigned SplatBitSize
;
5372 bool IsSplat
= Vector
->isConstantSplat(SplatValue
, SplatUndef
,
5373 SplatBitSize
, HasAnyUndefs
);
5375 // Undef bits can contribute to a possible optimisation if set, so
5377 SplatValue
|= SplatUndef
;
5379 // The splat value may be something like "0x00FFFFFF", which means 0 for
5380 // the first vector value and FF for the rest, repeating. We need a mask
5381 // that will apply equally to all members of the vector, so AND all the
5382 // lanes of the constant together.
5383 unsigned EltBitWidth
= Vector
->getValueType(0).getScalarSizeInBits();
5385 // If the splat value has been compressed to a bitlength lower
5386 // than the size of the vector lane, we need to re-expand it to
5388 if (EltBitWidth
> SplatBitSize
)
5389 for (SplatValue
= SplatValue
.zextOrTrunc(EltBitWidth
);
5390 SplatBitSize
< EltBitWidth
; SplatBitSize
= SplatBitSize
* 2)
5391 SplatValue
|= SplatValue
.shl(SplatBitSize
);
5393 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5394 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5395 if ((SplatBitSize
% EltBitWidth
) == 0) {
5396 Constant
= APInt::getAllOnesValue(EltBitWidth
);
5397 for (unsigned i
= 0, n
= (SplatBitSize
/ EltBitWidth
); i
< n
; ++i
)
5398 Constant
&= SplatValue
.extractBits(EltBitWidth
, i
* EltBitWidth
);
5403 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
5404 // actually legal and isn't going to get expanded, else this is a false
5406 bool CanZextLoadProfitably
= TLI
.isLoadExtLegal(ISD::ZEXTLOAD
,
5407 Load
->getValueType(0),
5408 Load
->getMemoryVT());
5410 // Resize the constant to the same size as the original memory access before
5411 // extension. If it is still the AllOnesValue then this AND is completely
5413 Constant
= Constant
.zextOrTrunc(Load
->getMemoryVT().getScalarSizeInBits());
5416 switch (Load
->getExtensionType()) {
5417 default: B
= false; break;
5418 case ISD::EXTLOAD
: B
= CanZextLoadProfitably
; break;
5420 case ISD::NON_EXTLOAD
: B
= true; break;
5423 if (B
&& Constant
.isAllOnesValue()) {
5424 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
5425 // preserve semantics once we get rid of the AND.
5426 SDValue
NewLoad(Load
, 0);
5428 // Fold the AND away. NewLoad may get replaced immediately.
5429 CombineTo(N
, (N0
.getNode() == Load
) ? NewLoad
: N0
);
5431 if (Load
->getExtensionType() == ISD::EXTLOAD
) {
5432 NewLoad
= DAG
.getLoad(Load
->getAddressingMode(), ISD::ZEXTLOAD
,
5433 Load
->getValueType(0), SDLoc(Load
),
5434 Load
->getChain(), Load
->getBasePtr(),
5435 Load
->getOffset(), Load
->getMemoryVT(),
5436 Load
->getMemOperand());
5437 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
5438 if (Load
->getNumValues() == 3) {
5439 // PRE/POST_INC loads have 3 values.
5440 SDValue To
[] = { NewLoad
.getValue(0), NewLoad
.getValue(1),
5441 NewLoad
.getValue(2) };
5442 CombineTo(Load
, To
, 3, true);
5444 CombineTo(Load
, NewLoad
.getValue(0), NewLoad
.getValue(1));
5448 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5452 // fold (and (load x), 255) -> (zextload x, i8)
5453 // fold (and (extload x, i16), 255) -> (zextload x, i8)
5454 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
5455 if (!VT
.isVector() && N1C
&& (N0
.getOpcode() == ISD::LOAD
||
5456 (N0
.getOpcode() == ISD::ANY_EXTEND
&&
5457 N0
.getOperand(0).getOpcode() == ISD::LOAD
))) {
5458 if (SDValue Res
= ReduceLoadWidth(N
)) {
5459 LoadSDNode
*LN0
= N0
->getOpcode() == ISD::ANY_EXTEND
5460 ? cast
<LoadSDNode
>(N0
.getOperand(0)) : cast
<LoadSDNode
>(N0
);
5462 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 0), Res
);
5463 return SDValue(N
, 0);
5467 if (Level
>= AfterLegalizeTypes
) {
5468 // Attempt to propagate the AND back up to the leaves which, if they're
5469 // loads, can be combined to narrow loads and the AND node can be removed.
5470 // Perform after legalization so that extend nodes will already be
5471 // combined into the loads.
5472 if (BackwardsPropagateMask(N
, DAG
)) {
5473 return SDValue(N
, 0);
5477 if (SDValue Combined
= visitANDLike(N0
, N1
, N
))
5480 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
5481 if (N0
.getOpcode() == N1
.getOpcode())
5482 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
5485 // Masking the negated extension of a boolean is just the zero-extended
5487 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
5488 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
5490 // Note: the SimplifyDemandedBits fold below can make an information-losing
5491 // transform, and then we have no way to find this better fold.
5492 if (N1C
&& N1C
->isOne() && N0
.getOpcode() == ISD::SUB
) {
5493 if (isNullOrNullSplat(N0
.getOperand(0))) {
5494 SDValue SubRHS
= N0
.getOperand(1);
5495 if (SubRHS
.getOpcode() == ISD::ZERO_EXTEND
&&
5496 SubRHS
.getOperand(0).getScalarValueSizeInBits() == 1)
5498 if (SubRHS
.getOpcode() == ISD::SIGN_EXTEND
&&
5499 SubRHS
.getOperand(0).getScalarValueSizeInBits() == 1)
5500 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), VT
, SubRHS
.getOperand(0));
5504 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
5505 // fold (and (sra)) -> (and (srl)) when possible.
5506 if (SimplifyDemandedBits(SDValue(N
, 0)))
5507 return SDValue(N
, 0);
5509 // fold (zext_inreg (extload x)) -> (zextload x)
5510 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
5511 if (ISD::isUNINDEXEDLoad(N0
.getNode()) &&
5512 (ISD::isEXTLoad(N0
.getNode()) ||
5513 (ISD::isSEXTLoad(N0
.getNode()) && N0
.hasOneUse()))) {
5514 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
5515 EVT MemVT
= LN0
->getMemoryVT();
5516 // If we zero all the possible extended bits, then we can turn this into
5517 // a zextload if we are running before legalize or the operation is legal.
5518 unsigned ExtBitSize
= N1
.getScalarValueSizeInBits();
5519 unsigned MemBitSize
= MemVT
.getScalarSizeInBits();
5520 APInt ExtBits
= APInt::getHighBitsSet(ExtBitSize
, ExtBitSize
- MemBitSize
);
5521 if (DAG
.MaskedValueIsZero(N1
, ExtBits
) &&
5522 ((!LegalOperations
&& LN0
->isSimple()) ||
5523 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
))) {
5525 DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(N0
), VT
, LN0
->getChain(),
5526 LN0
->getBasePtr(), MemVT
, LN0
->getMemOperand());
5528 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
5529 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5533 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
5534 if (N1C
&& N1C
->getAPIntValue() == 0xffff && N0
.getOpcode() == ISD::OR
) {
5535 if (SDValue BSwap
= MatchBSwapHWordLow(N0
.getNode(), N0
.getOperand(0),
5536 N0
.getOperand(1), false))
5540 if (SDValue Shifts
= unfoldExtremeBitClearingToShifts(N
))
5543 if (TLI
.hasBitTest(N0
, N1
))
5544 if (SDValue V
= combineShiftAnd1ToBitTest(N
, DAG
))
5550 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
5551 SDValue
DAGCombiner::MatchBSwapHWordLow(SDNode
*N
, SDValue N0
, SDValue N1
,
5552 bool DemandHighBits
) {
5553 if (!LegalOperations
)
5556 EVT VT
= N
->getValueType(0);
5557 if (VT
!= MVT::i64
&& VT
!= MVT::i32
&& VT
!= MVT::i16
)
5559 if (!TLI
.isOperationLegalOrCustom(ISD::BSWAP
, VT
))
5562 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
5563 bool LookPassAnd0
= false;
5564 bool LookPassAnd1
= false;
5565 if (N0
.getOpcode() == ISD::AND
&& N0
.getOperand(0).getOpcode() == ISD::SRL
)
5567 if (N1
.getOpcode() == ISD::AND
&& N1
.getOperand(0).getOpcode() == ISD::SHL
)
5569 if (N0
.getOpcode() == ISD::AND
) {
5570 if (!N0
.getNode()->hasOneUse())
5572 ConstantSDNode
*N01C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5573 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
5574 // This is needed for X86.
5575 if (!N01C
|| (N01C
->getZExtValue() != 0xFF00 &&
5576 N01C
->getZExtValue() != 0xFFFF))
5578 N0
= N0
.getOperand(0);
5579 LookPassAnd0
= true;
5582 if (N1
.getOpcode() == ISD::AND
) {
5583 if (!N1
.getNode()->hasOneUse())
5585 ConstantSDNode
*N11C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1));
5586 if (!N11C
|| N11C
->getZExtValue() != 0xFF)
5588 N1
= N1
.getOperand(0);
5589 LookPassAnd1
= true;
5592 if (N0
.getOpcode() == ISD::SRL
&& N1
.getOpcode() == ISD::SHL
)
5594 if (N0
.getOpcode() != ISD::SHL
|| N1
.getOpcode() != ISD::SRL
)
5596 if (!N0
.getNode()->hasOneUse() || !N1
.getNode()->hasOneUse())
5599 ConstantSDNode
*N01C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5600 ConstantSDNode
*N11C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1));
5603 if (N01C
->getZExtValue() != 8 || N11C
->getZExtValue() != 8)
5606 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
5607 SDValue N00
= N0
->getOperand(0);
5608 if (!LookPassAnd0
&& N00
.getOpcode() == ISD::AND
) {
5609 if (!N00
.getNode()->hasOneUse())
5611 ConstantSDNode
*N001C
= dyn_cast
<ConstantSDNode
>(N00
.getOperand(1));
5612 if (!N001C
|| N001C
->getZExtValue() != 0xFF)
5614 N00
= N00
.getOperand(0);
5615 LookPassAnd0
= true;
5618 SDValue N10
= N1
->getOperand(0);
5619 if (!LookPassAnd1
&& N10
.getOpcode() == ISD::AND
) {
5620 if (!N10
.getNode()->hasOneUse())
5622 ConstantSDNode
*N101C
= dyn_cast
<ConstantSDNode
>(N10
.getOperand(1));
5623 // Also allow 0xFFFF since the bits will be shifted out. This is needed
5625 if (!N101C
|| (N101C
->getZExtValue() != 0xFF00 &&
5626 N101C
->getZExtValue() != 0xFFFF))
5628 N10
= N10
.getOperand(0);
5629 LookPassAnd1
= true;
5635 // Make sure everything beyond the low halfword gets set to zero since the SRL
5636 // 16 will clear the top bits.
5637 unsigned OpSizeInBits
= VT
.getSizeInBits();
5638 if (DemandHighBits
&& OpSizeInBits
> 16) {
5639 // If the left-shift isn't masked out then the only way this is a bswap is
5640 // if all bits beyond the low 8 are 0. In that case the entire pattern
5641 // reduces to a left shift anyway: leave it for other parts of the combiner.
5645 // However, if the right shift isn't masked out then it might be because
5646 // it's not needed. See if we can spot that too.
5647 if (!LookPassAnd1
&&
5648 !DAG
.MaskedValueIsZero(
5649 N10
, APInt::getHighBitsSet(OpSizeInBits
, OpSizeInBits
- 16)))
5653 SDValue Res
= DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, N00
);
5654 if (OpSizeInBits
> 16) {
5656 Res
= DAG
.getNode(ISD::SRL
, DL
, VT
, Res
,
5657 DAG
.getConstant(OpSizeInBits
- 16, DL
,
5658 getShiftAmountTy(VT
)));
5663 /// Return true if the specified node is an element that makes up a 32-bit
5664 /// packed halfword byteswap.
5665 /// ((x & 0x000000ff) << 8) |
5666 /// ((x & 0x0000ff00) >> 8) |
5667 /// ((x & 0x00ff0000) << 8) |
5668 /// ((x & 0xff000000) >> 8)
5669 static bool isBSwapHWordElement(SDValue N
, MutableArrayRef
<SDNode
*> Parts
) {
5670 if (!N
.getNode()->hasOneUse())
5673 unsigned Opc
= N
.getOpcode();
5674 if (Opc
!= ISD::AND
&& Opc
!= ISD::SHL
&& Opc
!= ISD::SRL
)
5677 SDValue N0
= N
.getOperand(0);
5678 unsigned Opc0
= N0
.getOpcode();
5679 if (Opc0
!= ISD::AND
&& Opc0
!= ISD::SHL
&& Opc0
!= ISD::SRL
)
5682 ConstantSDNode
*N1C
= nullptr;
5683 // SHL or SRL: look upstream for AND mask operand
5684 if (Opc
== ISD::AND
)
5685 N1C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5686 else if (Opc0
== ISD::AND
)
5687 N1C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5691 unsigned MaskByteOffset
;
5692 switch (N1C
->getZExtValue()) {
5695 case 0xFF: MaskByteOffset
= 0; break;
5696 case 0xFF00: MaskByteOffset
= 1; break;
5698 // In case demanded bits didn't clear the bits that will be shifted out.
5699 // This is needed for X86.
5700 if (Opc
== ISD::SRL
|| (Opc
== ISD::AND
&& Opc0
== ISD::SHL
)) {
5705 case 0xFF0000: MaskByteOffset
= 2; break;
5706 case 0xFF000000: MaskByteOffset
= 3; break;
5709 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
5710 if (Opc
== ISD::AND
) {
5711 if (MaskByteOffset
== 0 || MaskByteOffset
== 2) {
5713 // (x >> 8) & 0xff0000
5714 if (Opc0
!= ISD::SRL
)
5716 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5717 if (!C
|| C
->getZExtValue() != 8)
5720 // (x << 8) & 0xff00
5721 // (x << 8) & 0xff000000
5722 if (Opc0
!= ISD::SHL
)
5724 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5725 if (!C
|| C
->getZExtValue() != 8)
5728 } else if (Opc
== ISD::SHL
) {
5730 // (x & 0xff0000) << 8
5731 if (MaskByteOffset
!= 0 && MaskByteOffset
!= 2)
5733 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5734 if (!C
|| C
->getZExtValue() != 8)
5736 } else { // Opc == ISD::SRL
5737 // (x & 0xff00) >> 8
5738 // (x & 0xff000000) >> 8
5739 if (MaskByteOffset
!= 1 && MaskByteOffset
!= 3)
5741 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5742 if (!C
|| C
->getZExtValue() != 8)
5746 if (Parts
[MaskByteOffset
])
5749 Parts
[MaskByteOffset
] = N0
.getOperand(0).getNode();
5753 /// Match a 32-bit packed halfword bswap. That is
5754 /// ((x & 0x000000ff) << 8) |
5755 /// ((x & 0x0000ff00) >> 8) |
5756 /// ((x & 0x00ff0000) << 8) |
5757 /// ((x & 0xff000000) >> 8)
5758 /// => (rotl (bswap x), 16)
5759 SDValue
DAGCombiner::MatchBSwapHWord(SDNode
*N
, SDValue N0
, SDValue N1
) {
5760 if (!LegalOperations
)
5763 EVT VT
= N
->getValueType(0);
5766 if (!TLI
.isOperationLegalOrCustom(ISD::BSWAP
, VT
))
5770 // (or (or (and), (and)), (or (and), (and)))
5771 // (or (or (or (and), (and)), (and)), (and))
5772 if (N0
.getOpcode() != ISD::OR
)
5774 SDValue N00
= N0
.getOperand(0);
5775 SDValue N01
= N0
.getOperand(1);
5776 SDNode
*Parts
[4] = {};
5778 if (N1
.getOpcode() == ISD::OR
&&
5779 N00
.getNumOperands() == 2 && N01
.getNumOperands() == 2) {
5780 // (or (or (and), (and)), (or (and), (and)))
5781 if (!isBSwapHWordElement(N00
, Parts
))
5784 if (!isBSwapHWordElement(N01
, Parts
))
5786 SDValue N10
= N1
.getOperand(0);
5787 if (!isBSwapHWordElement(N10
, Parts
))
5789 SDValue N11
= N1
.getOperand(1);
5790 if (!isBSwapHWordElement(N11
, Parts
))
5793 // (or (or (or (and), (and)), (and)), (and))
5794 if (!isBSwapHWordElement(N1
, Parts
))
5796 if (!isBSwapHWordElement(N01
, Parts
))
5798 if (N00
.getOpcode() != ISD::OR
)
5800 SDValue N000
= N00
.getOperand(0);
5801 if (!isBSwapHWordElement(N000
, Parts
))
5803 SDValue N001
= N00
.getOperand(1);
5804 if (!isBSwapHWordElement(N001
, Parts
))
5808 // Make sure the parts are all coming from the same node.
5809 if (Parts
[0] != Parts
[1] || Parts
[0] != Parts
[2] || Parts
[0] != Parts
[3])
5813 SDValue BSwap
= DAG
.getNode(ISD::BSWAP
, DL
, VT
,
5814 SDValue(Parts
[0], 0));
5816 // Result of the bswap should be rotated by 16. If it's not legal, then
5817 // do (x << 16) | (x >> 16).
5818 SDValue ShAmt
= DAG
.getConstant(16, DL
, getShiftAmountTy(VT
));
5819 if (TLI
.isOperationLegalOrCustom(ISD::ROTL
, VT
))
5820 return DAG
.getNode(ISD::ROTL
, DL
, VT
, BSwap
, ShAmt
);
5821 if (TLI
.isOperationLegalOrCustom(ISD::ROTR
, VT
))
5822 return DAG
.getNode(ISD::ROTR
, DL
, VT
, BSwap
, ShAmt
);
5823 return DAG
.getNode(ISD::OR
, DL
, VT
,
5824 DAG
.getNode(ISD::SHL
, DL
, VT
, BSwap
, ShAmt
),
5825 DAG
.getNode(ISD::SRL
, DL
, VT
, BSwap
, ShAmt
));
5828 /// This contains all DAGCombine rules which reduce two values combined by
5829 /// an Or operation to a single value \see visitANDLike().
5830 SDValue
DAGCombiner::visitORLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
5831 EVT VT
= N1
.getValueType();
5834 // fold (or x, undef) -> -1
5835 if (!LegalOperations
&& (N0
.isUndef() || N1
.isUndef()))
5836 return DAG
.getAllOnesConstant(DL
, VT
);
5838 if (SDValue V
= foldLogicOfSetCCs(false, N0
, N1
, DL
))
5841 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
5842 if (N0
.getOpcode() == ISD::AND
&& N1
.getOpcode() == ISD::AND
&&
5843 // Don't increase # computations.
5844 (N0
.getNode()->hasOneUse() || N1
.getNode()->hasOneUse())) {
5845 // We can only do this xform if we know that bits from X that are set in C2
5846 // but not in C1 are already zero. Likewise for Y.
5847 if (const ConstantSDNode
*N0O1C
=
5848 getAsNonOpaqueConstant(N0
.getOperand(1))) {
5849 if (const ConstantSDNode
*N1O1C
=
5850 getAsNonOpaqueConstant(N1
.getOperand(1))) {
5851 // We can only do this xform if we know that bits from X that are set in
5852 // C2 but not in C1 are already zero. Likewise for Y.
5853 const APInt
&LHSMask
= N0O1C
->getAPIntValue();
5854 const APInt
&RHSMask
= N1O1C
->getAPIntValue();
5856 if (DAG
.MaskedValueIsZero(N0
.getOperand(0), RHSMask
&~LHSMask
) &&
5857 DAG
.MaskedValueIsZero(N1
.getOperand(0), LHSMask
&~RHSMask
)) {
5858 SDValue X
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
,
5859 N0
.getOperand(0), N1
.getOperand(0));
5860 return DAG
.getNode(ISD::AND
, DL
, VT
, X
,
5861 DAG
.getConstant(LHSMask
| RHSMask
, DL
, VT
));
5867 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
5868 if (N0
.getOpcode() == ISD::AND
&&
5869 N1
.getOpcode() == ISD::AND
&&
5870 N0
.getOperand(0) == N1
.getOperand(0) &&
5871 // Don't increase # computations.
5872 (N0
.getNode()->hasOneUse() || N1
.getNode()->hasOneUse())) {
5873 SDValue X
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
,
5874 N0
.getOperand(1), N1
.getOperand(1));
5875 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), X
);
5881 /// OR combines for which the commuted variant will be tried as well.
5882 static SDValue
visitORCommutative(
5883 SelectionDAG
&DAG
, SDValue N0
, SDValue N1
, SDNode
*N
) {
5884 EVT VT
= N0
.getValueType();
5885 if (N0
.getOpcode() == ISD::AND
) {
5886 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
5887 if (isBitwiseNot(N0
.getOperand(1)) && N0
.getOperand(1).getOperand(0) == N1
)
5888 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
5890 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
5891 if (isBitwiseNot(N0
.getOperand(0)) && N0
.getOperand(0).getOperand(0) == N1
)
5892 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N0
.getOperand(1), N1
);
5898 SDValue
DAGCombiner::visitOR(SDNode
*N
) {
5899 SDValue N0
= N
->getOperand(0);
5900 SDValue N1
= N
->getOperand(1);
5901 EVT VT
= N1
.getValueType();
5908 if (VT
.isVector()) {
5909 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
5912 // fold (or x, 0) -> x, vector edition
5913 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
5915 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
5918 // fold (or x, -1) -> -1, vector edition
5919 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
5920 // do not return N0, because undef node may exist in N0
5921 return DAG
.getAllOnesConstant(SDLoc(N
), N0
.getValueType());
5922 if (ISD::isBuildVectorAllOnes(N1
.getNode()))
5923 // do not return N1, because undef node may exist in N1
5924 return DAG
.getAllOnesConstant(SDLoc(N
), N1
.getValueType());
5926 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
5927 // Do this only if the resulting shuffle is legal.
5928 if (isa
<ShuffleVectorSDNode
>(N0
) &&
5929 isa
<ShuffleVectorSDNode
>(N1
) &&
5930 // Avoid folding a node with illegal type.
5931 TLI
.isTypeLegal(VT
)) {
5932 bool ZeroN00
= ISD::isBuildVectorAllZeros(N0
.getOperand(0).getNode());
5933 bool ZeroN01
= ISD::isBuildVectorAllZeros(N0
.getOperand(1).getNode());
5934 bool ZeroN10
= ISD::isBuildVectorAllZeros(N1
.getOperand(0).getNode());
5935 bool ZeroN11
= ISD::isBuildVectorAllZeros(N1
.getOperand(1).getNode());
5936 // Ensure both shuffles have a zero input.
5937 if ((ZeroN00
!= ZeroN01
) && (ZeroN10
!= ZeroN11
)) {
5938 assert((!ZeroN00
|| !ZeroN01
) && "Both inputs zero!");
5939 assert((!ZeroN10
|| !ZeroN11
) && "Both inputs zero!");
5940 const ShuffleVectorSDNode
*SV0
= cast
<ShuffleVectorSDNode
>(N0
);
5941 const ShuffleVectorSDNode
*SV1
= cast
<ShuffleVectorSDNode
>(N1
);
5942 bool CanFold
= true;
5943 int NumElts
= VT
.getVectorNumElements();
5944 SmallVector
<int, 4> Mask(NumElts
);
5946 for (int i
= 0; i
!= NumElts
; ++i
) {
5947 int M0
= SV0
->getMaskElt(i
);
5948 int M1
= SV1
->getMaskElt(i
);
5950 // Determine if either index is pointing to a zero vector.
5951 bool M0Zero
= M0
< 0 || (ZeroN00
== (M0
< NumElts
));
5952 bool M1Zero
= M1
< 0 || (ZeroN10
== (M1
< NumElts
));
5954 // If one element is zero and the otherside is undef, keep undef.
5955 // This also handles the case that both are undef.
5956 if ((M0Zero
&& M1
< 0) || (M1Zero
&& M0
< 0)) {
5961 // Make sure only one of the elements is zero.
5962 if (M0Zero
== M1Zero
) {
5967 assert((M0
>= 0 || M1
>= 0) && "Undef index!");
5969 // We have a zero and non-zero element. If the non-zero came from
5970 // SV0 make the index a LHS index. If it came from SV1, make it
5971 // a RHS index. We need to mod by NumElts because we don't care
5972 // which operand it came from in the original shuffles.
5973 Mask
[i
] = M1Zero
? M0
% NumElts
: (M1
% NumElts
) + NumElts
;
5977 SDValue NewLHS
= ZeroN00
? N0
.getOperand(1) : N0
.getOperand(0);
5978 SDValue NewRHS
= ZeroN10
? N1
.getOperand(1) : N1
.getOperand(0);
5980 SDValue LegalShuffle
=
5981 TLI
.buildLegalVectorShuffle(VT
, SDLoc(N
), NewLHS
, NewRHS
,
5984 return LegalShuffle
;
5990 // fold (or c1, c2) -> c1|c2
5991 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
5992 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
5993 if (N0C
&& N1C
&& !N1C
->isOpaque())
5994 return DAG
.FoldConstantArithmetic(ISD::OR
, SDLoc(N
), VT
, N0C
, N1C
);
5995 // canonicalize constant to RHS
5996 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
5997 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
5998 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N1
, N0
);
5999 // fold (or x, 0) -> x
6000 if (isNullConstant(N1
))
6002 // fold (or x, -1) -> -1
6003 if (isAllOnesConstant(N1
))
6006 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
6009 // fold (or x, c) -> c iff (x & ~c) == 0
6010 if (N1C
&& DAG
.MaskedValueIsZero(N0
, ~N1C
->getAPIntValue()))
6013 if (SDValue Combined
= visitORLike(N0
, N1
, N
))
6016 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
6017 if (SDValue BSwap
= MatchBSwapHWord(N
, N0
, N1
))
6019 if (SDValue BSwap
= MatchBSwapHWordLow(N
, N0
, N1
))
6023 if (SDValue ROR
= reassociateOps(ISD::OR
, SDLoc(N
), N0
, N1
, N
->getFlags()))
6026 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
6027 // iff (c1 & c2) != 0 or c1/c2 are undef.
6028 auto MatchIntersect
= [](ConstantSDNode
*C1
, ConstantSDNode
*C2
) {
6029 return !C1
|| !C2
|| C1
->getAPIntValue().intersects(C2
->getAPIntValue());
6031 if (N0
.getOpcode() == ISD::AND
&& N0
.getNode()->hasOneUse() &&
6032 ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchIntersect
, true)) {
6033 if (SDValue COR
= DAG
.FoldConstantArithmetic(
6034 ISD::OR
, SDLoc(N1
), VT
, N1
.getNode(), N0
.getOperand(1).getNode())) {
6035 SDValue IOR
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
6036 AddToWorklist(IOR
.getNode());
6037 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, COR
, IOR
);
6041 if (SDValue Combined
= visitORCommutative(DAG
, N0
, N1
, N
))
6043 if (SDValue Combined
= visitORCommutative(DAG
, N1
, N0
, N
))
6046 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
6047 if (N0
.getOpcode() == N1
.getOpcode())
6048 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
6051 // See if this is some rotate idiom.
6052 if (SDNode
*Rot
= MatchRotate(N0
, N1
, SDLoc(N
)))
6053 return SDValue(Rot
, 0);
6055 if (SDValue Load
= MatchLoadCombine(N
))
6058 // Simplify the operands using demanded-bits information.
6059 if (SimplifyDemandedBits(SDValue(N
, 0)))
6060 return SDValue(N
, 0);
6062 // If OR can be rewritten into ADD, try combines based on ADD.
6063 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::ADD
, VT
)) &&
6064 DAG
.haveNoCommonBitsSet(N0
, N1
))
6065 if (SDValue Combined
= visitADDLike(N
))
6071 static SDValue
stripConstantMask(SelectionDAG
&DAG
, SDValue Op
, SDValue
&Mask
) {
6072 if (Op
.getOpcode() == ISD::AND
&&
6073 DAG
.isConstantIntBuildVectorOrConstantInt(Op
.getOperand(1))) {
6074 Mask
= Op
.getOperand(1);
6075 return Op
.getOperand(0);
6080 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
6081 static bool matchRotateHalf(SelectionDAG
&DAG
, SDValue Op
, SDValue
&Shift
,
6083 Op
= stripConstantMask(DAG
, Op
, Mask
);
6084 if (Op
.getOpcode() == ISD::SRL
|| Op
.getOpcode() == ISD::SHL
) {
6091 /// Helper function for visitOR to extract the needed side of a rotate idiom
6092 /// from a shl/srl/mul/udiv. This is meant to handle cases where
6093 /// InstCombine merged some outside op with one of the shifts from
6094 /// the rotate pattern.
6095 /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
6096 /// Otherwise, returns an expansion of \p ExtractFrom based on the following
6099 /// (or (add v v) (shrl v bitwidth-1)):
6100 /// expands (add v v) -> (shl v 1)
6102 /// (or (mul v c0) (shrl (mul v c1) c2)):
6103 /// expands (mul v c0) -> (shl (mul v c1) c3)
6105 /// (or (udiv v c0) (shl (udiv v c1) c2)):
6106 /// expands (udiv v c0) -> (shrl (udiv v c1) c3)
6108 /// (or (shl v c0) (shrl (shl v c1) c2)):
6109 /// expands (shl v c0) -> (shl (shl v c1) c3)
6111 /// (or (shrl v c0) (shl (shrl v c1) c2)):
6112 /// expands (shrl v c0) -> (shrl (shrl v c1) c3)
6114 /// Such that in all cases, c3+c2==bitwidth(op v c1).
6115 static SDValue
extractShiftForRotate(SelectionDAG
&DAG
, SDValue OppShift
,
6116 SDValue ExtractFrom
, SDValue
&Mask
,
6118 assert(OppShift
&& ExtractFrom
&& "Empty SDValue");
6120 (OppShift
.getOpcode() == ISD::SHL
|| OppShift
.getOpcode() == ISD::SRL
) &&
6121 "Existing shift must be valid as a rotate half");
6123 ExtractFrom
= stripConstantMask(DAG
, ExtractFrom
, Mask
);
6125 // Value and Type of the shift.
6126 SDValue OppShiftLHS
= OppShift
.getOperand(0);
6127 EVT ShiftedVT
= OppShiftLHS
.getValueType();
6129 // Amount of the existing shift.
6130 ConstantSDNode
*OppShiftCst
= isConstOrConstSplat(OppShift
.getOperand(1));
6132 // (add v v) -> (shl v 1)
6133 if (OppShift
.getOpcode() == ISD::SRL
&& OppShiftCst
&&
6134 ExtractFrom
.getOpcode() == ISD::ADD
&&
6135 ExtractFrom
.getOperand(0) == ExtractFrom
.getOperand(1) &&
6136 ExtractFrom
.getOperand(0) == OppShiftLHS
&&
6137 OppShiftCst
->getAPIntValue() == ShiftedVT
.getScalarSizeInBits() - 1)
6138 return DAG
.getNode(ISD::SHL
, DL
, ShiftedVT
, OppShiftLHS
,
6139 DAG
.getShiftAmountConstant(1, ShiftedVT
, DL
));
6142 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
6144 // Find opcode of the needed shift to be extracted from (op0 v c0).
6145 unsigned Opcode
= ISD::DELETED_NODE
;
6146 bool IsMulOrDiv
= false;
6147 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
6148 // opcode or its arithmetic (mul or udiv) variant.
6149 auto SelectOpcode
= [&](unsigned NeededShift
, unsigned MulOrDivVariant
) {
6150 IsMulOrDiv
= ExtractFrom
.getOpcode() == MulOrDivVariant
;
6151 if (!IsMulOrDiv
&& ExtractFrom
.getOpcode() != NeededShift
)
6153 Opcode
= NeededShift
;
6156 // op0 must be either the needed shift opcode or the mul/udiv equivalent
6157 // that the needed shift can be extracted from.
6158 if ((OppShift
.getOpcode() != ISD::SRL
|| !SelectOpcode(ISD::SHL
, ISD::MUL
)) &&
6159 (OppShift
.getOpcode() != ISD::SHL
|| !SelectOpcode(ISD::SRL
, ISD::UDIV
)))
6162 // op0 must be the same opcode on both sides, have the same LHS argument,
6163 // and produce the same value type.
6164 if (OppShiftLHS
.getOpcode() != ExtractFrom
.getOpcode() ||
6165 OppShiftLHS
.getOperand(0) != ExtractFrom
.getOperand(0) ||
6166 ShiftedVT
!= ExtractFrom
.getValueType())
6169 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
6170 ConstantSDNode
*OppLHSCst
= isConstOrConstSplat(OppShiftLHS
.getOperand(1));
6171 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
6172 ConstantSDNode
*ExtractFromCst
=
6173 isConstOrConstSplat(ExtractFrom
.getOperand(1));
6174 // TODO: We should be able to handle non-uniform constant vectors for these values
6175 // Check that we have constant values.
6176 if (!OppShiftCst
|| !OppShiftCst
->getAPIntValue() ||
6177 !OppLHSCst
|| !OppLHSCst
->getAPIntValue() ||
6178 !ExtractFromCst
|| !ExtractFromCst
->getAPIntValue())
6181 // Compute the shift amount we need to extract to complete the rotate.
6182 const unsigned VTWidth
= ShiftedVT
.getScalarSizeInBits();
6183 if (OppShiftCst
->getAPIntValue().ugt(VTWidth
))
6185 APInt NeededShiftAmt
= VTWidth
- OppShiftCst
->getAPIntValue();
6186 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
6187 APInt ExtractFromAmt
= ExtractFromCst
->getAPIntValue();
6188 APInt OppLHSAmt
= OppLHSCst
->getAPIntValue();
6189 zeroExtendToMatch(ExtractFromAmt
, OppLHSAmt
);
6191 // Now try extract the needed shift from the ExtractFrom op and see if the
6192 // result matches up with the existing shift's LHS op.
6194 // Op to extract from is a mul or udiv by a constant.
6196 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
6197 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
6198 const APInt ExtractDiv
= APInt::getOneBitSet(ExtractFromAmt
.getBitWidth(),
6199 NeededShiftAmt
.getZExtValue());
6202 APInt::udivrem(ExtractFromAmt
, ExtractDiv
, ResultAmt
, Rem
);
6203 if (Rem
!= 0 || ResultAmt
!= OppLHSAmt
)
6206 // Op to extract from is a shift by a constant.
6208 // c2 - (bitwidth(op0 v c0) - c1) == c0
6209 if (OppLHSAmt
!= ExtractFromAmt
- NeededShiftAmt
.zextOrTrunc(
6210 ExtractFromAmt
.getBitWidth()))
6214 // Return the expanded shift op that should allow a rotate to be formed.
6215 EVT ShiftVT
= OppShift
.getOperand(1).getValueType();
6216 EVT ResVT
= ExtractFrom
.getValueType();
6217 SDValue NewShiftNode
= DAG
.getConstant(NeededShiftAmt
, DL
, ShiftVT
);
6218 return DAG
.getNode(Opcode
, DL
, ResVT
, OppShiftLHS
, NewShiftNode
);
6221 // Return true if we can prove that, whenever Neg and Pos are both in the
6222 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
6223 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
6225 // (or (shift1 X, Neg), (shift2 X, Pos))
6227 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
6228 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
6229 // to consider shift amounts with defined behavior.
6230 static bool matchRotateSub(SDValue Pos
, SDValue Neg
, unsigned EltSize
,
6231 SelectionDAG
&DAG
) {
6232 // If EltSize is a power of 2 then:
6234 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
6235 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
6237 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
6238 // for the stronger condition:
6240 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
6242 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
6243 // we can just replace Neg with Neg' for the rest of the function.
6245 // In other cases we check for the even stronger condition:
6247 // Neg == EltSize - Pos [B]
6249 // for all Neg and Pos. Note that the (or ...) then invokes undefined
6250 // behavior if Pos == 0 (and consequently Neg == EltSize).
6252 // We could actually use [A] whenever EltSize is a power of 2, but the
6253 // only extra cases that it would match are those uninteresting ones
6254 // where Neg and Pos are never in range at the same time. E.g. for
6255 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
6256 // as well as (sub 32, Pos), but:
6258 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
6260 // always invokes undefined behavior for 32-bit X.
6262 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
6263 unsigned MaskLoBits
= 0;
6264 if (Neg
.getOpcode() == ISD::AND
&& isPowerOf2_64(EltSize
)) {
6265 if (ConstantSDNode
*NegC
= isConstOrConstSplat(Neg
.getOperand(1))) {
6266 KnownBits Known
= DAG
.computeKnownBits(Neg
.getOperand(0));
6267 unsigned Bits
= Log2_64(EltSize
);
6268 if (NegC
->getAPIntValue().getActiveBits() <= Bits
&&
6269 ((NegC
->getAPIntValue() | Known
.Zero
).countTrailingOnes() >= Bits
)) {
6270 Neg
= Neg
.getOperand(0);
6276 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
6277 if (Neg
.getOpcode() != ISD::SUB
)
6279 ConstantSDNode
*NegC
= isConstOrConstSplat(Neg
.getOperand(0));
6282 SDValue NegOp1
= Neg
.getOperand(1);
6284 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
6285 // Pos'. The truncation is redundant for the purpose of the equality.
6286 if (MaskLoBits
&& Pos
.getOpcode() == ISD::AND
) {
6287 if (ConstantSDNode
*PosC
= isConstOrConstSplat(Pos
.getOperand(1))) {
6288 KnownBits Known
= DAG
.computeKnownBits(Pos
.getOperand(0));
6289 if (PosC
->getAPIntValue().getActiveBits() <= MaskLoBits
&&
6290 ((PosC
->getAPIntValue() | Known
.Zero
).countTrailingOnes() >=
6292 Pos
= Pos
.getOperand(0);
6296 // The condition we need is now:
6298 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
6300 // If NegOp1 == Pos then we need:
6302 // EltSize & Mask == NegC & Mask
6304 // (because "x & Mask" is a truncation and distributes through subtraction).
6307 Width
= NegC
->getAPIntValue();
6309 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
6310 // Then the condition we want to prove becomes:
6312 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
6314 // which, again because "x & Mask" is a truncation, becomes:
6316 // NegC & Mask == (EltSize - PosC) & Mask
6317 // EltSize & Mask == (NegC + PosC) & Mask
6318 else if (Pos
.getOpcode() == ISD::ADD
&& Pos
.getOperand(0) == NegOp1
) {
6319 if (ConstantSDNode
*PosC
= isConstOrConstSplat(Pos
.getOperand(1)))
6320 Width
= PosC
->getAPIntValue() + NegC
->getAPIntValue();
6326 // Now we just need to check that EltSize & Mask == Width & Mask.
6328 // EltSize & Mask is 0 since Mask is EltSize - 1.
6329 return Width
.getLoBits(MaskLoBits
) == 0;
6330 return Width
== EltSize
;
6333 // A subroutine of MatchRotate used once we have found an OR of two opposite
6334 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
6335 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
6336 // former being preferred if supported. InnerPos and InnerNeg are Pos and
6337 // Neg with outer conversions stripped away.
6338 SDNode
*DAGCombiner::MatchRotatePosNeg(SDValue Shifted
, SDValue Pos
,
6339 SDValue Neg
, SDValue InnerPos
,
6340 SDValue InnerNeg
, unsigned PosOpcode
,
6341 unsigned NegOpcode
, const SDLoc
&DL
) {
6342 // fold (or (shl x, (*ext y)),
6343 // (srl x, (*ext (sub 32, y)))) ->
6344 // (rotl x, y) or (rotr x, (sub 32, y))
6346 // fold (or (shl x, (*ext (sub 32, y))),
6347 // (srl x, (*ext y))) ->
6348 // (rotr x, y) or (rotl x, (sub 32, y))
6349 EVT VT
= Shifted
.getValueType();
6350 if (matchRotateSub(InnerPos
, InnerNeg
, VT
.getScalarSizeInBits(), DAG
)) {
6351 bool HasPos
= TLI
.isOperationLegalOrCustom(PosOpcode
, VT
);
6352 return DAG
.getNode(HasPos
? PosOpcode
: NegOpcode
, DL
, VT
, Shifted
,
6353 HasPos
? Pos
: Neg
).getNode();
6359 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
6360 // idioms for rotate, and if the target supports rotation instructions, generate
6362 SDNode
*DAGCombiner::MatchRotate(SDValue LHS
, SDValue RHS
, const SDLoc
&DL
) {
6363 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
6364 EVT VT
= LHS
.getValueType();
6365 if (!TLI
.isTypeLegal(VT
)) return nullptr;
6367 // The target must have at least one rotate flavor.
6368 bool HasROTL
= hasOperation(ISD::ROTL
, VT
);
6369 bool HasROTR
= hasOperation(ISD::ROTR
, VT
);
6370 if (!HasROTL
&& !HasROTR
) return nullptr;
6372 // Check for truncated rotate.
6373 if (LHS
.getOpcode() == ISD::TRUNCATE
&& RHS
.getOpcode() == ISD::TRUNCATE
&&
6374 LHS
.getOperand(0).getValueType() == RHS
.getOperand(0).getValueType()) {
6375 assert(LHS
.getValueType() == RHS
.getValueType());
6376 if (SDNode
*Rot
= MatchRotate(LHS
.getOperand(0), RHS
.getOperand(0), DL
)) {
6377 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(LHS
), LHS
.getValueType(),
6378 SDValue(Rot
, 0)).getNode();
6382 // Match "(X shl/srl V1) & V2" where V2 may not be present.
6383 SDValue LHSShift
; // The shift.
6384 SDValue LHSMask
; // AND value if any.
6385 matchRotateHalf(DAG
, LHS
, LHSShift
, LHSMask
);
6387 SDValue RHSShift
; // The shift.
6388 SDValue RHSMask
; // AND value if any.
6389 matchRotateHalf(DAG
, RHS
, RHSShift
, RHSMask
);
6391 // If neither side matched a rotate half, bail
6392 if (!LHSShift
&& !RHSShift
)
6395 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
6396 // side of the rotate, so try to handle that here. In all cases we need to
6397 // pass the matched shift from the opposite side to compute the opcode and
6398 // needed shift amount to extract. We still want to do this if both sides
6399 // matched a rotate half because one half may be a potential overshift that
6400 // can be broken down (ie if InstCombine merged two shl or srl ops into a
6403 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
6405 if (SDValue NewRHSShift
=
6406 extractShiftForRotate(DAG
, LHSShift
, RHS
, RHSMask
, DL
))
6407 RHSShift
= NewRHSShift
;
6408 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
6410 if (SDValue NewLHSShift
=
6411 extractShiftForRotate(DAG
, RHSShift
, LHS
, LHSMask
, DL
))
6412 LHSShift
= NewLHSShift
;
6414 // If a side is still missing, nothing else we can do.
6415 if (!RHSShift
|| !LHSShift
)
6418 // At this point we've matched or extracted a shift op on each side.
6420 if (LHSShift
.getOperand(0) != RHSShift
.getOperand(0))
6421 return nullptr; // Not shifting the same value.
6423 if (LHSShift
.getOpcode() == RHSShift
.getOpcode())
6424 return nullptr; // Shifts must disagree.
6426 // Canonicalize shl to left side in a shl/srl pair.
6427 if (RHSShift
.getOpcode() == ISD::SHL
) {
6428 std::swap(LHS
, RHS
);
6429 std::swap(LHSShift
, RHSShift
);
6430 std::swap(LHSMask
, RHSMask
);
6433 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
6434 SDValue LHSShiftArg
= LHSShift
.getOperand(0);
6435 SDValue LHSShiftAmt
= LHSShift
.getOperand(1);
6436 SDValue RHSShiftArg
= RHSShift
.getOperand(0);
6437 SDValue RHSShiftAmt
= RHSShift
.getOperand(1);
6439 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
6440 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
6441 auto MatchRotateSum
= [EltSizeInBits
](ConstantSDNode
*LHS
,
6442 ConstantSDNode
*RHS
) {
6443 return (LHS
->getAPIntValue() + RHS
->getAPIntValue()) == EltSizeInBits
;
6445 if (ISD::matchBinaryPredicate(LHSShiftAmt
, RHSShiftAmt
, MatchRotateSum
)) {
6446 SDValue Rot
= DAG
.getNode(HasROTL
? ISD::ROTL
: ISD::ROTR
, DL
, VT
,
6447 LHSShiftArg
, HasROTL
? LHSShiftAmt
: RHSShiftAmt
);
6449 // If there is an AND of either shifted operand, apply it to the result.
6450 if (LHSMask
.getNode() || RHSMask
.getNode()) {
6451 SDValue AllOnes
= DAG
.getAllOnesConstant(DL
, VT
);
6452 SDValue Mask
= AllOnes
;
6454 if (LHSMask
.getNode()) {
6455 SDValue RHSBits
= DAG
.getNode(ISD::SRL
, DL
, VT
, AllOnes
, RHSShiftAmt
);
6456 Mask
= DAG
.getNode(ISD::AND
, DL
, VT
, Mask
,
6457 DAG
.getNode(ISD::OR
, DL
, VT
, LHSMask
, RHSBits
));
6459 if (RHSMask
.getNode()) {
6460 SDValue LHSBits
= DAG
.getNode(ISD::SHL
, DL
, VT
, AllOnes
, LHSShiftAmt
);
6461 Mask
= DAG
.getNode(ISD::AND
, DL
, VT
, Mask
,
6462 DAG
.getNode(ISD::OR
, DL
, VT
, RHSMask
, LHSBits
));
6465 Rot
= DAG
.getNode(ISD::AND
, DL
, VT
, Rot
, Mask
);
6468 return Rot
.getNode();
6471 // If there is a mask here, and we have a variable shift, we can't be sure
6472 // that we're masking out the right stuff.
6473 if (LHSMask
.getNode() || RHSMask
.getNode())
6476 // If the shift amount is sign/zext/any-extended just peel it off.
6477 SDValue LExtOp0
= LHSShiftAmt
;
6478 SDValue RExtOp0
= RHSShiftAmt
;
6479 if ((LHSShiftAmt
.getOpcode() == ISD::SIGN_EXTEND
||
6480 LHSShiftAmt
.getOpcode() == ISD::ZERO_EXTEND
||
6481 LHSShiftAmt
.getOpcode() == ISD::ANY_EXTEND
||
6482 LHSShiftAmt
.getOpcode() == ISD::TRUNCATE
) &&
6483 (RHSShiftAmt
.getOpcode() == ISD::SIGN_EXTEND
||
6484 RHSShiftAmt
.getOpcode() == ISD::ZERO_EXTEND
||
6485 RHSShiftAmt
.getOpcode() == ISD::ANY_EXTEND
||
6486 RHSShiftAmt
.getOpcode() == ISD::TRUNCATE
)) {
6487 LExtOp0
= LHSShiftAmt
.getOperand(0);
6488 RExtOp0
= RHSShiftAmt
.getOperand(0);
6491 SDNode
*TryL
= MatchRotatePosNeg(LHSShiftArg
, LHSShiftAmt
, RHSShiftAmt
,
6492 LExtOp0
, RExtOp0
, ISD::ROTL
, ISD::ROTR
, DL
);
6496 SDNode
*TryR
= MatchRotatePosNeg(RHSShiftArg
, RHSShiftAmt
, LHSShiftAmt
,
6497 RExtOp0
, LExtOp0
, ISD::ROTR
, ISD::ROTL
, DL
);
6506 /// Represents known origin of an individual byte in load combine pattern. The
6507 /// value of the byte is either constant zero or comes from memory.
6508 struct ByteProvider
{
6509 // For constant zero providers Load is set to nullptr. For memory providers
6510 // Load represents the node which loads the byte from memory.
6511 // ByteOffset is the offset of the byte in the value produced by the load.
6512 LoadSDNode
*Load
= nullptr;
6513 unsigned ByteOffset
= 0;
6515 ByteProvider() = default;
6517 static ByteProvider
getMemory(LoadSDNode
*Load
, unsigned ByteOffset
) {
6518 return ByteProvider(Load
, ByteOffset
);
6521 static ByteProvider
getConstantZero() { return ByteProvider(nullptr, 0); }
6523 bool isConstantZero() const { return !Load
; }
6524 bool isMemory() const { return Load
; }
6526 bool operator==(const ByteProvider
&Other
) const {
6527 return Other
.Load
== Load
&& Other
.ByteOffset
== ByteOffset
;
6531 ByteProvider(LoadSDNode
*Load
, unsigned ByteOffset
)
6532 : Load(Load
), ByteOffset(ByteOffset
) {}
6535 } // end anonymous namespace
6537 /// Recursively traverses the expression calculating the origin of the requested
6538 /// byte of the given value. Returns None if the provider can't be calculated.
6540 /// For all the values except the root of the expression verifies that the value
6541 /// has exactly one use and if it's not true return None. This way if the origin
6542 /// of the byte is returned it's guaranteed that the values which contribute to
6543 /// the byte are not used outside of this expression.
6545 /// Because the parts of the expression are not allowed to have more than one
6546 /// use this function iterates over trees, not DAGs. So it never visits the same
6547 /// node more than once.
6548 static const Optional
<ByteProvider
>
6549 calculateByteProvider(SDValue Op
, unsigned Index
, unsigned Depth
,
6550 bool Root
= false) {
6551 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
6555 if (!Root
&& !Op
.hasOneUse())
6558 assert(Op
.getValueType().isScalarInteger() && "can't handle other types");
6559 unsigned BitWidth
= Op
.getValueSizeInBits();
6560 if (BitWidth
% 8 != 0)
6562 unsigned ByteWidth
= BitWidth
/ 8;
6563 assert(Index
< ByteWidth
&& "invalid index requested");
6566 switch (Op
.getOpcode()) {
6568 auto LHS
= calculateByteProvider(Op
->getOperand(0), Index
, Depth
+ 1);
6571 auto RHS
= calculateByteProvider(Op
->getOperand(1), Index
, Depth
+ 1);
6575 if (LHS
->isConstantZero())
6577 if (RHS
->isConstantZero())
6582 auto ShiftOp
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1));
6586 uint64_t BitShift
= ShiftOp
->getZExtValue();
6587 if (BitShift
% 8 != 0)
6589 uint64_t ByteShift
= BitShift
/ 8;
6591 return Index
< ByteShift
6592 ? ByteProvider::getConstantZero()
6593 : calculateByteProvider(Op
->getOperand(0), Index
- ByteShift
,
6596 case ISD::ANY_EXTEND
:
6597 case ISD::SIGN_EXTEND
:
6598 case ISD::ZERO_EXTEND
: {
6599 SDValue NarrowOp
= Op
->getOperand(0);
6600 unsigned NarrowBitWidth
= NarrowOp
.getScalarValueSizeInBits();
6601 if (NarrowBitWidth
% 8 != 0)
6603 uint64_t NarrowByteWidth
= NarrowBitWidth
/ 8;
6605 if (Index
>= NarrowByteWidth
)
6606 return Op
.getOpcode() == ISD::ZERO_EXTEND
6607 ? Optional
<ByteProvider
>(ByteProvider::getConstantZero())
6609 return calculateByteProvider(NarrowOp
, Index
, Depth
+ 1);
6612 return calculateByteProvider(Op
->getOperand(0), ByteWidth
- Index
- 1,
6615 auto L
= cast
<LoadSDNode
>(Op
.getNode());
6616 if (!L
->isSimple() || L
->isIndexed())
6619 unsigned NarrowBitWidth
= L
->getMemoryVT().getSizeInBits();
6620 if (NarrowBitWidth
% 8 != 0)
6622 uint64_t NarrowByteWidth
= NarrowBitWidth
/ 8;
6624 if (Index
>= NarrowByteWidth
)
6625 return L
->getExtensionType() == ISD::ZEXTLOAD
6626 ? Optional
<ByteProvider
>(ByteProvider::getConstantZero())
6628 return ByteProvider::getMemory(L
, Index
);
6635 static unsigned LittleEndianByteAt(unsigned BW
, unsigned i
) {
6639 static unsigned BigEndianByteAt(unsigned BW
, unsigned i
) {
6643 // Check if the bytes offsets we are looking at match with either big or
6644 // little endian value loaded. Return true for big endian, false for little
6645 // endian, and None if match failed.
6646 static Optional
<bool> isBigEndian(const SmallVector
<int64_t, 4> &ByteOffsets
,
6647 int64_t FirstOffset
) {
6648 // The endian can be decided only when it is 2 bytes at least.
6649 unsigned Width
= ByteOffsets
.size();
6653 bool BigEndian
= true, LittleEndian
= true;
6654 for (unsigned i
= 0; i
< Width
; i
++) {
6655 int64_t CurrentByteOffset
= ByteOffsets
[i
] - FirstOffset
;
6656 LittleEndian
&= CurrentByteOffset
== LittleEndianByteAt(Width
, i
);
6657 BigEndian
&= CurrentByteOffset
== BigEndianByteAt(Width
, i
);
6658 if (!BigEndian
&& !LittleEndian
)
6662 assert((BigEndian
!= LittleEndian
) && "It should be either big endian or"
6667 static SDValue
stripTruncAndExt(SDValue Value
) {
6668 switch (Value
.getOpcode()) {
6670 case ISD::ZERO_EXTEND
:
6671 case ISD::SIGN_EXTEND
:
6672 case ISD::ANY_EXTEND
:
6673 return stripTruncAndExt(Value
.getOperand(0));
6678 /// Match a pattern where a wide type scalar value is stored by several narrow
6679 /// stores. Fold it into a single store or a BSWAP and a store if the targets
6682 /// Assuming little endian target:
6685 /// p[0] = (val >> 0) & 0xFF;
6686 /// p[1] = (val >> 8) & 0xFF;
6687 /// p[2] = (val >> 16) & 0xFF;
6688 /// p[3] = (val >> 24) & 0xFF;
6690 /// *((i32)p) = val;
6694 /// p[0] = (val >> 24) & 0xFF;
6695 /// p[1] = (val >> 16) & 0xFF;
6696 /// p[2] = (val >> 8) & 0xFF;
6697 /// p[3] = (val >> 0) & 0xFF;
6699 /// *((i32)p) = BSWAP(val);
6700 SDValue
DAGCombiner::MatchStoreCombine(StoreSDNode
*N
) {
6701 // Collect all the stores in the chain.
6703 SmallVector
<StoreSDNode
*, 8> Stores
;
6704 for (StoreSDNode
*Store
= N
; Store
; Store
= dyn_cast
<StoreSDNode
>(Chain
)) {
6705 // TODO: Allow unordered atomics when wider type is legal (see D66309)
6706 if (Store
->getMemoryVT() != MVT::i8
||
6707 !Store
->isSimple() || Store
->isIndexed())
6709 Stores
.push_back(Store
);
6710 Chain
= Store
->getChain();
6712 // Handle the simple type only.
6713 unsigned Width
= Stores
.size();
6714 EVT VT
= EVT::getIntegerVT(
6715 *DAG
.getContext(), Width
* N
->getMemoryVT().getSizeInBits());
6716 if (VT
!= MVT::i16
&& VT
!= MVT::i32
&& VT
!= MVT::i64
)
6719 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6720 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::STORE
, VT
))
6723 // Check if all the bytes of the combined value we are looking at are stored
6724 // to the same base address. Collect bytes offsets from Base address into
6726 SDValue CombinedValue
;
6727 SmallVector
<int64_t, 4> ByteOffsets(Width
, INT64_MAX
);
6728 int64_t FirstOffset
= INT64_MAX
;
6729 StoreSDNode
*FirstStore
= nullptr;
6730 Optional
<BaseIndexOffset
> Base
;
6731 for (auto Store
: Stores
) {
6732 // All the stores store different byte of the CombinedValue. A truncate is
6733 // required to get that byte value.
6734 SDValue Trunc
= Store
->getValue();
6735 if (Trunc
.getOpcode() != ISD::TRUNCATE
)
6737 // A shift operation is required to get the right byte offset, except the
6740 SDValue Value
= Trunc
.getOperand(0);
6741 if (Value
.getOpcode() == ISD::SRL
||
6742 Value
.getOpcode() == ISD::SRA
) {
6743 ConstantSDNode
*ShiftOffset
=
6744 dyn_cast
<ConstantSDNode
>(Value
.getOperand(1));
6745 // Trying to match the following pattern. The shift offset must be
6746 // a constant and a multiple of 8. It is the byte offset in "y".
6748 // x = srl y, offset
6751 if (!ShiftOffset
|| (ShiftOffset
->getSExtValue() % 8))
6754 Offset
= ShiftOffset
->getSExtValue()/8;
6755 Value
= Value
.getOperand(0);
6758 // Stores must share the same combined value with different offsets.
6760 CombinedValue
= Value
;
6761 else if (stripTruncAndExt(CombinedValue
) != stripTruncAndExt(Value
))
6764 // The trunc and all the extend operation should be stripped to get the
6765 // real value we are stored.
6766 else if (CombinedValue
.getValueType() != VT
) {
6767 if (Value
.getValueType() == VT
||
6768 Value
.getValueSizeInBits() > CombinedValue
.getValueSizeInBits())
6769 CombinedValue
= Value
;
6770 // Give up if the combined value type is smaller than the store size.
6771 if (CombinedValue
.getValueSizeInBits() < VT
.getSizeInBits())
6775 // Stores must share the same base address
6776 BaseIndexOffset Ptr
= BaseIndexOffset::match(Store
, DAG
);
6777 int64_t ByteOffsetFromBase
= 0;
6780 else if (!Base
->equalBaseIndex(Ptr
, DAG
, ByteOffsetFromBase
))
6783 // Remember the first byte store
6784 if (ByteOffsetFromBase
< FirstOffset
) {
6786 FirstOffset
= ByteOffsetFromBase
;
6788 // Map the offset in the store and the offset in the combined value, and
6789 // early return if it has been set before.
6790 if (Offset
< 0 || Offset
>= Width
|| ByteOffsets
[Offset
] != INT64_MAX
)
6792 ByteOffsets
[Offset
] = ByteOffsetFromBase
;
6795 assert(FirstOffset
!= INT64_MAX
&& "First byte offset must be set");
6796 assert(FirstStore
&& "First store must be set");
6798 // Check if the bytes of the combined value we are looking at match with
6799 // either big or little endian value store.
6800 Optional
<bool> IsBigEndian
= isBigEndian(ByteOffsets
, FirstOffset
);
6801 if (!IsBigEndian
.hasValue())
6804 // The node we are looking at matches with the pattern, check if we can
6805 // replace it with a single bswap if needed and store.
6807 // If the store needs byte swap check if the target supports it
6808 bool NeedsBswap
= DAG
.getDataLayout().isBigEndian() != *IsBigEndian
;
6810 // Before legalize we can introduce illegal bswaps which will be later
6811 // converted to an explicit bswap sequence. This way we end up with a single
6812 // store and byte shuffling instead of several stores and byte shuffling.
6813 if (NeedsBswap
&& LegalOperations
&& !TLI
.isOperationLegal(ISD::BSWAP
, VT
))
6816 // Check that a store of the wide type is both allowed and fast on the target
6819 TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(), VT
,
6820 *FirstStore
->getMemOperand(), &Fast
);
6821 if (!Allowed
|| !Fast
)
6824 if (VT
!= CombinedValue
.getValueType()) {
6825 assert(CombinedValue
.getValueType().getSizeInBits() > VT
.getSizeInBits() &&
6826 "Get unexpected store value to combine");
6827 CombinedValue
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
,
6832 CombinedValue
= DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, CombinedValue
);
6835 DAG
.getStore(Chain
, SDLoc(N
), CombinedValue
, FirstStore
->getBasePtr(),
6836 FirstStore
->getPointerInfo(), FirstStore
->getAlignment());
6838 // Rely on other DAG combine rules to remove the other individual stores.
6839 DAG
.ReplaceAllUsesWith(N
, NewStore
.getNode());
6843 /// Match a pattern where a wide type scalar value is loaded by several narrow
6844 /// loads and combined by shifts and ors. Fold it into a single load or a load
6845 /// and a BSWAP if the targets supports it.
6847 /// Assuming little endian target:
6849 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
6851 /// i32 val = *((i32)a)
6854 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
6856 /// i32 val = BSWAP(*((i32)a))
6858 /// TODO: This rule matches complex patterns with OR node roots and doesn't
6859 /// interact well with the worklist mechanism. When a part of the pattern is
6860 /// updated (e.g. one of the loads) its direct users are put into the worklist,
6861 /// but the root node of the pattern which triggers the load combine is not
6862 /// necessarily a direct user of the changed node. For example, once the address
6863 /// of t28 load is reassociated load combine won't be triggered:
6864 /// t25: i32 = add t4, Constant:i32<2>
6865 /// t26: i64 = sign_extend t25
6866 /// t27: i64 = add t2, t26
6867 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
6868 /// t29: i32 = zero_extend t28
6869 /// t32: i32 = shl t29, Constant:i8<8>
6870 /// t33: i32 = or t23, t32
6871 /// As a possible fix visitLoad can check if the load can be a part of a load
6872 /// combine pattern and add corresponding OR roots to the worklist.
6873 SDValue
DAGCombiner::MatchLoadCombine(SDNode
*N
) {
6874 assert(N
->getOpcode() == ISD::OR
&&
6875 "Can only match load combining against OR nodes");
6877 // Handles simple types only
6878 EVT VT
= N
->getValueType(0);
6879 if (VT
!= MVT::i16
&& VT
!= MVT::i32
&& VT
!= MVT::i64
)
6881 unsigned ByteWidth
= VT
.getSizeInBits() / 8;
6883 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6884 // Before legalize we can introduce too wide illegal loads which will be later
6885 // split into legal sized loads. This enables us to combine i64 load by i8
6886 // patterns to a couple of i32 loads on 32 bit targets.
6887 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::LOAD
, VT
))
6890 bool IsBigEndianTarget
= DAG
.getDataLayout().isBigEndian();
6891 auto MemoryByteOffset
= [&] (ByteProvider P
) {
6892 assert(P
.isMemory() && "Must be a memory byte provider");
6893 unsigned LoadBitWidth
= P
.Load
->getMemoryVT().getSizeInBits();
6894 assert(LoadBitWidth
% 8 == 0 &&
6895 "can only analyze providers for individual bytes not bit");
6896 unsigned LoadByteWidth
= LoadBitWidth
/ 8;
6897 return IsBigEndianTarget
6898 ? BigEndianByteAt(LoadByteWidth
, P
.ByteOffset
)
6899 : LittleEndianByteAt(LoadByteWidth
, P
.ByteOffset
);
6902 Optional
<BaseIndexOffset
> Base
;
6905 SmallPtrSet
<LoadSDNode
*, 8> Loads
;
6906 Optional
<ByteProvider
> FirstByteProvider
;
6907 int64_t FirstOffset
= INT64_MAX
;
6909 // Check if all the bytes of the OR we are looking at are loaded from the same
6910 // base address. Collect bytes offsets from Base address in ByteOffsets.
6911 SmallVector
<int64_t, 4> ByteOffsets(ByteWidth
);
6912 for (unsigned i
= 0; i
< ByteWidth
; i
++) {
6913 auto P
= calculateByteProvider(SDValue(N
, 0), i
, 0, /*Root=*/true);
6914 if (!P
|| !P
->isMemory()) // All the bytes must be loaded from memory
6917 LoadSDNode
*L
= P
->Load
;
6918 assert(L
->hasNUsesOfValue(1, 0) && L
->isSimple() &&
6920 "Must be enforced by calculateByteProvider");
6921 assert(L
->getOffset().isUndef() && "Unindexed load must have undef offset");
6923 // All loads must share the same chain
6924 SDValue LChain
= L
->getChain();
6927 else if (Chain
!= LChain
)
6930 // Loads must share the same base address
6931 BaseIndexOffset Ptr
= BaseIndexOffset::match(L
, DAG
);
6932 int64_t ByteOffsetFromBase
= 0;
6935 else if (!Base
->equalBaseIndex(Ptr
, DAG
, ByteOffsetFromBase
))
6938 // Calculate the offset of the current byte from the base address
6939 ByteOffsetFromBase
+= MemoryByteOffset(*P
);
6940 ByteOffsets
[i
] = ByteOffsetFromBase
;
6942 // Remember the first byte load
6943 if (ByteOffsetFromBase
< FirstOffset
) {
6944 FirstByteProvider
= P
;
6945 FirstOffset
= ByteOffsetFromBase
;
6950 assert(!Loads
.empty() && "All the bytes of the value must be loaded from "
6951 "memory, so there must be at least one load which produces the value");
6952 assert(Base
&& "Base address of the accessed memory location must be set");
6953 assert(FirstOffset
!= INT64_MAX
&& "First byte offset must be set");
6955 // Check if the bytes of the OR we are looking at match with either big or
6956 // little endian value load
6957 Optional
<bool> IsBigEndian
= isBigEndian(ByteOffsets
, FirstOffset
);
6958 if (!IsBigEndian
.hasValue())
6961 assert(FirstByteProvider
&& "must be set");
6963 // Ensure that the first byte is loaded from zero offset of the first load.
6964 // So the combined value can be loaded from the first load address.
6965 if (MemoryByteOffset(*FirstByteProvider
) != 0)
6967 LoadSDNode
*FirstLoad
= FirstByteProvider
->Load
;
6969 // The node we are looking at matches with the pattern, check if we can
6970 // replace it with a single load and bswap if needed.
6972 // If the load needs byte swap check if the target supports it
6973 bool NeedsBswap
= IsBigEndianTarget
!= *IsBigEndian
;
6975 // Before legalize we can introduce illegal bswaps which will be later
6976 // converted to an explicit bswap sequence. This way we end up with a single
6977 // load and byte shuffling instead of several loads and byte shuffling.
6978 if (NeedsBswap
&& LegalOperations
&& !TLI
.isOperationLegal(ISD::BSWAP
, VT
))
6981 // Check that a load of the wide type is both allowed and fast on the target
6983 bool Allowed
= TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(),
6984 VT
, *FirstLoad
->getMemOperand(), &Fast
);
6985 if (!Allowed
|| !Fast
)
6989 DAG
.getLoad(VT
, SDLoc(N
), Chain
, FirstLoad
->getBasePtr(),
6990 FirstLoad
->getPointerInfo(), FirstLoad
->getAlignment());
6992 // Transfer chain users from old loads to the new load.
6993 for (LoadSDNode
*L
: Loads
)
6994 DAG
.ReplaceAllUsesOfValueWith(SDValue(L
, 1), SDValue(NewLoad
.getNode(), 1));
6996 return NeedsBswap
? DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, NewLoad
) : NewLoad
;
6999 // If the target has andn, bsl, or a similar bit-select instruction,
7000 // we want to unfold masked merge, with canonical pattern of:
7002 // ((x ^ y) & m) ^ y
7005 // (x & m) | (y & ~m)
7006 // If y is a constant, and the 'andn' does not work with immediates,
7007 // we unfold into a different pattern:
7008 // ~(~x & m) & (m | y)
7009 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
7010 // the very least that breaks andnpd / andnps patterns, and because those
7011 // patterns are simplified in IR and shouldn't be created in the DAG
7012 SDValue
DAGCombiner::unfoldMaskedMerge(SDNode
*N
) {
7013 assert(N
->getOpcode() == ISD::XOR
);
7015 // Don't touch 'not' (i.e. where y = -1).
7016 if (isAllOnesOrAllOnesSplat(N
->getOperand(1)))
7019 EVT VT
= N
->getValueType(0);
7021 // There are 3 commutable operators in the pattern,
7022 // so we have to deal with 8 possible variants of the basic pattern.
7024 auto matchAndXor
= [&X
, &Y
, &M
](SDValue And
, unsigned XorIdx
, SDValue Other
) {
7025 if (And
.getOpcode() != ISD::AND
|| !And
.hasOneUse())
7027 SDValue Xor
= And
.getOperand(XorIdx
);
7028 if (Xor
.getOpcode() != ISD::XOR
|| !Xor
.hasOneUse())
7030 SDValue Xor0
= Xor
.getOperand(0);
7031 SDValue Xor1
= Xor
.getOperand(1);
7032 // Don't touch 'not' (i.e. where y = -1).
7033 if (isAllOnesOrAllOnesSplat(Xor1
))
7036 std::swap(Xor0
, Xor1
);
7041 M
= And
.getOperand(XorIdx
? 0 : 1);
7045 SDValue N0
= N
->getOperand(0);
7046 SDValue N1
= N
->getOperand(1);
7047 if (!matchAndXor(N0
, 0, N1
) && !matchAndXor(N0
, 1, N1
) &&
7048 !matchAndXor(N1
, 0, N0
) && !matchAndXor(N1
, 1, N0
))
7051 // Don't do anything if the mask is constant. This should not be reachable.
7052 // InstCombine should have already unfolded this pattern, and DAGCombiner
7053 // probably shouldn't produce it, too.
7054 if (isa
<ConstantSDNode
>(M
.getNode()))
7057 // We can transform if the target has AndNot
7058 if (!TLI
.hasAndNot(M
))
7063 // If Y is a constant, check that 'andn' works with immediates.
7064 if (!TLI
.hasAndNot(Y
)) {
7065 assert(TLI
.hasAndNot(X
) && "Only mask is a variable? Unreachable.");
7066 // If not, we need to do a bit more work to make sure andn is still used.
7067 SDValue NotX
= DAG
.getNOT(DL
, X
, VT
);
7068 SDValue LHS
= DAG
.getNode(ISD::AND
, DL
, VT
, NotX
, M
);
7069 SDValue NotLHS
= DAG
.getNOT(DL
, LHS
, VT
);
7070 SDValue RHS
= DAG
.getNode(ISD::OR
, DL
, VT
, M
, Y
);
7071 return DAG
.getNode(ISD::AND
, DL
, VT
, NotLHS
, RHS
);
7074 SDValue LHS
= DAG
.getNode(ISD::AND
, DL
, VT
, X
, M
);
7075 SDValue NotM
= DAG
.getNOT(DL
, M
, VT
);
7076 SDValue RHS
= DAG
.getNode(ISD::AND
, DL
, VT
, Y
, NotM
);
7078 return DAG
.getNode(ISD::OR
, DL
, VT
, LHS
, RHS
);
7081 SDValue
DAGCombiner::visitXOR(SDNode
*N
) {
7082 SDValue N0
= N
->getOperand(0);
7083 SDValue N1
= N
->getOperand(1);
7084 EVT VT
= N0
.getValueType();
7087 if (VT
.isVector()) {
7088 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7091 // fold (xor x, 0) -> x, vector edition
7092 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
7094 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
7098 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
7100 if (N0
.isUndef() && N1
.isUndef())
7101 return DAG
.getConstant(0, DL
, VT
);
7102 // fold (xor x, undef) -> undef
7107 // fold (xor c1, c2) -> c1^c2
7108 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7109 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
7111 return DAG
.FoldConstantArithmetic(ISD::XOR
, DL
, VT
, N0C
, N1C
);
7112 // canonicalize constant to RHS
7113 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
7114 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
7115 return DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
);
7116 // fold (xor x, 0) -> x
7117 if (isNullConstant(N1
))
7120 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7124 if (SDValue RXOR
= reassociateOps(ISD::XOR
, DL
, N0
, N1
, N
->getFlags()))
7127 // fold !(x cc y) -> (x !cc y)
7128 unsigned N0Opcode
= N0
.getOpcode();
7129 SDValue LHS
, RHS
, CC
;
7130 if (TLI
.isConstTrueVal(N1
.getNode()) && isSetCCEquivalent(N0
, LHS
, RHS
, CC
)) {
7131 ISD::CondCode NotCC
= ISD::getSetCCInverse(cast
<CondCodeSDNode
>(CC
)->get(),
7132 LHS
.getValueType().isInteger());
7133 if (!LegalOperations
||
7134 TLI
.isCondCodeLegal(NotCC
, LHS
.getSimpleValueType())) {
7137 llvm_unreachable("Unhandled SetCC Equivalent!");
7139 return DAG
.getSetCC(SDLoc(N0
), VT
, LHS
, RHS
, NotCC
);
7140 case ISD::SELECT_CC
:
7141 return DAG
.getSelectCC(SDLoc(N0
), LHS
, RHS
, N0
.getOperand(2),
7142 N0
.getOperand(3), NotCC
);
7147 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
7148 if (isOneConstant(N1
) && N0Opcode
== ISD::ZERO_EXTEND
&& N0
.hasOneUse() &&
7149 isSetCCEquivalent(N0
.getOperand(0), LHS
, RHS
, CC
)){
7150 SDValue V
= N0
.getOperand(0);
7152 V
= DAG
.getNode(ISD::XOR
, DL0
, V
.getValueType(), V
,
7153 DAG
.getConstant(1, DL0
, V
.getValueType()));
7154 AddToWorklist(V
.getNode());
7155 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, V
);
7158 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
7159 if (isOneConstant(N1
) && VT
== MVT::i1
&& N0
.hasOneUse() &&
7160 (N0Opcode
== ISD::OR
|| N0Opcode
== ISD::AND
)) {
7161 SDValue N00
= N0
.getOperand(0), N01
= N0
.getOperand(1);
7162 if (isOneUseSetCC(N01
) || isOneUseSetCC(N00
)) {
7163 unsigned NewOpcode
= N0Opcode
== ISD::AND
? ISD::OR
: ISD::AND
;
7164 N00
= DAG
.getNode(ISD::XOR
, SDLoc(N00
), VT
, N00
, N1
); // N00 = ~N00
7165 N01
= DAG
.getNode(ISD::XOR
, SDLoc(N01
), VT
, N01
, N1
); // N01 = ~N01
7166 AddToWorklist(N00
.getNode()); AddToWorklist(N01
.getNode());
7167 return DAG
.getNode(NewOpcode
, DL
, VT
, N00
, N01
);
7170 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
7171 if (isAllOnesConstant(N1
) && N0
.hasOneUse() &&
7172 (N0Opcode
== ISD::OR
|| N0Opcode
== ISD::AND
)) {
7173 SDValue N00
= N0
.getOperand(0), N01
= N0
.getOperand(1);
7174 if (isa
<ConstantSDNode
>(N01
) || isa
<ConstantSDNode
>(N00
)) {
7175 unsigned NewOpcode
= N0Opcode
== ISD::AND
? ISD::OR
: ISD::AND
;
7176 N00
= DAG
.getNode(ISD::XOR
, SDLoc(N00
), VT
, N00
, N1
); // N00 = ~N00
7177 N01
= DAG
.getNode(ISD::XOR
, SDLoc(N01
), VT
, N01
, N1
); // N01 = ~N01
7178 AddToWorklist(N00
.getNode()); AddToWorklist(N01
.getNode());
7179 return DAG
.getNode(NewOpcode
, DL
, VT
, N00
, N01
);
7183 // fold (not (neg x)) -> (add X, -1)
7184 // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
7185 // Y is a constant or the subtract has a single use.
7186 if (isAllOnesConstant(N1
) && N0
.getOpcode() == ISD::SUB
&&
7187 isNullConstant(N0
.getOperand(0))) {
7188 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(1),
7189 DAG
.getAllOnesConstant(DL
, VT
));
7192 // fold (xor (and x, y), y) -> (and (not x), y)
7193 if (N0Opcode
== ISD::AND
&& N0
.hasOneUse() && N0
->getOperand(1) == N1
) {
7194 SDValue X
= N0
.getOperand(0);
7195 SDValue NotX
= DAG
.getNOT(SDLoc(X
), X
, VT
);
7196 AddToWorklist(NotX
.getNode());
7197 return DAG
.getNode(ISD::AND
, DL
, VT
, NotX
, N1
);
7200 if ((N0Opcode
== ISD::SRL
|| N0Opcode
== ISD::SHL
) && N0
.hasOneUse()) {
7201 ConstantSDNode
*XorC
= isConstOrConstSplat(N1
);
7202 ConstantSDNode
*ShiftC
= isConstOrConstSplat(N0
.getOperand(1));
7203 unsigned BitWidth
= VT
.getScalarSizeInBits();
7204 if (XorC
&& ShiftC
) {
7205 // Don't crash on an oversized shift. We can not guarantee that a bogus
7206 // shift has been simplified to undef.
7207 uint64_t ShiftAmt
= ShiftC
->getLimitedValue();
7208 if (ShiftAmt
< BitWidth
) {
7209 APInt Ones
= APInt::getAllOnesValue(BitWidth
);
7210 Ones
= N0Opcode
== ISD::SHL
? Ones
.shl(ShiftAmt
) : Ones
.lshr(ShiftAmt
);
7211 if (XorC
->getAPIntValue() == Ones
) {
7212 // If the xor constant is a shifted -1, do a 'not' before the shift:
7213 // xor (X << ShiftC), XorC --> (not X) << ShiftC
7214 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
7215 SDValue Not
= DAG
.getNOT(DL
, N0
.getOperand(0), VT
);
7216 return DAG
.getNode(N0Opcode
, DL
, VT
, Not
, N0
.getOperand(1));
7222 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
7223 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
)) {
7224 SDValue A
= N0Opcode
== ISD::ADD
? N0
: N1
;
7225 SDValue S
= N0Opcode
== ISD::SRA
? N0
: N1
;
7226 if (A
.getOpcode() == ISD::ADD
&& S
.getOpcode() == ISD::SRA
) {
7227 SDValue A0
= A
.getOperand(0), A1
= A
.getOperand(1);
7228 SDValue S0
= S
.getOperand(0);
7229 if ((A0
== S
&& A1
== S0
) || (A1
== S
&& A0
== S0
)) {
7230 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7231 if (ConstantSDNode
*C
= isConstOrConstSplat(S
.getOperand(1)))
7232 if (C
->getAPIntValue() == (OpSizeInBits
- 1))
7233 return DAG
.getNode(ISD::ABS
, DL
, VT
, S0
);
7238 // fold (xor x, x) -> 0
7240 return tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
7242 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
7243 // Here is a concrete example of this equivalence:
7245 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
7246 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
7250 // i16 ~1 == 0b1111111111111110
7251 // i16 rol(~1, 14) == 0b1011111111111111
7253 // Some additional tips to help conceptualize this transform:
7254 // - Try to see the operation as placing a single zero in a value of all ones.
7255 // - There exists no value for x which would allow the result to contain zero.
7256 // - Values of x larger than the bitwidth are undefined and do not require a
7257 // consistent result.
7258 // - Pushing the zero left requires shifting one bits in from the right.
7259 // A rotate left of ~1 is a nice way of achieving the desired result.
7260 if (TLI
.isOperationLegalOrCustom(ISD::ROTL
, VT
) && N0Opcode
== ISD::SHL
&&
7261 isAllOnesConstant(N1
) && isOneConstant(N0
.getOperand(0))) {
7262 return DAG
.getNode(ISD::ROTL
, DL
, VT
, DAG
.getConstant(~1, DL
, VT
),
7266 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
7267 if (N0Opcode
== N1
.getOpcode())
7268 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
7271 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
7272 if (SDValue MM
= unfoldMaskedMerge(N
))
7275 // Simplify the expression using non-local knowledge.
7276 if (SimplifyDemandedBits(SDValue(N
, 0)))
7277 return SDValue(N
, 0);
7282 /// If we have a shift-by-constant of a bitwise logic op that itself has a
7283 /// shift-by-constant operand with identical opcode, we may be able to convert
7284 /// that into 2 independent shifts followed by the logic op. This is a
7285 /// throughput improvement.
7286 static SDValue
combineShiftOfShiftedLogic(SDNode
*Shift
, SelectionDAG
&DAG
) {
7287 // Match a one-use bitwise logic op.
7288 SDValue LogicOp
= Shift
->getOperand(0);
7289 if (!LogicOp
.hasOneUse())
7292 unsigned LogicOpcode
= LogicOp
.getOpcode();
7293 if (LogicOpcode
!= ISD::AND
&& LogicOpcode
!= ISD::OR
&&
7294 LogicOpcode
!= ISD::XOR
)
7297 // Find a matching one-use shift by constant.
7298 unsigned ShiftOpcode
= Shift
->getOpcode();
7299 SDValue C1
= Shift
->getOperand(1);
7300 ConstantSDNode
*C1Node
= isConstOrConstSplat(C1
);
7301 assert(C1Node
&& "Expected a shift with constant operand");
7302 const APInt
&C1Val
= C1Node
->getAPIntValue();
7303 auto matchFirstShift
= [&](SDValue V
, SDValue
&ShiftOp
,
7304 const APInt
*&ShiftAmtVal
) {
7305 if (V
.getOpcode() != ShiftOpcode
|| !V
.hasOneUse())
7308 ConstantSDNode
*ShiftCNode
= isConstOrConstSplat(V
.getOperand(1));
7312 // Capture the shifted operand and shift amount value.
7313 ShiftOp
= V
.getOperand(0);
7314 ShiftAmtVal
= &ShiftCNode
->getAPIntValue();
7316 // Shift amount types do not have to match their operand type, so check that
7317 // the constants are the same width.
7318 if (ShiftAmtVal
->getBitWidth() != C1Val
.getBitWidth())
7321 // The fold is not valid if the sum of the shift values exceeds bitwidth.
7322 if ((*ShiftAmtVal
+ C1Val
).uge(V
.getScalarValueSizeInBits()))
7328 // Logic ops are commutative, so check each operand for a match.
7331 if (matchFirstShift(LogicOp
.getOperand(0), X
, C0Val
))
7332 Y
= LogicOp
.getOperand(1);
7333 else if (matchFirstShift(LogicOp
.getOperand(1), X
, C0Val
))
7334 Y
= LogicOp
.getOperand(0);
7338 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
7340 EVT VT
= Shift
->getValueType(0);
7341 EVT ShiftAmtVT
= Shift
->getOperand(1).getValueType();
7342 SDValue ShiftSumC
= DAG
.getConstant(*C0Val
+ C1Val
, DL
, ShiftAmtVT
);
7343 SDValue NewShift1
= DAG
.getNode(ShiftOpcode
, DL
, VT
, X
, ShiftSumC
);
7344 SDValue NewShift2
= DAG
.getNode(ShiftOpcode
, DL
, VT
, Y
, C1
);
7345 return DAG
.getNode(LogicOpcode
, DL
, VT
, NewShift1
, NewShift2
);
7348 /// Handle transforms common to the three shifts, when the shift amount is a
7350 /// We are looking for: (shift being one of shl/sra/srl)
7351 /// shift (binop X, C0), C1
7352 /// And want to transform into:
7353 /// binop (shift X, C1), (shift C0, C1)
7354 SDValue
DAGCombiner::visitShiftByConstant(SDNode
*N
) {
7355 assert(isConstOrConstSplat(N
->getOperand(1)) && "Expected constant operand");
7357 // Do not turn a 'not' into a regular xor.
7358 if (isBitwiseNot(N
->getOperand(0)))
7361 // The inner binop must be one-use, since we want to replace it.
7362 SDValue LHS
= N
->getOperand(0);
7363 if (!LHS
.hasOneUse() || !TLI
.isDesirableToCommuteWithShift(N
, Level
))
7366 // TODO: This is limited to early combining because it may reveal regressions
7367 // otherwise. But since we just checked a target hook to see if this is
7368 // desirable, that should have filtered out cases where this interferes
7369 // with some other pattern matching.
7371 if (SDValue R
= combineShiftOfShiftedLogic(N
, DAG
))
7374 // We want to pull some binops through shifts, so that we have (and (shift))
7375 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
7376 // thing happens with address calculations, so it's important to canonicalize
7378 switch (LHS
.getOpcode()) {
7386 if (N
->getOpcode() != ISD::SHL
)
7387 return SDValue(); // only shl(add) not sr[al](add).
7391 // We require the RHS of the binop to be a constant and not opaque as well.
7392 ConstantSDNode
*BinOpCst
= getAsNonOpaqueConstant(LHS
.getOperand(1));
7396 // FIXME: disable this unless the input to the binop is a shift by a constant
7397 // or is copy/select. Enable this in other cases when figure out it's exactly
7399 SDValue BinOpLHSVal
= LHS
.getOperand(0);
7400 bool IsShiftByConstant
= (BinOpLHSVal
.getOpcode() == ISD::SHL
||
7401 BinOpLHSVal
.getOpcode() == ISD::SRA
||
7402 BinOpLHSVal
.getOpcode() == ISD::SRL
) &&
7403 isa
<ConstantSDNode
>(BinOpLHSVal
.getOperand(1));
7404 bool IsCopyOrSelect
= BinOpLHSVal
.getOpcode() == ISD::CopyFromReg
||
7405 BinOpLHSVal
.getOpcode() == ISD::SELECT
;
7407 if (!IsShiftByConstant
&& !IsCopyOrSelect
)
7410 if (IsCopyOrSelect
&& N
->hasOneUse())
7413 // Fold the constants, shifting the binop RHS by the shift amount.
7415 EVT VT
= N
->getValueType(0);
7416 SDValue NewRHS
= DAG
.getNode(N
->getOpcode(), DL
, VT
, LHS
.getOperand(1),
7418 assert(isa
<ConstantSDNode
>(NewRHS
) && "Folding was not successful!");
7420 SDValue NewShift
= DAG
.getNode(N
->getOpcode(), DL
, VT
, LHS
.getOperand(0),
7422 return DAG
.getNode(LHS
.getOpcode(), DL
, VT
, NewShift
, NewRHS
);
7425 SDValue
DAGCombiner::distributeTruncateThroughAnd(SDNode
*N
) {
7426 assert(N
->getOpcode() == ISD::TRUNCATE
);
7427 assert(N
->getOperand(0).getOpcode() == ISD::AND
);
7429 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
7430 EVT TruncVT
= N
->getValueType(0);
7431 if (N
->hasOneUse() && N
->getOperand(0).hasOneUse() &&
7432 TLI
.isTypeDesirableForOp(ISD::AND
, TruncVT
)) {
7433 SDValue N01
= N
->getOperand(0).getOperand(1);
7434 if (isConstantOrConstantVector(N01
, /* NoOpaques */ true)) {
7436 SDValue N00
= N
->getOperand(0).getOperand(0);
7437 SDValue Trunc00
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
, N00
);
7438 SDValue Trunc01
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
, N01
);
7439 AddToWorklist(Trunc00
.getNode());
7440 AddToWorklist(Trunc01
.getNode());
7441 return DAG
.getNode(ISD::AND
, DL
, TruncVT
, Trunc00
, Trunc01
);
7448 SDValue
DAGCombiner::visitRotate(SDNode
*N
) {
7450 SDValue N0
= N
->getOperand(0);
7451 SDValue N1
= N
->getOperand(1);
7452 EVT VT
= N
->getValueType(0);
7453 unsigned Bitsize
= VT
.getScalarSizeInBits();
7455 // fold (rot x, 0) -> x
7456 if (isNullOrNullSplat(N1
))
7459 // fold (rot x, c) -> x iff (c % BitSize) == 0
7460 if (isPowerOf2_32(Bitsize
) && Bitsize
> 1) {
7461 APInt
ModuloMask(N1
.getScalarValueSizeInBits(), Bitsize
- 1);
7462 if (DAG
.MaskedValueIsZero(N1
, ModuloMask
))
7466 // fold (rot x, c) -> (rot x, c % BitSize)
7467 // TODO - support non-uniform vector amounts.
7468 if (ConstantSDNode
*Cst
= isConstOrConstSplat(N1
)) {
7469 if (Cst
->getAPIntValue().uge(Bitsize
)) {
7470 uint64_t RotAmt
= Cst
->getAPIntValue().urem(Bitsize
);
7471 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
,
7472 DAG
.getConstant(RotAmt
, dl
, N1
.getValueType()));
7476 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
7477 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7478 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7479 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7480 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
, NewOp1
);
7483 unsigned NextOp
= N0
.getOpcode();
7484 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
7485 if (NextOp
== ISD::ROTL
|| NextOp
== ISD::ROTR
) {
7486 SDNode
*C1
= DAG
.isConstantIntBuildVectorOrConstantInt(N1
);
7487 SDNode
*C2
= DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1));
7488 if (C1
&& C2
&& C1
->getValueType(0) == C2
->getValueType(0)) {
7489 EVT ShiftVT
= C1
->getValueType(0);
7490 bool SameSide
= (N
->getOpcode() == NextOp
);
7491 unsigned CombineOp
= SameSide
? ISD::ADD
: ISD::SUB
;
7492 if (SDValue CombinedShift
=
7493 DAG
.FoldConstantArithmetic(CombineOp
, dl
, ShiftVT
, C1
, C2
)) {
7494 SDValue BitsizeC
= DAG
.getConstant(Bitsize
, dl
, ShiftVT
);
7495 SDValue CombinedShiftNorm
= DAG
.FoldConstantArithmetic(
7496 ISD::SREM
, dl
, ShiftVT
, CombinedShift
.getNode(),
7497 BitsizeC
.getNode());
7498 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
->getOperand(0),
7506 SDValue
DAGCombiner::visitSHL(SDNode
*N
) {
7507 SDValue N0
= N
->getOperand(0);
7508 SDValue N1
= N
->getOperand(1);
7509 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7512 EVT VT
= N0
.getValueType();
7513 EVT ShiftVT
= N1
.getValueType();
7514 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7517 if (VT
.isVector()) {
7518 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7521 BuildVectorSDNode
*N1CV
= dyn_cast
<BuildVectorSDNode
>(N1
);
7522 // If setcc produces all-one true value then:
7523 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
7524 if (N1CV
&& N1CV
->isConstant()) {
7525 if (N0
.getOpcode() == ISD::AND
) {
7526 SDValue N00
= N0
->getOperand(0);
7527 SDValue N01
= N0
->getOperand(1);
7528 BuildVectorSDNode
*N01CV
= dyn_cast
<BuildVectorSDNode
>(N01
);
7530 if (N01CV
&& N01CV
->isConstant() && N00
.getOpcode() == ISD::SETCC
&&
7531 TLI
.getBooleanContents(N00
.getOperand(0).getValueType()) ==
7532 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
7533 if (SDValue C
= DAG
.FoldConstantArithmetic(ISD::SHL
, SDLoc(N
), VT
,
7535 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, N00
, C
);
7541 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7543 // fold (shl c1, c2) -> c1<<c2
7544 // TODO - support non-uniform vector shift amounts.
7545 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7546 if (N0C
&& N1C
&& !N1C
->isOpaque())
7547 return DAG
.FoldConstantArithmetic(ISD::SHL
, SDLoc(N
), VT
, N0C
, N1C
);
7549 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7552 // if (shl x, c) is known to be zero, return 0
7553 if (DAG
.MaskedValueIsZero(SDValue(N
, 0),
7554 APInt::getAllOnesValue(OpSizeInBits
)))
7555 return DAG
.getConstant(0, SDLoc(N
), VT
);
7557 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
7558 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7559 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7560 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7561 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
, NewOp1
);
7564 // TODO - support non-uniform vector shift amounts.
7565 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
7566 return SDValue(N
, 0);
7568 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
7569 if (N0
.getOpcode() == ISD::SHL
) {
7570 auto MatchOutOfRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7571 ConstantSDNode
*RHS
) {
7572 APInt c1
= LHS
->getAPIntValue();
7573 APInt c2
= RHS
->getAPIntValue();
7574 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7575 return (c1
+ c2
).uge(OpSizeInBits
);
7577 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchOutOfRange
))
7578 return DAG
.getConstant(0, SDLoc(N
), VT
);
7580 auto MatchInRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7581 ConstantSDNode
*RHS
) {
7582 APInt c1
= LHS
->getAPIntValue();
7583 APInt c2
= RHS
->getAPIntValue();
7584 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7585 return (c1
+ c2
).ult(OpSizeInBits
);
7587 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchInRange
)) {
7589 SDValue Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, N1
, N0
.getOperand(1));
7590 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0), Sum
);
7594 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
7595 // For this to be valid, the second form must not preserve any of the bits
7596 // that are shifted out by the inner shift in the first form. This means
7597 // the outer shift size must be >= the number of bits added by the ext.
7598 // As a corollary, we don't care what kind of ext it is.
7599 if ((N0
.getOpcode() == ISD::ZERO_EXTEND
||
7600 N0
.getOpcode() == ISD::ANY_EXTEND
||
7601 N0
.getOpcode() == ISD::SIGN_EXTEND
) &&
7602 N0
.getOperand(0).getOpcode() == ISD::SHL
) {
7603 SDValue N0Op0
= N0
.getOperand(0);
7604 SDValue InnerShiftAmt
= N0Op0
.getOperand(1);
7605 EVT InnerVT
= N0Op0
.getValueType();
7606 uint64_t InnerBitwidth
= InnerVT
.getScalarSizeInBits();
7608 auto MatchOutOfRange
= [OpSizeInBits
, InnerBitwidth
](ConstantSDNode
*LHS
,
7609 ConstantSDNode
*RHS
) {
7610 APInt c1
= LHS
->getAPIntValue();
7611 APInt c2
= RHS
->getAPIntValue();
7612 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7613 return c2
.uge(OpSizeInBits
- InnerBitwidth
) &&
7614 (c1
+ c2
).uge(OpSizeInBits
);
7616 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchOutOfRange
,
7617 /*AllowUndefs*/ false,
7618 /*AllowTypeMismatch*/ true))
7619 return DAG
.getConstant(0, SDLoc(N
), VT
);
7621 auto MatchInRange
= [OpSizeInBits
, InnerBitwidth
](ConstantSDNode
*LHS
,
7622 ConstantSDNode
*RHS
) {
7623 APInt c1
= LHS
->getAPIntValue();
7624 APInt c2
= RHS
->getAPIntValue();
7625 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7626 return c2
.uge(OpSizeInBits
- InnerBitwidth
) &&
7627 (c1
+ c2
).ult(OpSizeInBits
);
7629 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchInRange
,
7630 /*AllowUndefs*/ false,
7631 /*AllowTypeMismatch*/ true)) {
7633 SDValue Ext
= DAG
.getNode(N0
.getOpcode(), DL
, VT
, N0Op0
.getOperand(0));
7634 SDValue Sum
= DAG
.getZExtOrTrunc(InnerShiftAmt
, DL
, ShiftVT
);
7635 Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, Sum
, N1
);
7636 return DAG
.getNode(ISD::SHL
, DL
, VT
, Ext
, Sum
);
7640 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
7641 // Only fold this if the inner zext has no other uses to avoid increasing
7642 // the total number of instructions.
7643 if (N0
.getOpcode() == ISD::ZERO_EXTEND
&& N0
.hasOneUse() &&
7644 N0
.getOperand(0).getOpcode() == ISD::SRL
) {
7645 SDValue N0Op0
= N0
.getOperand(0);
7646 SDValue InnerShiftAmt
= N0Op0
.getOperand(1);
7648 auto MatchEqual
= [VT
](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
7649 APInt c1
= LHS
->getAPIntValue();
7650 APInt c2
= RHS
->getAPIntValue();
7651 zeroExtendToMatch(c1
, c2
);
7652 return c1
.ult(VT
.getScalarSizeInBits()) && (c1
== c2
);
7654 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchEqual
,
7655 /*AllowUndefs*/ false,
7656 /*AllowTypeMismatch*/ true)) {
7658 EVT InnerShiftAmtVT
= N0Op0
.getOperand(1).getValueType();
7659 SDValue NewSHL
= DAG
.getZExtOrTrunc(N1
, DL
, InnerShiftAmtVT
);
7660 NewSHL
= DAG
.getNode(ISD::SHL
, DL
, N0Op0
.getValueType(), N0Op0
, NewSHL
);
7661 AddToWorklist(NewSHL
.getNode());
7662 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N0
), VT
, NewSHL
);
7666 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
7667 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
7668 // TODO - support non-uniform vector shift amounts.
7669 if (N1C
&& (N0
.getOpcode() == ISD::SRL
|| N0
.getOpcode() == ISD::SRA
) &&
7670 N0
->getFlags().hasExact()) {
7671 if (ConstantSDNode
*N0C1
= isConstOrConstSplat(N0
.getOperand(1))) {
7672 uint64_t C1
= N0C1
->getZExtValue();
7673 uint64_t C2
= N1C
->getZExtValue();
7676 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0),
7677 DAG
.getConstant(C2
- C1
, DL
, ShiftVT
));
7678 return DAG
.getNode(N0
.getOpcode(), DL
, VT
, N0
.getOperand(0),
7679 DAG
.getConstant(C1
- C2
, DL
, ShiftVT
));
7683 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
7684 // (and (srl x, (sub c1, c2), MASK)
7685 // Only fold this if the inner shift has no other uses -- if it does, folding
7686 // this will increase the total number of instructions.
7687 // TODO - drop hasOneUse requirement if c1 == c2?
7688 // TODO - support non-uniform vector shift amounts.
7689 if (N1C
&& N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse() &&
7690 TLI
.shouldFoldConstantShiftPairToMask(N
, Level
)) {
7691 if (ConstantSDNode
*N0C1
= isConstOrConstSplat(N0
.getOperand(1))) {
7692 if (N0C1
->getAPIntValue().ult(OpSizeInBits
)) {
7693 uint64_t c1
= N0C1
->getZExtValue();
7694 uint64_t c2
= N1C
->getZExtValue();
7695 APInt Mask
= APInt::getHighBitsSet(OpSizeInBits
, OpSizeInBits
- c1
);
7700 Shift
= DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0),
7701 DAG
.getConstant(c2
- c1
, DL
, ShiftVT
));
7703 Mask
.lshrInPlace(c1
- c2
);
7705 Shift
= DAG
.getNode(ISD::SRL
, DL
, VT
, N0
.getOperand(0),
7706 DAG
.getConstant(c1
- c2
, DL
, ShiftVT
));
7709 return DAG
.getNode(ISD::AND
, DL
, VT
, Shift
,
7710 DAG
.getConstant(Mask
, DL
, VT
));
7715 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
7716 if (N0
.getOpcode() == ISD::SRA
&& N1
== N0
.getOperand(1) &&
7717 isConstantOrConstantVector(N1
, /* No Opaques */ true)) {
7719 SDValue AllBits
= DAG
.getAllOnesConstant(DL
, VT
);
7720 SDValue HiBitsMask
= DAG
.getNode(ISD::SHL
, DL
, VT
, AllBits
, N1
);
7721 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), HiBitsMask
);
7724 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7725 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7726 // Variant of version done on multiply, except mul by a power of 2 is turned
7728 if ((N0
.getOpcode() == ISD::ADD
|| N0
.getOpcode() == ISD::OR
) &&
7729 N0
.getNode()->hasOneUse() &&
7730 isConstantOrConstantVector(N1
, /* No Opaques */ true) &&
7731 isConstantOrConstantVector(N0
.getOperand(1), /* No Opaques */ true) &&
7732 TLI
.isDesirableToCommuteWithShift(N
, Level
)) {
7733 SDValue Shl0
= DAG
.getNode(ISD::SHL
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
7734 SDValue Shl1
= DAG
.getNode(ISD::SHL
, SDLoc(N1
), VT
, N0
.getOperand(1), N1
);
7735 AddToWorklist(Shl0
.getNode());
7736 AddToWorklist(Shl1
.getNode());
7737 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, Shl0
, Shl1
);
7740 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
7741 if (N0
.getOpcode() == ISD::MUL
&& N0
.getNode()->hasOneUse() &&
7742 isConstantOrConstantVector(N1
, /* No Opaques */ true) &&
7743 isConstantOrConstantVector(N0
.getOperand(1), /* No Opaques */ true)) {
7744 SDValue Shl
= DAG
.getNode(ISD::SHL
, SDLoc(N1
), VT
, N0
.getOperand(1), N1
);
7745 if (isConstantOrConstantVector(Shl
))
7746 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N0
.getOperand(0), Shl
);
7749 if (N1C
&& !N1C
->isOpaque())
7750 if (SDValue NewSHL
= visitShiftByConstant(N
))
7756 SDValue
DAGCombiner::visitSRA(SDNode
*N
) {
7757 SDValue N0
= N
->getOperand(0);
7758 SDValue N1
= N
->getOperand(1);
7759 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7762 EVT VT
= N0
.getValueType();
7763 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7765 // Arithmetic shifting an all-sign-bit value is a no-op.
7766 // fold (sra 0, x) -> 0
7767 // fold (sra -1, x) -> -1
7768 if (DAG
.ComputeNumSignBits(N0
) == OpSizeInBits
)
7773 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7776 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7778 // fold (sra c1, c2) -> (sra c1, c2)
7779 // TODO - support non-uniform vector shift amounts.
7780 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7781 if (N0C
&& N1C
&& !N1C
->isOpaque())
7782 return DAG
.FoldConstantArithmetic(ISD::SRA
, SDLoc(N
), VT
, N0C
, N1C
);
7784 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7787 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
7789 if (N1C
&& N0
.getOpcode() == ISD::SHL
&& N1
== N0
.getOperand(1)) {
7790 unsigned LowBits
= OpSizeInBits
- (unsigned)N1C
->getZExtValue();
7791 EVT ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), LowBits
);
7793 ExtVT
= EVT::getVectorVT(*DAG
.getContext(),
7794 ExtVT
, VT
.getVectorNumElements());
7795 if ((!LegalOperations
||
7796 TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
, ExtVT
)))
7797 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
7798 N0
.getOperand(0), DAG
.getValueType(ExtVT
));
7801 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
7802 // clamp (add c1, c2) to max shift.
7803 if (N0
.getOpcode() == ISD::SRA
) {
7805 EVT ShiftVT
= N1
.getValueType();
7806 EVT ShiftSVT
= ShiftVT
.getScalarType();
7807 SmallVector
<SDValue
, 16> ShiftValues
;
7809 auto SumOfShifts
= [&](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
7810 APInt c1
= LHS
->getAPIntValue();
7811 APInt c2
= RHS
->getAPIntValue();
7812 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7813 APInt Sum
= c1
+ c2
;
7815 Sum
.uge(OpSizeInBits
) ? (OpSizeInBits
- 1) : Sum
.getZExtValue();
7816 ShiftValues
.push_back(DAG
.getConstant(ShiftSum
, DL
, ShiftSVT
));
7819 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), SumOfShifts
)) {
7822 ShiftValue
= DAG
.getBuildVector(ShiftVT
, DL
, ShiftValues
);
7824 ShiftValue
= ShiftValues
[0];
7825 return DAG
.getNode(ISD::SRA
, DL
, VT
, N0
.getOperand(0), ShiftValue
);
7829 // fold (sra (shl X, m), (sub result_size, n))
7830 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
7831 // result_size - n != m.
7832 // If truncate is free for the target sext(shl) is likely to result in better
7834 if (N0
.getOpcode() == ISD::SHL
&& N1C
) {
7835 // Get the two constanst of the shifts, CN0 = m, CN = n.
7836 const ConstantSDNode
*N01C
= isConstOrConstSplat(N0
.getOperand(1));
7838 LLVMContext
&Ctx
= *DAG
.getContext();
7839 // Determine what the truncate's result bitsize and type would be.
7840 EVT TruncVT
= EVT::getIntegerVT(Ctx
, OpSizeInBits
- N1C
->getZExtValue());
7843 TruncVT
= EVT::getVectorVT(Ctx
, TruncVT
, VT
.getVectorNumElements());
7845 // Determine the residual right-shift amount.
7846 int ShiftAmt
= N1C
->getZExtValue() - N01C
->getZExtValue();
7848 // If the shift is not a no-op (in which case this should be just a sign
7849 // extend already), the truncated to type is legal, sign_extend is legal
7850 // on that type, and the truncate to that type is both legal and free,
7851 // perform the transform.
7852 if ((ShiftAmt
> 0) &&
7853 TLI
.isOperationLegalOrCustom(ISD::SIGN_EXTEND
, TruncVT
) &&
7854 TLI
.isOperationLegalOrCustom(ISD::TRUNCATE
, VT
) &&
7855 TLI
.isTruncateFree(VT
, TruncVT
)) {
7857 SDValue Amt
= DAG
.getConstant(ShiftAmt
, DL
,
7858 getShiftAmountTy(N0
.getOperand(0).getValueType()));
7859 SDValue Shift
= DAG
.getNode(ISD::SRL
, DL
, VT
,
7860 N0
.getOperand(0), Amt
);
7861 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
,
7863 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
,
7864 N
->getValueType(0), Trunc
);
7869 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
7870 // sra (add (shl X, N1C), AddC), N1C -->
7871 // sext (add (trunc X to (width - N1C)), AddC')
7872 if (!LegalTypes
&& N0
.getOpcode() == ISD::ADD
&& N0
.hasOneUse() && N1C
&&
7873 N0
.getOperand(0).getOpcode() == ISD::SHL
&&
7874 N0
.getOperand(0).getOperand(1) == N1
&& N0
.getOperand(0).hasOneUse()) {
7875 if (ConstantSDNode
*AddC
= isConstOrConstSplat(N0
.getOperand(1))) {
7876 SDValue Shl
= N0
.getOperand(0);
7877 // Determine what the truncate's type would be and ask the target if that
7878 // is a free operation.
7879 LLVMContext
&Ctx
= *DAG
.getContext();
7880 unsigned ShiftAmt
= N1C
->getZExtValue();
7881 EVT TruncVT
= EVT::getIntegerVT(Ctx
, OpSizeInBits
- ShiftAmt
);
7883 TruncVT
= EVT::getVectorVT(Ctx
, TruncVT
, VT
.getVectorNumElements());
7885 // TODO: The simple type check probably belongs in the default hook
7886 // implementation and/or target-specific overrides (because
7887 // non-simple types likely require masking when legalized), but that
7888 // restriction may conflict with other transforms.
7889 if (TruncVT
.isSimple() && TLI
.isTruncateFree(VT
, TruncVT
)) {
7891 SDValue Trunc
= DAG
.getZExtOrTrunc(Shl
.getOperand(0), DL
, TruncVT
);
7892 SDValue ShiftC
= DAG
.getConstant(AddC
->getAPIntValue().lshr(ShiftAmt
).
7893 trunc(TruncVT
.getScalarSizeInBits()), DL
, TruncVT
);
7894 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, TruncVT
, Trunc
, ShiftC
);
7895 return DAG
.getSExtOrTrunc(Add
, DL
, VT
);
7900 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
7901 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7902 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7903 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7904 return DAG
.getNode(ISD::SRA
, SDLoc(N
), VT
, N0
, NewOp1
);
7907 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
7908 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
7909 // if c1 is equal to the number of bits the trunc removes
7910 // TODO - support non-uniform vector shift amounts.
7911 if (N0
.getOpcode() == ISD::TRUNCATE
&&
7912 (N0
.getOperand(0).getOpcode() == ISD::SRL
||
7913 N0
.getOperand(0).getOpcode() == ISD::SRA
) &&
7914 N0
.getOperand(0).hasOneUse() &&
7915 N0
.getOperand(0).getOperand(1).hasOneUse() && N1C
) {
7916 SDValue N0Op0
= N0
.getOperand(0);
7917 if (ConstantSDNode
*LargeShift
= isConstOrConstSplat(N0Op0
.getOperand(1))) {
7918 EVT LargeVT
= N0Op0
.getValueType();
7919 unsigned TruncBits
= LargeVT
.getScalarSizeInBits() - OpSizeInBits
;
7920 if (LargeShift
->getAPIntValue() == TruncBits
) {
7922 SDValue Amt
= DAG
.getConstant(N1C
->getZExtValue() + TruncBits
, DL
,
7923 getShiftAmountTy(LargeVT
));
7925 DAG
.getNode(ISD::SRA
, DL
, LargeVT
, N0Op0
.getOperand(0), Amt
);
7926 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, SRA
);
7931 // Simplify, based on bits shifted out of the LHS.
7932 // TODO - support non-uniform vector shift amounts.
7933 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
7934 return SDValue(N
, 0);
7936 // If the sign bit is known to be zero, switch this to a SRL.
7937 if (DAG
.SignBitIsZero(N0
))
7938 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
, N1
);
7940 if (N1C
&& !N1C
->isOpaque())
7941 if (SDValue NewSRA
= visitShiftByConstant(N
))
7947 SDValue
DAGCombiner::visitSRL(SDNode
*N
) {
7948 SDValue N0
= N
->getOperand(0);
7949 SDValue N1
= N
->getOperand(1);
7950 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7953 EVT VT
= N0
.getValueType();
7954 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7958 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7961 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7963 // fold (srl c1, c2) -> c1 >>u c2
7964 // TODO - support non-uniform vector shift amounts.
7965 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7966 if (N0C
&& N1C
&& !N1C
->isOpaque())
7967 return DAG
.FoldConstantArithmetic(ISD::SRL
, SDLoc(N
), VT
, N0C
, N1C
);
7969 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7972 // if (srl x, c) is known to be zero, return 0
7973 if (N1C
&& DAG
.MaskedValueIsZero(SDValue(N
, 0),
7974 APInt::getAllOnesValue(OpSizeInBits
)))
7975 return DAG
.getConstant(0, SDLoc(N
), VT
);
7977 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
7978 if (N0
.getOpcode() == ISD::SRL
) {
7979 auto MatchOutOfRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7980 ConstantSDNode
*RHS
) {
7981 APInt c1
= LHS
->getAPIntValue();
7982 APInt c2
= RHS
->getAPIntValue();
7983 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7984 return (c1
+ c2
).uge(OpSizeInBits
);
7986 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchOutOfRange
))
7987 return DAG
.getConstant(0, SDLoc(N
), VT
);
7989 auto MatchInRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7990 ConstantSDNode
*RHS
) {
7991 APInt c1
= LHS
->getAPIntValue();
7992 APInt c2
= RHS
->getAPIntValue();
7993 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7994 return (c1
+ c2
).ult(OpSizeInBits
);
7996 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchInRange
)) {
7998 EVT ShiftVT
= N1
.getValueType();
7999 SDValue Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, N1
, N0
.getOperand(1));
8000 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
.getOperand(0), Sum
);
8004 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
8005 // TODO - support non-uniform vector shift amounts.
8006 if (N1C
&& N0
.getOpcode() == ISD::TRUNCATE
&&
8007 N0
.getOperand(0).getOpcode() == ISD::SRL
) {
8008 if (auto N001C
= isConstOrConstSplat(N0
.getOperand(0).getOperand(1))) {
8009 uint64_t c1
= N001C
->getZExtValue();
8010 uint64_t c2
= N1C
->getZExtValue();
8011 EVT InnerShiftVT
= N0
.getOperand(0).getValueType();
8012 EVT ShiftCountVT
= N0
.getOperand(0).getOperand(1).getValueType();
8013 uint64_t InnerShiftSize
= InnerShiftVT
.getScalarSizeInBits();
8014 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
8015 if (c1
+ OpSizeInBits
== InnerShiftSize
) {
8017 if (c1
+ c2
>= InnerShiftSize
)
8018 return DAG
.getConstant(0, DL
, VT
);
8019 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
,
8020 DAG
.getNode(ISD::SRL
, DL
, InnerShiftVT
,
8021 N0
.getOperand(0).getOperand(0),
8022 DAG
.getConstant(c1
+ c2
, DL
,
8028 // fold (srl (shl x, c), c) -> (and x, cst2)
8029 // TODO - (srl (shl x, c1), c2).
8030 if (N0
.getOpcode() == ISD::SHL
&& N0
.getOperand(1) == N1
&&
8031 isConstantOrConstantVector(N1
, /* NoOpaques */ true)) {
8034 DAG
.getNode(ISD::SRL
, DL
, VT
, DAG
.getAllOnesConstant(DL
, VT
), N1
);
8035 AddToWorklist(Mask
.getNode());
8036 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), Mask
);
8039 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
8040 // TODO - support non-uniform vector shift amounts.
8041 if (N1C
&& N0
.getOpcode() == ISD::ANY_EXTEND
) {
8042 // Shifting in all undef bits?
8043 EVT SmallVT
= N0
.getOperand(0).getValueType();
8044 unsigned BitSize
= SmallVT
.getScalarSizeInBits();
8045 if (N1C
->getAPIntValue().uge(BitSize
))
8046 return DAG
.getUNDEF(VT
);
8048 if (!LegalTypes
|| TLI
.isTypeDesirableForOp(ISD::SRL
, SmallVT
)) {
8049 uint64_t ShiftAmt
= N1C
->getZExtValue();
8051 SDValue SmallShift
= DAG
.getNode(ISD::SRL
, DL0
, SmallVT
,
8053 DAG
.getConstant(ShiftAmt
, DL0
,
8054 getShiftAmountTy(SmallVT
)));
8055 AddToWorklist(SmallShift
.getNode());
8056 APInt Mask
= APInt::getLowBitsSet(OpSizeInBits
, OpSizeInBits
- ShiftAmt
);
8058 return DAG
.getNode(ISD::AND
, DL
, VT
,
8059 DAG
.getNode(ISD::ANY_EXTEND
, DL
, VT
, SmallShift
),
8060 DAG
.getConstant(Mask
, DL
, VT
));
8064 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
8065 // bit, which is unmodified by sra.
8066 if (N1C
&& N1C
->getAPIntValue() == (OpSizeInBits
- 1)) {
8067 if (N0
.getOpcode() == ISD::SRA
)
8068 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
8071 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
8072 if (N1C
&& N0
.getOpcode() == ISD::CTLZ
&&
8073 N1C
->getAPIntValue() == Log2_32(OpSizeInBits
)) {
8074 KnownBits Known
= DAG
.computeKnownBits(N0
.getOperand(0));
8076 // If any of the input bits are KnownOne, then the input couldn't be all
8077 // zeros, thus the result of the srl will always be zero.
8078 if (Known
.One
.getBoolValue()) return DAG
.getConstant(0, SDLoc(N0
), VT
);
8080 // If all of the bits input the to ctlz node are known to be zero, then
8081 // the result of the ctlz is "32" and the result of the shift is one.
8082 APInt UnknownBits
= ~Known
.Zero
;
8083 if (UnknownBits
== 0) return DAG
.getConstant(1, SDLoc(N0
), VT
);
8085 // Otherwise, check to see if there is exactly one bit input to the ctlz.
8086 if (UnknownBits
.isPowerOf2()) {
8087 // Okay, we know that only that the single bit specified by UnknownBits
8088 // could be set on input to the CTLZ node. If this bit is set, the SRL
8089 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
8090 // to an SRL/XOR pair, which is likely to simplify more.
8091 unsigned ShAmt
= UnknownBits
.countTrailingZeros();
8092 SDValue Op
= N0
.getOperand(0);
8096 Op
= DAG
.getNode(ISD::SRL
, DL
, VT
, Op
,
8097 DAG
.getConstant(ShAmt
, DL
,
8098 getShiftAmountTy(Op
.getValueType())));
8099 AddToWorklist(Op
.getNode());
8103 return DAG
.getNode(ISD::XOR
, DL
, VT
,
8104 Op
, DAG
.getConstant(1, DL
, VT
));
8108 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
8109 if (N1
.getOpcode() == ISD::TRUNCATE
&&
8110 N1
.getOperand(0).getOpcode() == ISD::AND
) {
8111 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
8112 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
, NewOp1
);
8115 // fold operands of srl based on knowledge that the low bits are not
8117 // TODO - support non-uniform vector shift amounts.
8118 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
8119 return SDValue(N
, 0);
8121 if (N1C
&& !N1C
->isOpaque())
8122 if (SDValue NewSRL
= visitShiftByConstant(N
))
8125 // Attempt to convert a srl of a load into a narrower zero-extending load.
8126 if (SDValue NarrowLoad
= ReduceLoadWidth(N
))
8129 // Here is a common situation. We want to optimize:
8132 // %b = and i32 %a, 2
8133 // %c = srl i32 %b, 1
8134 // brcond i32 %c ...
8140 // %c = setcc eq %b, 0
8143 // However when after the source operand of SRL is optimized into AND, the SRL
8144 // itself may not be optimized further. Look for it and add the BRCOND into
8146 if (N
->hasOneUse()) {
8147 SDNode
*Use
= *N
->use_begin();
8148 if (Use
->getOpcode() == ISD::BRCOND
)
8150 else if (Use
->getOpcode() == ISD::TRUNCATE
&& Use
->hasOneUse()) {
8151 // Also look pass the truncate.
8152 Use
= *Use
->use_begin();
8153 if (Use
->getOpcode() == ISD::BRCOND
)
8161 SDValue
DAGCombiner::visitFunnelShift(SDNode
*N
) {
8162 EVT VT
= N
->getValueType(0);
8163 SDValue N0
= N
->getOperand(0);
8164 SDValue N1
= N
->getOperand(1);
8165 SDValue N2
= N
->getOperand(2);
8166 bool IsFSHL
= N
->getOpcode() == ISD::FSHL
;
8167 unsigned BitWidth
= VT
.getScalarSizeInBits();
8169 // fold (fshl N0, N1, 0) -> N0
8170 // fold (fshr N0, N1, 0) -> N1
8171 if (isPowerOf2_32(BitWidth
))
8172 if (DAG
.MaskedValueIsZero(
8173 N2
, APInt(N2
.getScalarValueSizeInBits(), BitWidth
- 1)))
8174 return IsFSHL
? N0
: N1
;
8176 auto IsUndefOrZero
= [](SDValue V
) {
8177 return V
.isUndef() || isNullOrNullSplat(V
, /*AllowUndefs*/ true);
8180 // TODO - support non-uniform vector shift amounts.
8181 if (ConstantSDNode
*Cst
= isConstOrConstSplat(N2
)) {
8182 EVT ShAmtTy
= N2
.getValueType();
8184 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
8185 if (Cst
->getAPIntValue().uge(BitWidth
)) {
8186 uint64_t RotAmt
= Cst
->getAPIntValue().urem(BitWidth
);
8187 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N0
, N1
,
8188 DAG
.getConstant(RotAmt
, SDLoc(N
), ShAmtTy
));
8191 unsigned ShAmt
= Cst
->getZExtValue();
8193 return IsFSHL
? N0
: N1
;
8195 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
8196 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
8197 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
8198 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
8199 if (IsUndefOrZero(N0
))
8200 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N1
,
8201 DAG
.getConstant(IsFSHL
? BitWidth
- ShAmt
: ShAmt
,
8202 SDLoc(N
), ShAmtTy
));
8203 if (IsUndefOrZero(N1
))
8204 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
,
8205 DAG
.getConstant(IsFSHL
? ShAmt
: BitWidth
- ShAmt
,
8206 SDLoc(N
), ShAmtTy
));
8209 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
8210 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
8211 // iff We know the shift amount is in range.
8212 // TODO: when is it worth doing SUB(BW, N2) as well?
8213 if (isPowerOf2_32(BitWidth
)) {
8214 APInt
ModuloBits(N2
.getScalarValueSizeInBits(), BitWidth
- 1);
8215 if (IsUndefOrZero(N0
) && !IsFSHL
&& DAG
.MaskedValueIsZero(N2
, ~ModuloBits
))
8216 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N1
, N2
);
8217 if (IsUndefOrZero(N1
) && IsFSHL
&& DAG
.MaskedValueIsZero(N2
, ~ModuloBits
))
8218 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
, N2
);
8221 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
8222 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
8223 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
8224 // is legal as well we might be better off avoiding non-constant (BW - N2).
8225 unsigned RotOpc
= IsFSHL
? ISD::ROTL
: ISD::ROTR
;
8226 if (N0
== N1
&& hasOperation(RotOpc
, VT
))
8227 return DAG
.getNode(RotOpc
, SDLoc(N
), VT
, N0
, N2
);
8229 // Simplify, based on bits shifted out of N0/N1.
8230 if (SimplifyDemandedBits(SDValue(N
, 0)))
8231 return SDValue(N
, 0);
8236 SDValue
DAGCombiner::visitABS(SDNode
*N
) {
8237 SDValue N0
= N
->getOperand(0);
8238 EVT VT
= N
->getValueType(0);
8240 // fold (abs c1) -> c2
8241 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8242 return DAG
.getNode(ISD::ABS
, SDLoc(N
), VT
, N0
);
8243 // fold (abs (abs x)) -> (abs x)
8244 if (N0
.getOpcode() == ISD::ABS
)
8246 // fold (abs x) -> x iff not-negative
8247 if (DAG
.SignBitIsZero(N0
))
8252 SDValue
DAGCombiner::visitBSWAP(SDNode
*N
) {
8253 SDValue N0
= N
->getOperand(0);
8254 EVT VT
= N
->getValueType(0);
8256 // fold (bswap c1) -> c2
8257 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8258 return DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, N0
);
8259 // fold (bswap (bswap x)) -> x
8260 if (N0
.getOpcode() == ISD::BSWAP
)
8261 return N0
->getOperand(0);
8265 SDValue
DAGCombiner::visitBITREVERSE(SDNode
*N
) {
8266 SDValue N0
= N
->getOperand(0);
8267 EVT VT
= N
->getValueType(0);
8269 // fold (bitreverse c1) -> c2
8270 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8271 return DAG
.getNode(ISD::BITREVERSE
, SDLoc(N
), VT
, N0
);
8272 // fold (bitreverse (bitreverse x)) -> x
8273 if (N0
.getOpcode() == ISD::BITREVERSE
)
8274 return N0
.getOperand(0);
8278 SDValue
DAGCombiner::visitCTLZ(SDNode
*N
) {
8279 SDValue N0
= N
->getOperand(0);
8280 EVT VT
= N
->getValueType(0);
8282 // fold (ctlz c1) -> c2
8283 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8284 return DAG
.getNode(ISD::CTLZ
, SDLoc(N
), VT
, N0
);
8286 // If the value is known never to be zero, switch to the undef version.
8287 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTLZ_ZERO_UNDEF
, VT
)) {
8288 if (DAG
.isKnownNeverZero(N0
))
8289 return DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8295 SDValue
DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode
*N
) {
8296 SDValue N0
= N
->getOperand(0);
8297 EVT VT
= N
->getValueType(0);
8299 // fold (ctlz_zero_undef c1) -> c2
8300 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8301 return DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8305 SDValue
DAGCombiner::visitCTTZ(SDNode
*N
) {
8306 SDValue N0
= N
->getOperand(0);
8307 EVT VT
= N
->getValueType(0);
8309 // fold (cttz c1) -> c2
8310 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8311 return DAG
.getNode(ISD::CTTZ
, SDLoc(N
), VT
, N0
);
8313 // If the value is known never to be zero, switch to the undef version.
8314 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTTZ_ZERO_UNDEF
, VT
)) {
8315 if (DAG
.isKnownNeverZero(N0
))
8316 return DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8322 SDValue
DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode
*N
) {
8323 SDValue N0
= N
->getOperand(0);
8324 EVT VT
= N
->getValueType(0);
8326 // fold (cttz_zero_undef c1) -> c2
8327 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8328 return DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8332 SDValue
DAGCombiner::visitCTPOP(SDNode
*N
) {
8333 SDValue N0
= N
->getOperand(0);
8334 EVT VT
= N
->getValueType(0);
8336 // fold (ctpop c1) -> c2
8337 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8338 return DAG
.getNode(ISD::CTPOP
, SDLoc(N
), VT
, N0
);
8342 // FIXME: This should be checking for no signed zeros on individual operands, as
8344 static bool isLegalToCombineMinNumMaxNum(SelectionDAG
&DAG
, SDValue LHS
,
8346 const TargetLowering
&TLI
) {
8347 const TargetOptions
&Options
= DAG
.getTarget().Options
;
8348 EVT VT
= LHS
.getValueType();
8350 return Options
.NoSignedZerosFPMath
&& VT
.isFloatingPoint() &&
8351 TLI
.isProfitableToCombineMinNumMaxNum(VT
) &&
8352 DAG
.isKnownNeverNaN(LHS
) && DAG
.isKnownNeverNaN(RHS
);
8355 /// Generate Min/Max node
8356 static SDValue
combineMinNumMaxNum(const SDLoc
&DL
, EVT VT
, SDValue LHS
,
8357 SDValue RHS
, SDValue True
, SDValue False
,
8358 ISD::CondCode CC
, const TargetLowering
&TLI
,
8359 SelectionDAG
&DAG
) {
8360 if (!(LHS
== True
&& RHS
== False
) && !(LHS
== False
&& RHS
== True
))
8363 EVT TransformVT
= TLI
.getTypeToTransformTo(*DAG
.getContext(), VT
);
8371 // Since it's known never nan to get here already, either fminnum or
8372 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
8373 // expanded in terms of it.
8374 unsigned IEEEOpcode
= (LHS
== True
) ? ISD::FMINNUM_IEEE
: ISD::FMAXNUM_IEEE
;
8375 if (TLI
.isOperationLegalOrCustom(IEEEOpcode
, VT
))
8376 return DAG
.getNode(IEEEOpcode
, DL
, VT
, LHS
, RHS
);
8378 unsigned Opcode
= (LHS
== True
) ? ISD::FMINNUM
: ISD::FMAXNUM
;
8379 if (TLI
.isOperationLegalOrCustom(Opcode
, TransformVT
))
8380 return DAG
.getNode(Opcode
, DL
, VT
, LHS
, RHS
);
8389 unsigned IEEEOpcode
= (LHS
== True
) ? ISD::FMAXNUM_IEEE
: ISD::FMINNUM_IEEE
;
8390 if (TLI
.isOperationLegalOrCustom(IEEEOpcode
, VT
))
8391 return DAG
.getNode(IEEEOpcode
, DL
, VT
, LHS
, RHS
);
8393 unsigned Opcode
= (LHS
== True
) ? ISD::FMAXNUM
: ISD::FMINNUM
;
8394 if (TLI
.isOperationLegalOrCustom(Opcode
, TransformVT
))
8395 return DAG
.getNode(Opcode
, DL
, VT
, LHS
, RHS
);
8403 SDValue
DAGCombiner::foldSelectOfConstants(SDNode
*N
) {
8404 SDValue Cond
= N
->getOperand(0);
8405 SDValue N1
= N
->getOperand(1);
8406 SDValue N2
= N
->getOperand(2);
8407 EVT VT
= N
->getValueType(0);
8408 EVT CondVT
= Cond
.getValueType();
8411 if (!VT
.isInteger())
8414 auto *C1
= dyn_cast
<ConstantSDNode
>(N1
);
8415 auto *C2
= dyn_cast
<ConstantSDNode
>(N2
);
8419 // Only do this before legalization to avoid conflicting with target-specific
8420 // transforms in the other direction (create a select from a zext/sext). There
8421 // is also a target-independent combine here in DAGCombiner in the other
8422 // direction for (select Cond, -1, 0) when the condition is not i1.
8423 if (CondVT
== MVT::i1
&& !LegalOperations
) {
8424 if (C1
->isNullValue() && C2
->isOne()) {
8425 // select Cond, 0, 1 --> zext (!Cond)
8426 SDValue NotCond
= DAG
.getNOT(DL
, Cond
, MVT::i1
);
8428 NotCond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, NotCond
);
8431 if (C1
->isNullValue() && C2
->isAllOnesValue()) {
8432 // select Cond, 0, -1 --> sext (!Cond)
8433 SDValue NotCond
= DAG
.getNOT(DL
, Cond
, MVT::i1
);
8435 NotCond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, NotCond
);
8438 if (C1
->isOne() && C2
->isNullValue()) {
8439 // select Cond, 1, 0 --> zext (Cond)
8441 Cond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Cond
);
8444 if (C1
->isAllOnesValue() && C2
->isNullValue()) {
8445 // select Cond, -1, 0 --> sext (Cond)
8447 Cond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Cond
);
8451 // For any constants that differ by 1, we can transform the select into an
8452 // extend and add. Use a target hook because some targets may prefer to
8453 // transform in the other direction.
8454 if (TLI
.convertSelectOfConstantsToMath(VT
)) {
8455 if (C1
->getAPIntValue() - 1 == C2
->getAPIntValue()) {
8456 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
8458 Cond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Cond
);
8459 return DAG
.getNode(ISD::ADD
, DL
, VT
, Cond
, N2
);
8461 if (C1
->getAPIntValue() + 1 == C2
->getAPIntValue()) {
8462 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
8464 Cond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Cond
);
8465 return DAG
.getNode(ISD::ADD
, DL
, VT
, Cond
, N2
);
8472 // fold (select Cond, 0, 1) -> (xor Cond, 1)
8473 // We can't do this reliably if integer based booleans have different contents
8474 // to floating point based booleans. This is because we can't tell whether we
8475 // have an integer-based boolean or a floating-point-based boolean unless we
8476 // can find the SETCC that produced it and inspect its operands. This is
8477 // fairly easy if C is the SETCC node, but it can potentially be
8478 // undiscoverable (or not reasonably discoverable). For example, it could be
8479 // in another basic block or it could require searching a complicated
8481 if (CondVT
.isInteger() &&
8482 TLI
.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
8483 TargetLowering::ZeroOrOneBooleanContent
&&
8484 TLI
.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
8485 TargetLowering::ZeroOrOneBooleanContent
&&
8486 C1
->isNullValue() && C2
->isOne()) {
8488 DAG
.getNode(ISD::XOR
, DL
, CondVT
, Cond
, DAG
.getConstant(1, DL
, CondVT
));
8489 if (VT
.bitsEq(CondVT
))
8491 return DAG
.getZExtOrTrunc(NotCond
, DL
, VT
);
8497 SDValue
DAGCombiner::visitSELECT(SDNode
*N
) {
8498 SDValue N0
= N
->getOperand(0);
8499 SDValue N1
= N
->getOperand(1);
8500 SDValue N2
= N
->getOperand(2);
8501 EVT VT
= N
->getValueType(0);
8502 EVT VT0
= N0
.getValueType();
8504 SDNodeFlags Flags
= N
->getFlags();
8506 if (SDValue V
= DAG
.simplifySelect(N0
, N1
, N2
))
8509 // fold (select X, X, Y) -> (or X, Y)
8510 // fold (select X, 1, Y) -> (or C, Y)
8511 if (VT
== VT0
&& VT
== MVT::i1
&& (N0
== N1
|| isOneConstant(N1
)))
8512 return DAG
.getNode(ISD::OR
, DL
, VT
, N0
, N2
);
8514 if (SDValue V
= foldSelectOfConstants(N
))
8517 // fold (select C, 0, X) -> (and (not C), X)
8518 if (VT
== VT0
&& VT
== MVT::i1
&& isNullConstant(N1
)) {
8519 SDValue NOTNode
= DAG
.getNOT(SDLoc(N0
), N0
, VT
);
8520 AddToWorklist(NOTNode
.getNode());
8521 return DAG
.getNode(ISD::AND
, DL
, VT
, NOTNode
, N2
);
8523 // fold (select C, X, 1) -> (or (not C), X)
8524 if (VT
== VT0
&& VT
== MVT::i1
&& isOneConstant(N2
)) {
8525 SDValue NOTNode
= DAG
.getNOT(SDLoc(N0
), N0
, VT
);
8526 AddToWorklist(NOTNode
.getNode());
8527 return DAG
.getNode(ISD::OR
, DL
, VT
, NOTNode
, N1
);
8529 // fold (select X, Y, X) -> (and X, Y)
8530 // fold (select X, Y, 0) -> (and X, Y)
8531 if (VT
== VT0
&& VT
== MVT::i1
&& (N0
== N2
|| isNullConstant(N2
)))
8532 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, N1
);
8534 // If we can fold this based on the true/false value, do so.
8535 if (SimplifySelectOps(N
, N1
, N2
))
8536 return SDValue(N
, 0); // Don't revisit N.
8538 if (VT0
== MVT::i1
) {
8539 // The code in this block deals with the following 2 equivalences:
8540 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
8541 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
8542 // The target can specify its preferred form with the
8543 // shouldNormalizeToSelectSequence() callback. However we always transform
8544 // to the right anyway if we find the inner select exists in the DAG anyway
8545 // and we always transform to the left side if we know that we can further
8546 // optimize the combination of the conditions.
8547 bool normalizeToSequence
=
8548 TLI
.shouldNormalizeToSelectSequence(*DAG
.getContext(), VT
);
8549 // select (and Cond0, Cond1), X, Y
8550 // -> select Cond0, (select Cond1, X, Y), Y
8551 if (N0
->getOpcode() == ISD::AND
&& N0
->hasOneUse()) {
8552 SDValue Cond0
= N0
->getOperand(0);
8553 SDValue Cond1
= N0
->getOperand(1);
8554 SDValue InnerSelect
=
8555 DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond1
, N1
, N2
, Flags
);
8556 if (normalizeToSequence
|| !InnerSelect
.use_empty())
8557 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond0
,
8558 InnerSelect
, N2
, Flags
);
8559 // Cleanup on failure.
8560 if (InnerSelect
.use_empty())
8561 recursivelyDeleteUnusedNodes(InnerSelect
.getNode());
8563 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
8564 if (N0
->getOpcode() == ISD::OR
&& N0
->hasOneUse()) {
8565 SDValue Cond0
= N0
->getOperand(0);
8566 SDValue Cond1
= N0
->getOperand(1);
8567 SDValue InnerSelect
= DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(),
8568 Cond1
, N1
, N2
, Flags
);
8569 if (normalizeToSequence
|| !InnerSelect
.use_empty())
8570 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond0
, N1
,
8571 InnerSelect
, Flags
);
8572 // Cleanup on failure.
8573 if (InnerSelect
.use_empty())
8574 recursivelyDeleteUnusedNodes(InnerSelect
.getNode());
8577 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
8578 if (N1
->getOpcode() == ISD::SELECT
&& N1
->hasOneUse()) {
8579 SDValue N1_0
= N1
->getOperand(0);
8580 SDValue N1_1
= N1
->getOperand(1);
8581 SDValue N1_2
= N1
->getOperand(2);
8582 if (N1_2
== N2
&& N0
.getValueType() == N1_0
.getValueType()) {
8583 // Create the actual and node if we can generate good code for it.
8584 if (!normalizeToSequence
) {
8585 SDValue And
= DAG
.getNode(ISD::AND
, DL
, N0
.getValueType(), N0
, N1_0
);
8586 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), And
, N1_1
,
8589 // Otherwise see if we can optimize the "and" to a better pattern.
8590 if (SDValue Combined
= visitANDLike(N0
, N1_0
, N
)) {
8591 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Combined
, N1_1
,
8596 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
8597 if (N2
->getOpcode() == ISD::SELECT
&& N2
->hasOneUse()) {
8598 SDValue N2_0
= N2
->getOperand(0);
8599 SDValue N2_1
= N2
->getOperand(1);
8600 SDValue N2_2
= N2
->getOperand(2);
8601 if (N2_1
== N1
&& N0
.getValueType() == N2_0
.getValueType()) {
8602 // Create the actual or node if we can generate good code for it.
8603 if (!normalizeToSequence
) {
8604 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, N0
.getValueType(), N0
, N2_0
);
8605 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Or
, N1
,
8608 // Otherwise see if we can optimize to a better pattern.
8609 if (SDValue Combined
= visitORLike(N0
, N2_0
, N
))
8610 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Combined
, N1
,
8616 // select (not Cond), N1, N2 -> select Cond, N2, N1
8617 if (SDValue F
= extractBooleanFlip(N0
, DAG
, TLI
, false)) {
8618 SDValue SelectOp
= DAG
.getSelect(DL
, VT
, F
, N2
, N1
);
8619 SelectOp
->setFlags(Flags
);
8623 // Fold selects based on a setcc into other things, such as min/max/abs.
8624 if (N0
.getOpcode() == ISD::SETCC
) {
8625 SDValue Cond0
= N0
.getOperand(0), Cond1
= N0
.getOperand(1);
8626 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
8628 // select (fcmp lt x, y), x, y -> fminnum x, y
8629 // select (fcmp gt x, y), x, y -> fmaxnum x, y
8631 // This is OK if we don't care what happens if either operand is a NaN.
8632 if (N0
.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG
, N1
, N2
, TLI
))
8633 if (SDValue FMinMax
= combineMinNumMaxNum(DL
, VT
, Cond0
, Cond1
, N1
, N2
,
8637 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
8638 // This is conservatively limited to pre-legal-operations to give targets
8639 // a chance to reverse the transform if they want to do that. Also, it is
8640 // unlikely that the pattern would be formed late, so it's probably not
8641 // worth going through the other checks.
8642 if (!LegalOperations
&& TLI
.isOperationLegalOrCustom(ISD::UADDO
, VT
) &&
8643 CC
== ISD::SETUGT
&& N0
.hasOneUse() && isAllOnesConstant(N1
) &&
8644 N2
.getOpcode() == ISD::ADD
&& Cond0
== N2
.getOperand(0)) {
8645 auto *C
= dyn_cast
<ConstantSDNode
>(N2
.getOperand(1));
8646 auto *NotC
= dyn_cast
<ConstantSDNode
>(Cond1
);
8647 if (C
&& NotC
&& C
->getAPIntValue() == ~NotC
->getAPIntValue()) {
8648 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
8649 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
8651 // The IR equivalent of this transform would have this form:
8653 // %c = icmp ugt %x, ~C
8654 // %r = select %c, -1, %a
8656 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
8657 // %u0 = extractvalue %u, 0
8658 // %u1 = extractvalue %u, 1
8659 // %r = select %u1, -1, %u0
8660 SDVTList VTs
= DAG
.getVTList(VT
, VT0
);
8661 SDValue UAO
= DAG
.getNode(ISD::UADDO
, DL
, VTs
, Cond0
, N2
.getOperand(1));
8662 return DAG
.getSelect(DL
, VT
, UAO
.getValue(1), N1
, UAO
.getValue(0));
8666 if (TLI
.isOperationLegal(ISD::SELECT_CC
, VT
) ||
8667 (!LegalOperations
&&
8668 TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
))) {
8669 // Any flags available in a select/setcc fold will be on the setcc as they
8670 // migrated from fcmp
8671 Flags
= N0
.getNode()->getFlags();
8672 SDValue SelectNode
= DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Cond0
, Cond1
, N1
,
8673 N2
, N0
.getOperand(2));
8674 SelectNode
->setFlags(Flags
);
8678 return SimplifySelect(DL
, N0
, N1
, N2
);
8684 // This function assumes all the vselect's arguments are CONCAT_VECTOR
8685 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
8686 static SDValue
ConvertSelectToConcatVector(SDNode
*N
, SelectionDAG
&DAG
) {
8688 SDValue Cond
= N
->getOperand(0);
8689 SDValue LHS
= N
->getOperand(1);
8690 SDValue RHS
= N
->getOperand(2);
8691 EVT VT
= N
->getValueType(0);
8692 int NumElems
= VT
.getVectorNumElements();
8693 assert(LHS
.getOpcode() == ISD::CONCAT_VECTORS
&&
8694 RHS
.getOpcode() == ISD::CONCAT_VECTORS
&&
8695 Cond
.getOpcode() == ISD::BUILD_VECTOR
);
8697 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
8698 // binary ones here.
8699 if (LHS
->getNumOperands() != 2 || RHS
->getNumOperands() != 2)
8702 // We're sure we have an even number of elements due to the
8703 // concat_vectors we have as arguments to vselect.
8704 // Skip BV elements until we find one that's not an UNDEF
8705 // After we find an UNDEF element, keep looping until we get to half the
8706 // length of the BV and see if all the non-undef nodes are the same.
8707 ConstantSDNode
*BottomHalf
= nullptr;
8708 for (int i
= 0; i
< NumElems
/ 2; ++i
) {
8709 if (Cond
->getOperand(i
)->isUndef())
8712 if (BottomHalf
== nullptr)
8713 BottomHalf
= cast
<ConstantSDNode
>(Cond
.getOperand(i
));
8714 else if (Cond
->getOperand(i
).getNode() != BottomHalf
)
8718 // Do the same for the second half of the BuildVector
8719 ConstantSDNode
*TopHalf
= nullptr;
8720 for (int i
= NumElems
/ 2; i
< NumElems
; ++i
) {
8721 if (Cond
->getOperand(i
)->isUndef())
8724 if (TopHalf
== nullptr)
8725 TopHalf
= cast
<ConstantSDNode
>(Cond
.getOperand(i
));
8726 else if (Cond
->getOperand(i
).getNode() != TopHalf
)
8730 assert(TopHalf
&& BottomHalf
&&
8731 "One half of the selector was all UNDEFs and the other was all the "
8732 "same value. This should have been addressed before this function.");
8734 ISD::CONCAT_VECTORS
, DL
, VT
,
8735 BottomHalf
->isNullValue() ? RHS
->getOperand(0) : LHS
->getOperand(0),
8736 TopHalf
->isNullValue() ? RHS
->getOperand(1) : LHS
->getOperand(1));
8739 SDValue
DAGCombiner::visitMSCATTER(SDNode
*N
) {
8740 MaskedScatterSDNode
*MSC
= cast
<MaskedScatterSDNode
>(N
);
8741 SDValue Mask
= MSC
->getMask();
8742 SDValue Chain
= MSC
->getChain();
8745 // Zap scatters with a zero mask.
8746 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8752 SDValue
DAGCombiner::visitMSTORE(SDNode
*N
) {
8753 MaskedStoreSDNode
*MST
= cast
<MaskedStoreSDNode
>(N
);
8754 SDValue Mask
= MST
->getMask();
8755 SDValue Chain
= MST
->getChain();
8758 // Zap masked stores with a zero mask.
8759 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8765 SDValue
DAGCombiner::visitMGATHER(SDNode
*N
) {
8766 MaskedGatherSDNode
*MGT
= cast
<MaskedGatherSDNode
>(N
);
8767 SDValue Mask
= MGT
->getMask();
8770 // Zap gathers with a zero mask.
8771 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8772 return CombineTo(N
, MGT
->getPassThru(), MGT
->getChain());
8777 SDValue
DAGCombiner::visitMLOAD(SDNode
*N
) {
8778 MaskedLoadSDNode
*MLD
= cast
<MaskedLoadSDNode
>(N
);
8779 SDValue Mask
= MLD
->getMask();
8782 // Zap masked loads with a zero mask.
8783 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8784 return CombineTo(N
, MLD
->getPassThru(), MLD
->getChain());
8789 /// A vector select of 2 constant vectors can be simplified to math/logic to
8790 /// avoid a variable select instruction and possibly avoid constant loads.
8791 SDValue
DAGCombiner::foldVSelectOfConstants(SDNode
*N
) {
8792 SDValue Cond
= N
->getOperand(0);
8793 SDValue N1
= N
->getOperand(1);
8794 SDValue N2
= N
->getOperand(2);
8795 EVT VT
= N
->getValueType(0);
8796 if (!Cond
.hasOneUse() || Cond
.getScalarValueSizeInBits() != 1 ||
8797 !TLI
.convertSelectOfConstantsToMath(VT
) ||
8798 !ISD::isBuildVectorOfConstantSDNodes(N1
.getNode()) ||
8799 !ISD::isBuildVectorOfConstantSDNodes(N2
.getNode()))
8802 // Check if we can use the condition value to increment/decrement a single
8803 // constant value. This simplifies a select to an add and removes a constant
8804 // load/materialization from the general case.
8805 bool AllAddOne
= true;
8806 bool AllSubOne
= true;
8807 unsigned Elts
= VT
.getVectorNumElements();
8808 for (unsigned i
= 0; i
!= Elts
; ++i
) {
8809 SDValue N1Elt
= N1
.getOperand(i
);
8810 SDValue N2Elt
= N2
.getOperand(i
);
8811 if (N1Elt
.isUndef() || N2Elt
.isUndef())
8814 const APInt
&C1
= cast
<ConstantSDNode
>(N1Elt
)->getAPIntValue();
8815 const APInt
&C2
= cast
<ConstantSDNode
>(N2Elt
)->getAPIntValue();
8822 // Further simplifications for the extra-special cases where the constants are
8823 // all 0 or all -1 should be implemented as folds of these patterns.
8825 if (AllAddOne
|| AllSubOne
) {
8826 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
8827 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
8828 auto ExtendOpcode
= AllAddOne
? ISD::ZERO_EXTEND
: ISD::SIGN_EXTEND
;
8829 SDValue ExtendedCond
= DAG
.getNode(ExtendOpcode
, DL
, VT
, Cond
);
8830 return DAG
.getNode(ISD::ADD
, DL
, VT
, ExtendedCond
, N2
);
8833 // The general case for select-of-constants:
8834 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
8835 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
8836 // leave that to a machine-specific pass.
8840 SDValue
DAGCombiner::visitVSELECT(SDNode
*N
) {
8841 SDValue N0
= N
->getOperand(0);
8842 SDValue N1
= N
->getOperand(1);
8843 SDValue N2
= N
->getOperand(2);
8844 EVT VT
= N
->getValueType(0);
8847 if (SDValue V
= DAG
.simplifySelect(N0
, N1
, N2
))
8850 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
8851 if (SDValue F
= extractBooleanFlip(N0
, DAG
, TLI
, false))
8852 return DAG
.getSelect(DL
, VT
, F
, N2
, N1
);
8854 // Canonicalize integer abs.
8855 // vselect (setg[te] X, 0), X, -X ->
8856 // vselect (setgt X, -1), X, -X ->
8857 // vselect (setl[te] X, 0), -X, X ->
8858 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8859 if (N0
.getOpcode() == ISD::SETCC
) {
8860 SDValue LHS
= N0
.getOperand(0), RHS
= N0
.getOperand(1);
8861 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
8863 bool RHSIsAllZeros
= ISD::isBuildVectorAllZeros(RHS
.getNode());
8865 if (((RHSIsAllZeros
&& (CC
== ISD::SETGT
|| CC
== ISD::SETGE
)) ||
8866 (ISD::isBuildVectorAllOnes(RHS
.getNode()) && CC
== ISD::SETGT
)) &&
8867 N1
== LHS
&& N2
.getOpcode() == ISD::SUB
&& N1
== N2
.getOperand(1))
8868 isAbs
= ISD::isBuildVectorAllZeros(N2
.getOperand(0).getNode());
8869 else if ((RHSIsAllZeros
&& (CC
== ISD::SETLT
|| CC
== ISD::SETLE
)) &&
8870 N2
== LHS
&& N1
.getOpcode() == ISD::SUB
&& N2
== N1
.getOperand(1))
8871 isAbs
= ISD::isBuildVectorAllZeros(N1
.getOperand(0).getNode());
8874 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
))
8875 return DAG
.getNode(ISD::ABS
, DL
, VT
, LHS
);
8877 SDValue Shift
= DAG
.getNode(ISD::SRA
, DL
, VT
, LHS
,
8878 DAG
.getConstant(VT
.getScalarSizeInBits() - 1,
8879 DL
, getShiftAmountTy(VT
)));
8880 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, LHS
, Shift
);
8881 AddToWorklist(Shift
.getNode());
8882 AddToWorklist(Add
.getNode());
8883 return DAG
.getNode(ISD::XOR
, DL
, VT
, Add
, Shift
);
8886 // vselect x, y (fcmp lt x, y) -> fminnum x, y
8887 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
8889 // This is OK if we don't care about what happens if either operand is a
8892 if (N0
.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG
, LHS
, RHS
, TLI
)) {
8893 if (SDValue FMinMax
=
8894 combineMinNumMaxNum(DL
, VT
, LHS
, RHS
, N1
, N2
, CC
, TLI
, DAG
))
8898 // If this select has a condition (setcc) with narrower operands than the
8899 // select, try to widen the compare to match the select width.
8900 // TODO: This should be extended to handle any constant.
8901 // TODO: This could be extended to handle non-loading patterns, but that
8902 // requires thorough testing to avoid regressions.
8903 if (isNullOrNullSplat(RHS
)) {
8904 EVT NarrowVT
= LHS
.getValueType();
8905 EVT WideVT
= N1
.getValueType().changeVectorElementTypeToInteger();
8906 EVT SetCCVT
= getSetCCResultType(LHS
.getValueType());
8907 unsigned SetCCWidth
= SetCCVT
.getScalarSizeInBits();
8908 unsigned WideWidth
= WideVT
.getScalarSizeInBits();
8909 bool IsSigned
= isSignedIntSetCC(CC
);
8910 auto LoadExtOpcode
= IsSigned
? ISD::SEXTLOAD
: ISD::ZEXTLOAD
;
8911 if (LHS
.getOpcode() == ISD::LOAD
&& LHS
.hasOneUse() &&
8912 SetCCWidth
!= 1 && SetCCWidth
< WideWidth
&&
8913 TLI
.isLoadExtLegalOrCustom(LoadExtOpcode
, WideVT
, NarrowVT
) &&
8914 TLI
.isOperationLegalOrCustom(ISD::SETCC
, WideVT
)) {
8915 // Both compare operands can be widened for free. The LHS can use an
8916 // extended load, and the RHS is a constant:
8917 // vselect (ext (setcc load(X), C)), N1, N2 -->
8918 // vselect (setcc extload(X), C'), N1, N2
8919 auto ExtOpcode
= IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
8920 SDValue WideLHS
= DAG
.getNode(ExtOpcode
, DL
, WideVT
, LHS
);
8921 SDValue WideRHS
= DAG
.getNode(ExtOpcode
, DL
, WideVT
, RHS
);
8922 EVT WideSetCCVT
= getSetCCResultType(WideVT
);
8923 SDValue WideSetCC
= DAG
.getSetCC(DL
, WideSetCCVT
, WideLHS
, WideRHS
, CC
);
8924 return DAG
.getSelect(DL
, N1
.getValueType(), WideSetCC
, N1
, N2
);
8929 if (SimplifySelectOps(N
, N1
, N2
))
8930 return SDValue(N
, 0); // Don't revisit N.
8932 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
8933 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
8935 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
8936 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
8939 // The ConvertSelectToConcatVector function is assuming both the above
8940 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
8942 if (N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
8943 N2
.getOpcode() == ISD::CONCAT_VECTORS
&&
8944 ISD::isBuildVectorOfConstantSDNodes(N0
.getNode())) {
8945 if (SDValue CV
= ConvertSelectToConcatVector(N
, DAG
))
8949 if (SDValue V
= foldVSelectOfConstants(N
))
8955 SDValue
DAGCombiner::visitSELECT_CC(SDNode
*N
) {
8956 SDValue N0
= N
->getOperand(0);
8957 SDValue N1
= N
->getOperand(1);
8958 SDValue N2
= N
->getOperand(2);
8959 SDValue N3
= N
->getOperand(3);
8960 SDValue N4
= N
->getOperand(4);
8961 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N4
)->get();
8963 // fold select_cc lhs, rhs, x, x, cc -> x
8967 // Determine if the condition we're dealing with is constant
8968 if (SDValue SCC
= SimplifySetCC(getSetCCResultType(N0
.getValueType()), N0
, N1
,
8969 CC
, SDLoc(N
), false)) {
8970 AddToWorklist(SCC
.getNode());
8972 if (ConstantSDNode
*SCCC
= dyn_cast
<ConstantSDNode
>(SCC
.getNode())) {
8973 if (!SCCC
->isNullValue())
8974 return N2
; // cond always true -> true val
8976 return N3
; // cond always false -> false val
8977 } else if (SCC
->isUndef()) {
8978 // When the condition is UNDEF, just return the first operand. This is
8979 // coherent the DAG creation, no setcc node is created in this case
8981 } else if (SCC
.getOpcode() == ISD::SETCC
) {
8982 // Fold to a simpler select_cc
8983 SDValue SelectOp
= DAG
.getNode(
8984 ISD::SELECT_CC
, SDLoc(N
), N2
.getValueType(), SCC
.getOperand(0),
8985 SCC
.getOperand(1), N2
, N3
, SCC
.getOperand(2));
8986 SelectOp
->setFlags(SCC
->getFlags());
8991 // If we can fold this based on the true/false value, do so.
8992 if (SimplifySelectOps(N
, N2
, N3
))
8993 return SDValue(N
, 0); // Don't revisit N.
8995 // fold select_cc into other things, such as min/max/abs
8996 return SimplifySelectCC(SDLoc(N
), N0
, N1
, N2
, N3
, CC
);
8999 SDValue
DAGCombiner::visitSETCC(SDNode
*N
) {
9000 // setcc is very commonly used as an argument to brcond. This pattern
9001 // also lend itself to numerous combines and, as a result, it is desired
9002 // we keep the argument to a brcond as a setcc as much as possible.
9004 N
->hasOneUse() && N
->use_begin()->getOpcode() == ISD::BRCOND
;
9006 SDValue Combined
= SimplifySetCC(
9007 N
->getValueType(0), N
->getOperand(0), N
->getOperand(1),
9008 cast
<CondCodeSDNode
>(N
->getOperand(2))->get(), SDLoc(N
), !PreferSetCC
);
9013 // If we prefer to have a setcc, and we don't, we'll try our best to
9014 // recreate one using rebuildSetCC.
9015 if (PreferSetCC
&& Combined
.getOpcode() != ISD::SETCC
) {
9016 SDValue NewSetCC
= rebuildSetCC(Combined
);
9018 // We don't have anything interesting to combine to.
9019 if (NewSetCC
.getNode() == N
)
9029 SDValue
DAGCombiner::visitSETCCCARRY(SDNode
*N
) {
9030 SDValue LHS
= N
->getOperand(0);
9031 SDValue RHS
= N
->getOperand(1);
9032 SDValue Carry
= N
->getOperand(2);
9033 SDValue Cond
= N
->getOperand(3);
9035 // If Carry is false, fold to a regular SETCC.
9036 if (isNullConstant(Carry
))
9037 return DAG
.getNode(ISD::SETCC
, SDLoc(N
), N
->getVTList(), LHS
, RHS
, Cond
);
9042 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
9043 /// a build_vector of constants.
9044 /// This function is called by the DAGCombiner when visiting sext/zext/aext
9045 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
9046 /// Vector extends are not folded if operations are legal; this is to
9047 /// avoid introducing illegal build_vector dag nodes.
9048 static SDValue
tryToFoldExtendOfConstant(SDNode
*N
, const TargetLowering
&TLI
,
9049 SelectionDAG
&DAG
, bool LegalTypes
) {
9050 unsigned Opcode
= N
->getOpcode();
9051 SDValue N0
= N
->getOperand(0);
9052 EVT VT
= N
->getValueType(0);
9055 assert((Opcode
== ISD::SIGN_EXTEND
|| Opcode
== ISD::ZERO_EXTEND
||
9056 Opcode
== ISD::ANY_EXTEND
|| Opcode
== ISD::SIGN_EXTEND_VECTOR_INREG
||
9057 Opcode
== ISD::ZERO_EXTEND_VECTOR_INREG
)
9058 && "Expected EXTEND dag node in input!");
9060 // fold (sext c1) -> c1
9061 // fold (zext c1) -> c1
9062 // fold (aext c1) -> c1
9063 if (isa
<ConstantSDNode
>(N0
))
9064 return DAG
.getNode(Opcode
, DL
, VT
, N0
);
9066 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
9067 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
9068 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
9069 if (N0
->getOpcode() == ISD::SELECT
) {
9070 SDValue Op1
= N0
->getOperand(1);
9071 SDValue Op2
= N0
->getOperand(2);
9072 if (isa
<ConstantSDNode
>(Op1
) && isa
<ConstantSDNode
>(Op2
) &&
9073 (Opcode
!= ISD::ZERO_EXTEND
|| !TLI
.isZExtFree(N0
.getValueType(), VT
))) {
9074 // For any_extend, choose sign extension of the constants to allow a
9075 // possible further transform to sign_extend_inreg.i.e.
9077 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
9078 // t2: i64 = any_extend t1
9080 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
9082 // t4: i64 = sign_extend_inreg t3
9083 unsigned FoldOpc
= Opcode
;
9084 if (FoldOpc
== ISD::ANY_EXTEND
)
9085 FoldOpc
= ISD::SIGN_EXTEND
;
9086 return DAG
.getSelect(DL
, VT
, N0
->getOperand(0),
9087 DAG
.getNode(FoldOpc
, DL
, VT
, Op1
),
9088 DAG
.getNode(FoldOpc
, DL
, VT
, Op2
));
9092 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
9093 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
9094 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
9095 EVT SVT
= VT
.getScalarType();
9096 if (!(VT
.isVector() && (!LegalTypes
|| TLI
.isTypeLegal(SVT
)) &&
9097 ISD::isBuildVectorOfConstantSDNodes(N0
.getNode())))
9100 // We can fold this node into a build_vector.
9101 unsigned VTBits
= SVT
.getSizeInBits();
9102 unsigned EVTBits
= N0
->getValueType(0).getScalarSizeInBits();
9103 SmallVector
<SDValue
, 8> Elts
;
9104 unsigned NumElts
= VT
.getVectorNumElements();
9106 // For zero-extensions, UNDEF elements still guarantee to have the upper
9107 // bits set to zero.
9109 Opcode
== ISD::ZERO_EXTEND
|| Opcode
== ISD::ZERO_EXTEND_VECTOR_INREG
;
9111 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
9112 SDValue Op
= N0
.getOperand(i
);
9114 Elts
.push_back(IsZext
? DAG
.getConstant(0, DL
, SVT
) : DAG
.getUNDEF(SVT
));
9119 // Get the constant value and if needed trunc it to the size of the type.
9120 // Nodes like build_vector might have constants wider than the scalar type.
9121 APInt C
= cast
<ConstantSDNode
>(Op
)->getAPIntValue().zextOrTrunc(EVTBits
);
9122 if (Opcode
== ISD::SIGN_EXTEND
|| Opcode
== ISD::SIGN_EXTEND_VECTOR_INREG
)
9123 Elts
.push_back(DAG
.getConstant(C
.sext(VTBits
), DL
, SVT
));
9125 Elts
.push_back(DAG
.getConstant(C
.zext(VTBits
), DL
, SVT
));
9128 return DAG
.getBuildVector(VT
, DL
, Elts
);
9131 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
9132 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
9133 // transformation. Returns true if extension are possible and the above
9134 // mentioned transformation is profitable.
9135 static bool ExtendUsesToFormExtLoad(EVT VT
, SDNode
*N
, SDValue N0
,
9137 SmallVectorImpl
<SDNode
*> &ExtendNodes
,
9138 const TargetLowering
&TLI
) {
9139 bool HasCopyToRegUses
= false;
9140 bool isTruncFree
= TLI
.isTruncateFree(VT
, N0
.getValueType());
9141 for (SDNode::use_iterator UI
= N0
.getNode()->use_begin(),
9142 UE
= N0
.getNode()->use_end();
9147 if (UI
.getUse().getResNo() != N0
.getResNo())
9149 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
9150 if (ExtOpc
!= ISD::ANY_EXTEND
&& User
->getOpcode() == ISD::SETCC
) {
9151 ISD::CondCode CC
= cast
<CondCodeSDNode
>(User
->getOperand(2))->get();
9152 if (ExtOpc
== ISD::ZERO_EXTEND
&& ISD::isSignedIntSetCC(CC
))
9153 // Sign bits will be lost after a zext.
9156 for (unsigned i
= 0; i
!= 2; ++i
) {
9157 SDValue UseOp
= User
->getOperand(i
);
9160 if (!isa
<ConstantSDNode
>(UseOp
))
9165 ExtendNodes
.push_back(User
);
9168 // If truncates aren't free and there are users we can't
9169 // extend, it isn't worthwhile.
9172 // Remember if this value is live-out.
9173 if (User
->getOpcode() == ISD::CopyToReg
)
9174 HasCopyToRegUses
= true;
9177 if (HasCopyToRegUses
) {
9178 bool BothLiveOut
= false;
9179 for (SDNode::use_iterator UI
= N
->use_begin(), UE
= N
->use_end();
9181 SDUse
&Use
= UI
.getUse();
9182 if (Use
.getResNo() == 0 && Use
.getUser()->getOpcode() == ISD::CopyToReg
) {
9188 // Both unextended and extended values are live out. There had better be
9189 // a good reason for the transformation.
9190 return ExtendNodes
.size();
9195 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl
<SDNode
*> &SetCCs
,
9196 SDValue OrigLoad
, SDValue ExtLoad
,
9197 ISD::NodeType ExtType
) {
9198 // Extend SetCC uses if necessary.
9200 for (SDNode
*SetCC
: SetCCs
) {
9201 SmallVector
<SDValue
, 4> Ops
;
9203 for (unsigned j
= 0; j
!= 2; ++j
) {
9204 SDValue SOp
= SetCC
->getOperand(j
);
9205 if (SOp
== OrigLoad
)
9206 Ops
.push_back(ExtLoad
);
9208 Ops
.push_back(DAG
.getNode(ExtType
, DL
, ExtLoad
->getValueType(0), SOp
));
9211 Ops
.push_back(SetCC
->getOperand(2));
9212 CombineTo(SetCC
, DAG
.getNode(ISD::SETCC
, DL
, SetCC
->getValueType(0), Ops
));
9216 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
9217 SDValue
DAGCombiner::CombineExtLoad(SDNode
*N
) {
9218 SDValue N0
= N
->getOperand(0);
9219 EVT DstVT
= N
->getValueType(0);
9220 EVT SrcVT
= N0
.getValueType();
9222 assert((N
->getOpcode() == ISD::SIGN_EXTEND
||
9223 N
->getOpcode() == ISD::ZERO_EXTEND
) &&
9224 "Unexpected node type (not an extend)!");
9226 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
9227 // For example, on a target with legal v4i32, but illegal v8i32, turn:
9228 // (v8i32 (sext (v8i16 (load x))))
9230 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9231 // (v4i32 (sextload (x + 16)))))
9232 // Where uses of the original load, i.e.:
9234 // are replaced with:
9236 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9237 // (v4i32 (sextload (x + 16)))))))
9239 // This combine is only applicable to illegal, but splittable, vectors.
9240 // All legal types, and illegal non-vector types, are handled elsewhere.
9241 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
9243 if (N0
->getOpcode() != ISD::LOAD
)
9246 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9248 if (!ISD::isNON_EXTLoad(LN0
) || !ISD::isUNINDEXEDLoad(LN0
) ||
9249 !N0
.hasOneUse() || !LN0
->isSimple() ||
9250 !DstVT
.isVector() || !DstVT
.isPow2VectorType() ||
9251 !TLI
.isVectorLoadExtDesirable(SDValue(N
, 0)))
9254 SmallVector
<SDNode
*, 4> SetCCs
;
9255 if (!ExtendUsesToFormExtLoad(DstVT
, N
, N0
, N
->getOpcode(), SetCCs
, TLI
))
9258 ISD::LoadExtType ExtType
=
9259 N
->getOpcode() == ISD::SIGN_EXTEND
? ISD::SEXTLOAD
: ISD::ZEXTLOAD
;
9261 // Try to split the vector types to get down to legal types.
9262 EVT SplitSrcVT
= SrcVT
;
9263 EVT SplitDstVT
= DstVT
;
9264 while (!TLI
.isLoadExtLegalOrCustom(ExtType
, SplitDstVT
, SplitSrcVT
) &&
9265 SplitSrcVT
.getVectorNumElements() > 1) {
9266 SplitDstVT
= DAG
.GetSplitDestVTs(SplitDstVT
).first
;
9267 SplitSrcVT
= DAG
.GetSplitDestVTs(SplitSrcVT
).first
;
9270 if (!TLI
.isLoadExtLegalOrCustom(ExtType
, SplitDstVT
, SplitSrcVT
))
9274 const unsigned NumSplits
=
9275 DstVT
.getVectorNumElements() / SplitDstVT
.getVectorNumElements();
9276 const unsigned Stride
= SplitSrcVT
.getStoreSize();
9277 SmallVector
<SDValue
, 4> Loads
;
9278 SmallVector
<SDValue
, 4> Chains
;
9280 SDValue BasePtr
= LN0
->getBasePtr();
9281 for (unsigned Idx
= 0; Idx
< NumSplits
; Idx
++) {
9282 const unsigned Offset
= Idx
* Stride
;
9283 const unsigned Align
= MinAlign(LN0
->getAlignment(), Offset
);
9285 SDValue SplitLoad
= DAG
.getExtLoad(
9286 ExtType
, SDLoc(LN0
), SplitDstVT
, LN0
->getChain(), BasePtr
,
9287 LN0
->getPointerInfo().getWithOffset(Offset
), SplitSrcVT
, Align
,
9288 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
9290 BasePtr
= DAG
.getNode(ISD::ADD
, DL
, BasePtr
.getValueType(), BasePtr
,
9291 DAG
.getConstant(Stride
, DL
, BasePtr
.getValueType()));
9293 Loads
.push_back(SplitLoad
.getValue(0));
9294 Chains
.push_back(SplitLoad
.getValue(1));
9297 SDValue NewChain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, Chains
);
9298 SDValue NewValue
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, DstVT
, Loads
);
9301 AddToWorklist(NewChain
.getNode());
9303 CombineTo(N
, NewValue
);
9305 // Replace uses of the original load (before extension)
9306 // with a truncate of the concatenated sextloaded vectors.
9308 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), N0
.getValueType(), NewValue
);
9309 ExtendSetCCUses(SetCCs
, N0
, NewValue
, (ISD::NodeType
)N
->getOpcode());
9310 CombineTo(N0
.getNode(), Trunc
, NewChain
);
9311 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9314 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9315 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9316 SDValue
DAGCombiner::CombineZExtLogicopShiftLoad(SDNode
*N
) {
9317 assert(N
->getOpcode() == ISD::ZERO_EXTEND
);
9318 EVT VT
= N
->getValueType(0);
9319 EVT OrigVT
= N
->getOperand(0).getValueType();
9320 if (TLI
.isZExtFree(OrigVT
, VT
))
9324 SDValue N0
= N
->getOperand(0);
9325 if (!(N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9326 N0
.getOpcode() == ISD::XOR
) ||
9327 N0
.getOperand(1).getOpcode() != ISD::Constant
||
9328 (LegalOperations
&& !TLI
.isOperationLegal(N0
.getOpcode(), VT
)))
9332 SDValue N1
= N0
->getOperand(0);
9333 if (!(N1
.getOpcode() == ISD::SHL
|| N1
.getOpcode() == ISD::SRL
) ||
9334 N1
.getOperand(1).getOpcode() != ISD::Constant
||
9335 (LegalOperations
&& !TLI
.isOperationLegal(N1
.getOpcode(), VT
)))
9339 if (!isa
<LoadSDNode
>(N1
.getOperand(0)))
9341 LoadSDNode
*Load
= cast
<LoadSDNode
>(N1
.getOperand(0));
9342 EVT MemVT
= Load
->getMemoryVT();
9343 if (!TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
) ||
9344 Load
->getExtensionType() == ISD::SEXTLOAD
|| Load
->isIndexed())
9348 // If the shift op is SHL, the logic op must be AND, otherwise the result
9350 if (N1
.getOpcode() == ISD::SHL
&& N0
.getOpcode() != ISD::AND
)
9353 if (!N0
.hasOneUse() || !N1
.hasOneUse())
9356 SmallVector
<SDNode
*, 4> SetCCs
;
9357 if (!ExtendUsesToFormExtLoad(VT
, N1
.getNode(), N1
.getOperand(0),
9358 ISD::ZERO_EXTEND
, SetCCs
, TLI
))
9361 // Actually do the transformation.
9362 SDValue ExtLoad
= DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(Load
), VT
,
9363 Load
->getChain(), Load
->getBasePtr(),
9364 Load
->getMemoryVT(), Load
->getMemOperand());
9367 SDValue Shift
= DAG
.getNode(N1
.getOpcode(), DL1
, VT
, ExtLoad
,
9370 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9371 Mask
= Mask
.zext(VT
.getSizeInBits());
9373 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL0
, VT
, Shift
,
9374 DAG
.getConstant(Mask
, DL0
, VT
));
9376 ExtendSetCCUses(SetCCs
, N1
.getOperand(0), ExtLoad
, ISD::ZERO_EXTEND
);
9378 if (SDValue(Load
, 0).hasOneUse()) {
9379 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 1), ExtLoad
.getValue(1));
9381 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(Load
),
9382 Load
->getValueType(0), ExtLoad
);
9383 CombineTo(Load
, Trunc
, ExtLoad
.getValue(1));
9386 // N0 is dead at this point.
9387 recursivelyDeleteUnusedNodes(N0
.getNode());
9389 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9392 /// If we're narrowing or widening the result of a vector select and the final
9393 /// size is the same size as a setcc (compare) feeding the select, then try to
9394 /// apply the cast operation to the select's operands because matching vector
9395 /// sizes for a select condition and other operands should be more efficient.
9396 SDValue
DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode
*Cast
) {
9397 unsigned CastOpcode
= Cast
->getOpcode();
9398 assert((CastOpcode
== ISD::SIGN_EXTEND
|| CastOpcode
== ISD::ZERO_EXTEND
||
9399 CastOpcode
== ISD::TRUNCATE
|| CastOpcode
== ISD::FP_EXTEND
||
9400 CastOpcode
== ISD::FP_ROUND
) &&
9401 "Unexpected opcode for vector select narrowing/widening");
9403 // We only do this transform before legal ops because the pattern may be
9404 // obfuscated by target-specific operations after legalization. Do not create
9405 // an illegal select op, however, because that may be difficult to lower.
9406 EVT VT
= Cast
->getValueType(0);
9407 if (LegalOperations
|| !TLI
.isOperationLegalOrCustom(ISD::VSELECT
, VT
))
9410 SDValue VSel
= Cast
->getOperand(0);
9411 if (VSel
.getOpcode() != ISD::VSELECT
|| !VSel
.hasOneUse() ||
9412 VSel
.getOperand(0).getOpcode() != ISD::SETCC
)
9415 // Does the setcc have the same vector size as the casted select?
9416 SDValue SetCC
= VSel
.getOperand(0);
9417 EVT SetCCVT
= getSetCCResultType(SetCC
.getOperand(0).getValueType());
9418 if (SetCCVT
.getSizeInBits() != VT
.getSizeInBits())
9421 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
9422 SDValue A
= VSel
.getOperand(1);
9423 SDValue B
= VSel
.getOperand(2);
9424 SDValue CastA
, CastB
;
9426 if (CastOpcode
== ISD::FP_ROUND
) {
9427 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
9428 CastA
= DAG
.getNode(CastOpcode
, DL
, VT
, A
, Cast
->getOperand(1));
9429 CastB
= DAG
.getNode(CastOpcode
, DL
, VT
, B
, Cast
->getOperand(1));
9431 CastA
= DAG
.getNode(CastOpcode
, DL
, VT
, A
);
9432 CastB
= DAG
.getNode(CastOpcode
, DL
, VT
, B
);
9434 return DAG
.getNode(ISD::VSELECT
, DL
, VT
, SetCC
, CastA
, CastB
);
9437 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9438 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9439 static SDValue
tryToFoldExtOfExtload(SelectionDAG
&DAG
, DAGCombiner
&Combiner
,
9440 const TargetLowering
&TLI
, EVT VT
,
9441 bool LegalOperations
, SDNode
*N
,
9442 SDValue N0
, ISD::LoadExtType ExtLoadType
) {
9443 SDNode
*N0Node
= N0
.getNode();
9444 bool isAExtLoad
= (ExtLoadType
== ISD::SEXTLOAD
) ? ISD::isSEXTLoad(N0Node
)
9445 : ISD::isZEXTLoad(N0Node
);
9446 if ((!isAExtLoad
&& !ISD::isEXTLoad(N0Node
)) ||
9447 !ISD::isUNINDEXEDLoad(N0Node
) || !N0
.hasOneUse())
9450 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9451 EVT MemVT
= LN0
->getMemoryVT();
9452 if ((LegalOperations
|| !LN0
->isSimple() ||
9454 !TLI
.isLoadExtLegal(ExtLoadType
, VT
, MemVT
))
9458 DAG
.getExtLoad(ExtLoadType
, SDLoc(LN0
), VT
, LN0
->getChain(),
9459 LN0
->getBasePtr(), MemVT
, LN0
->getMemOperand());
9460 Combiner
.CombineTo(N
, ExtLoad
);
9461 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9462 if (LN0
->use_empty())
9463 Combiner
.recursivelyDeleteUnusedNodes(LN0
);
9464 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9467 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9468 // Only generate vector extloads when 1) they're legal, and 2) they are
9469 // deemed desirable by the target.
9470 static SDValue
tryToFoldExtOfLoad(SelectionDAG
&DAG
, DAGCombiner
&Combiner
,
9471 const TargetLowering
&TLI
, EVT VT
,
9472 bool LegalOperations
, SDNode
*N
, SDValue N0
,
9473 ISD::LoadExtType ExtLoadType
,
9474 ISD::NodeType ExtOpc
) {
9475 if (!ISD::isNON_EXTLoad(N0
.getNode()) ||
9476 !ISD::isUNINDEXEDLoad(N0
.getNode()) ||
9477 ((LegalOperations
|| VT
.isVector() ||
9478 !cast
<LoadSDNode
>(N0
)->isSimple()) &&
9479 !TLI
.isLoadExtLegal(ExtLoadType
, VT
, N0
.getValueType())))
9482 bool DoXform
= true;
9483 SmallVector
<SDNode
*, 4> SetCCs
;
9484 if (!N0
.hasOneUse())
9485 DoXform
= ExtendUsesToFormExtLoad(VT
, N
, N0
, ExtOpc
, SetCCs
, TLI
);
9487 DoXform
&= TLI
.isVectorLoadExtDesirable(SDValue(N
, 0));
9491 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9492 SDValue ExtLoad
= DAG
.getExtLoad(ExtLoadType
, SDLoc(LN0
), VT
, LN0
->getChain(),
9493 LN0
->getBasePtr(), N0
.getValueType(),
9494 LN0
->getMemOperand());
9495 Combiner
.ExtendSetCCUses(SetCCs
, N0
, ExtLoad
, ExtOpc
);
9496 // If the load value is used only by N, replace it via CombineTo N.
9497 bool NoReplaceTrunc
= SDValue(LN0
, 0).hasOneUse();
9498 Combiner
.CombineTo(N
, ExtLoad
);
9499 if (NoReplaceTrunc
) {
9500 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9501 Combiner
.recursivelyDeleteUnusedNodes(LN0
);
9504 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), N0
.getValueType(), ExtLoad
);
9505 Combiner
.CombineTo(LN0
, Trunc
, ExtLoad
.getValue(1));
9507 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9510 static SDValue
foldExtendedSignBitTest(SDNode
*N
, SelectionDAG
&DAG
,
9511 bool LegalOperations
) {
9512 assert((N
->getOpcode() == ISD::SIGN_EXTEND
||
9513 N
->getOpcode() == ISD::ZERO_EXTEND
) && "Expected sext or zext");
9515 SDValue SetCC
= N
->getOperand(0);
9516 if (LegalOperations
|| SetCC
.getOpcode() != ISD::SETCC
||
9517 !SetCC
.hasOneUse() || SetCC
.getValueType() != MVT::i1
)
9520 SDValue X
= SetCC
.getOperand(0);
9521 SDValue Ones
= SetCC
.getOperand(1);
9522 ISD::CondCode CC
= cast
<CondCodeSDNode
>(SetCC
.getOperand(2))->get();
9523 EVT VT
= N
->getValueType(0);
9524 EVT XVT
= X
.getValueType();
9525 // setge X, C is canonicalized to setgt, so we do not need to match that
9526 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
9527 // not require the 'not' op.
9528 if (CC
== ISD::SETGT
&& isAllOnesConstant(Ones
) && VT
== XVT
) {
9529 // Invert and smear/shift the sign bit:
9530 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
9531 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
9533 SDValue NotX
= DAG
.getNOT(DL
, X
, VT
);
9534 SDValue ShiftAmount
= DAG
.getConstant(VT
.getSizeInBits() - 1, DL
, VT
);
9535 auto ShiftOpcode
= N
->getOpcode() == ISD::SIGN_EXTEND
? ISD::SRA
: ISD::SRL
;
9536 return DAG
.getNode(ShiftOpcode
, DL
, VT
, NotX
, ShiftAmount
);
9541 SDValue
DAGCombiner::visitSIGN_EXTEND(SDNode
*N
) {
9542 SDValue N0
= N
->getOperand(0);
9543 EVT VT
= N
->getValueType(0);
9546 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
9549 // fold (sext (sext x)) -> (sext x)
9550 // fold (sext (aext x)) -> (sext x)
9551 if (N0
.getOpcode() == ISD::SIGN_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
)
9552 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, N0
.getOperand(0));
9554 if (N0
.getOpcode() == ISD::TRUNCATE
) {
9555 // fold (sext (truncate (load x))) -> (sext (smaller load x))
9556 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
9557 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
9558 SDNode
*oye
= N0
.getOperand(0).getNode();
9559 if (NarrowLoad
.getNode() != N0
.getNode()) {
9560 CombineTo(N0
.getNode(), NarrowLoad
);
9561 // CombineTo deleted the truncate, if needed, but not what's under it.
9564 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9567 // See if the value being truncated is already sign extended. If so, just
9568 // eliminate the trunc/sext pair.
9569 SDValue Op
= N0
.getOperand(0);
9570 unsigned OpBits
= Op
.getScalarValueSizeInBits();
9571 unsigned MidBits
= N0
.getScalarValueSizeInBits();
9572 unsigned DestBits
= VT
.getScalarSizeInBits();
9573 unsigned NumSignBits
= DAG
.ComputeNumSignBits(Op
);
9575 if (OpBits
== DestBits
) {
9576 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9577 // bits, it is already ready.
9578 if (NumSignBits
> DestBits
-MidBits
)
9580 } else if (OpBits
< DestBits
) {
9581 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9582 // bits, just sext from i32.
9583 if (NumSignBits
> OpBits
-MidBits
)
9584 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Op
);
9586 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9587 // bits, just truncate to i32.
9588 if (NumSignBits
> OpBits
-MidBits
)
9589 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Op
);
9592 // fold (sext (truncate x)) -> (sextinreg x).
9593 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
,
9594 N0
.getValueType())) {
9595 if (OpBits
< DestBits
)
9596 Op
= DAG
.getNode(ISD::ANY_EXTEND
, SDLoc(N0
), VT
, Op
);
9597 else if (OpBits
> DestBits
)
9598 Op
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), VT
, Op
);
9599 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, DL
, VT
, Op
,
9600 DAG
.getValueType(N0
.getValueType()));
9604 // Try to simplify (sext (load x)).
9605 if (SDValue foldedExt
=
9606 tryToFoldExtOfLoad(DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
,
9607 ISD::SEXTLOAD
, ISD::SIGN_EXTEND
))
9610 // fold (sext (load x)) to multiple smaller sextloads.
9611 // Only on illegal but splittable vectors.
9612 if (SDValue ExtLoad
= CombineExtLoad(N
))
9615 // Try to simplify (sext (sextload x)).
9616 if (SDValue foldedExt
= tryToFoldExtOfExtload(
9617 DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
, ISD::SEXTLOAD
))
9620 // fold (sext (and/or/xor (load x), cst)) ->
9621 // (and/or/xor (sextload x), (sext cst))
9622 if ((N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9623 N0
.getOpcode() == ISD::XOR
) &&
9624 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
9625 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9626 (!LegalOperations
&& TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
9627 LoadSDNode
*LN00
= cast
<LoadSDNode
>(N0
.getOperand(0));
9628 EVT MemVT
= LN00
->getMemoryVT();
9629 if (TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, MemVT
) &&
9630 LN00
->getExtensionType() != ISD::ZEXTLOAD
&& LN00
->isUnindexed()) {
9631 SmallVector
<SDNode
*, 4> SetCCs
;
9632 bool DoXform
= ExtendUsesToFormExtLoad(VT
, N0
.getNode(), N0
.getOperand(0),
9633 ISD::SIGN_EXTEND
, SetCCs
, TLI
);
9635 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(LN00
), VT
,
9636 LN00
->getChain(), LN00
->getBasePtr(),
9637 LN00
->getMemoryVT(),
9638 LN00
->getMemOperand());
9639 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9640 Mask
= Mask
.sext(VT
.getSizeInBits());
9641 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL
, VT
,
9642 ExtLoad
, DAG
.getConstant(Mask
, DL
, VT
));
9643 ExtendSetCCUses(SetCCs
, N0
.getOperand(0), ExtLoad
, ISD::SIGN_EXTEND
);
9644 bool NoReplaceTruncAnd
= !N0
.hasOneUse();
9645 bool NoReplaceTrunc
= SDValue(LN00
, 0).hasOneUse();
9647 // If N0 has multiple uses, change other uses as well.
9648 if (NoReplaceTruncAnd
) {
9650 DAG
.getNode(ISD::TRUNCATE
, DL
, N0
.getValueType(), And
);
9651 CombineTo(N0
.getNode(), TruncAnd
);
9653 if (NoReplaceTrunc
) {
9654 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN00
, 1), ExtLoad
.getValue(1));
9656 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LN00
),
9657 LN00
->getValueType(0), ExtLoad
);
9658 CombineTo(LN00
, Trunc
, ExtLoad
.getValue(1));
9660 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9665 if (SDValue V
= foldExtendedSignBitTest(N
, DAG
, LegalOperations
))
9668 if (N0
.getOpcode() == ISD::SETCC
) {
9669 SDValue N00
= N0
.getOperand(0);
9670 SDValue N01
= N0
.getOperand(1);
9671 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
9672 EVT N00VT
= N0
.getOperand(0).getValueType();
9674 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
9675 // Only do this before legalize for now.
9676 if (VT
.isVector() && !LegalOperations
&&
9677 TLI
.getBooleanContents(N00VT
) ==
9678 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
9679 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
9680 // of the same size as the compared operands. Only optimize sext(setcc())
9681 // if this is the case.
9682 EVT SVT
= getSetCCResultType(N00VT
);
9684 // If we already have the desired type, don't change it.
9685 if (SVT
!= N0
.getValueType()) {
9686 // We know that the # elements of the results is the same as the
9687 // # elements of the compare (and the # elements of the compare result
9688 // for that matter). Check to see that they are the same size. If so,
9689 // we know that the element size of the sext'd result matches the
9690 // element size of the compare operands.
9691 if (VT
.getSizeInBits() == SVT
.getSizeInBits())
9692 return DAG
.getSetCC(DL
, VT
, N00
, N01
, CC
);
9694 // If the desired elements are smaller or larger than the source
9695 // elements, we can use a matching integer vector type and then
9696 // truncate/sign extend.
9697 EVT MatchingVecType
= N00VT
.changeVectorElementTypeToInteger();
9698 if (SVT
== MatchingVecType
) {
9699 SDValue VsetCC
= DAG
.getSetCC(DL
, MatchingVecType
, N00
, N01
, CC
);
9700 return DAG
.getSExtOrTrunc(VsetCC
, DL
, VT
);
9705 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
9706 // Here, T can be 1 or -1, depending on the type of the setcc and
9707 // getBooleanContents().
9708 unsigned SetCCWidth
= N0
.getScalarValueSizeInBits();
9710 // To determine the "true" side of the select, we need to know the high bit
9711 // of the value returned by the setcc if it evaluates to true.
9712 // If the type of the setcc is i1, then the true case of the select is just
9713 // sext(i1 1), that is, -1.
9714 // If the type of the setcc is larger (say, i8) then the value of the high
9715 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
9716 // of the appropriate width.
9717 SDValue ExtTrueVal
= (SetCCWidth
== 1)
9718 ? DAG
.getAllOnesConstant(DL
, VT
)
9719 : DAG
.getBoolConstant(true, DL
, VT
, N00VT
);
9720 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
9722 SimplifySelectCC(DL
, N00
, N01
, ExtTrueVal
, Zero
, CC
, true))
9725 if (!VT
.isVector() && !TLI
.convertSelectOfConstantsToMath(VT
)) {
9726 EVT SetCCVT
= getSetCCResultType(N00VT
);
9727 // Don't do this transform for i1 because there's a select transform
9728 // that would reverse it.
9729 // TODO: We should not do this transform at all without a target hook
9730 // because a sext is likely cheaper than a select?
9731 if (SetCCVT
.getScalarSizeInBits() != 1 &&
9732 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SETCC
, N00VT
))) {
9733 SDValue SetCC
= DAG
.getSetCC(DL
, SetCCVT
, N00
, N01
, CC
);
9734 return DAG
.getSelect(DL
, VT
, SetCC
, ExtTrueVal
, Zero
);
9739 // fold (sext x) -> (zext x) if the sign bit is known zero.
9740 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
)) &&
9741 DAG
.SignBitIsZero(N0
))
9742 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
);
9744 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
9747 // Eliminate this sign extend by doing a negation in the destination type:
9748 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
9749 if (N0
.getOpcode() == ISD::SUB
&& N0
.hasOneUse() &&
9750 isNullOrNullSplat(N0
.getOperand(0)) &&
9751 N0
.getOperand(1).getOpcode() == ISD::ZERO_EXTEND
&&
9752 TLI
.isOperationLegalOrCustom(ISD::SUB
, VT
)) {
9753 SDValue Zext
= DAG
.getZExtOrTrunc(N0
.getOperand(1).getOperand(0), DL
, VT
);
9754 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), Zext
);
9756 // Eliminate this sign extend by doing a decrement in the destination type:
9757 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
9758 if (N0
.getOpcode() == ISD::ADD
&& N0
.hasOneUse() &&
9759 isAllOnesOrAllOnesSplat(N0
.getOperand(1)) &&
9760 N0
.getOperand(0).getOpcode() == ISD::ZERO_EXTEND
&&
9761 TLI
.isOperationLegalOrCustom(ISD::ADD
, VT
)) {
9762 SDValue Zext
= DAG
.getZExtOrTrunc(N0
.getOperand(0).getOperand(0), DL
, VT
);
9763 return DAG
.getNode(ISD::ADD
, DL
, VT
, Zext
, DAG
.getAllOnesConstant(DL
, VT
));
9769 // isTruncateOf - If N is a truncate of some other value, return true, record
9770 // the value being truncated in Op and which of Op's bits are zero/one in Known.
9771 // This function computes KnownBits to avoid a duplicated call to
9772 // computeKnownBits in the caller.
9773 static bool isTruncateOf(SelectionDAG
&DAG
, SDValue N
, SDValue
&Op
,
9775 if (N
->getOpcode() == ISD::TRUNCATE
) {
9776 Op
= N
->getOperand(0);
9777 Known
= DAG
.computeKnownBits(Op
);
9781 if (N
.getOpcode() != ISD::SETCC
||
9782 N
.getValueType().getScalarType() != MVT::i1
||
9783 cast
<CondCodeSDNode
>(N
.getOperand(2))->get() != ISD::SETNE
)
9786 SDValue Op0
= N
->getOperand(0);
9787 SDValue Op1
= N
->getOperand(1);
9788 assert(Op0
.getValueType() == Op1
.getValueType());
9790 if (isNullOrNullSplat(Op0
))
9792 else if (isNullOrNullSplat(Op1
))
9797 Known
= DAG
.computeKnownBits(Op
);
9799 return (Known
.Zero
| 1).isAllOnesValue();
9802 SDValue
DAGCombiner::visitZERO_EXTEND(SDNode
*N
) {
9803 SDValue N0
= N
->getOperand(0);
9804 EVT VT
= N
->getValueType(0);
9806 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
9809 // fold (zext (zext x)) -> (zext x)
9810 // fold (zext (aext x)) -> (zext x)
9811 if (N0
.getOpcode() == ISD::ZERO_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
)
9812 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), VT
,
9815 // fold (zext (truncate x)) -> (zext x) or
9816 // (zext (truncate x)) -> (truncate x)
9817 // This is valid when the truncated bits of x are already zero.
9820 if (isTruncateOf(DAG
, N0
, Op
, Known
)) {
9821 APInt TruncatedBits
=
9822 (Op
.getScalarValueSizeInBits() == N0
.getScalarValueSizeInBits()) ?
9823 APInt(Op
.getScalarValueSizeInBits(), 0) :
9824 APInt::getBitsSet(Op
.getScalarValueSizeInBits(),
9825 N0
.getScalarValueSizeInBits(),
9826 std::min(Op
.getScalarValueSizeInBits(),
9827 VT
.getScalarSizeInBits()));
9828 if (TruncatedBits
.isSubsetOf(Known
.Zero
))
9829 return DAG
.getZExtOrTrunc(Op
, SDLoc(N
), VT
);
9832 // fold (zext (truncate x)) -> (and x, mask)
9833 if (N0
.getOpcode() == ISD::TRUNCATE
) {
9834 // fold (zext (truncate (load x))) -> (zext (smaller load x))
9835 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
9836 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
9837 SDNode
*oye
= N0
.getOperand(0).getNode();
9838 if (NarrowLoad
.getNode() != N0
.getNode()) {
9839 CombineTo(N0
.getNode(), NarrowLoad
);
9840 // CombineTo deleted the truncate, if needed, but not what's under it.
9843 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9846 EVT SrcVT
= N0
.getOperand(0).getValueType();
9847 EVT MinVT
= N0
.getValueType();
9849 // Try to mask before the extension to avoid having to generate a larger mask,
9850 // possibly over several sub-vectors.
9851 if (SrcVT
.bitsLT(VT
) && VT
.isVector()) {
9852 if (!LegalOperations
|| (TLI
.isOperationLegal(ISD::AND
, SrcVT
) &&
9853 TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
))) {
9854 SDValue Op
= N0
.getOperand(0);
9855 Op
= DAG
.getZeroExtendInReg(Op
, SDLoc(N
), MinVT
.getScalarType());
9856 AddToWorklist(Op
.getNode());
9857 SDValue ZExtOrTrunc
= DAG
.getZExtOrTrunc(Op
, SDLoc(N
), VT
);
9858 // Transfer the debug info; the new node is equivalent to N0.
9859 DAG
.transferDbgValues(N0
, ZExtOrTrunc
);
9864 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::AND
, VT
)) {
9865 SDValue Op
= DAG
.getAnyExtOrTrunc(N0
.getOperand(0), SDLoc(N
), VT
);
9866 AddToWorklist(Op
.getNode());
9867 SDValue And
= DAG
.getZeroExtendInReg(Op
, SDLoc(N
), MinVT
.getScalarType());
9868 // We may safely transfer the debug info describing the truncate node over
9869 // to the equivalent and operation.
9870 DAG
.transferDbgValues(N0
, And
);
9875 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
9876 // if either of the casts is not free.
9877 if (N0
.getOpcode() == ISD::AND
&&
9878 N0
.getOperand(0).getOpcode() == ISD::TRUNCATE
&&
9879 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9880 (!TLI
.isTruncateFree(N0
.getOperand(0).getOperand(0).getValueType(),
9881 N0
.getValueType()) ||
9882 !TLI
.isZExtFree(N0
.getValueType(), VT
))) {
9883 SDValue X
= N0
.getOperand(0).getOperand(0);
9884 X
= DAG
.getAnyExtOrTrunc(X
, SDLoc(X
), VT
);
9885 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9886 Mask
= Mask
.zext(VT
.getSizeInBits());
9888 return DAG
.getNode(ISD::AND
, DL
, VT
,
9889 X
, DAG
.getConstant(Mask
, DL
, VT
));
9892 // Try to simplify (zext (load x)).
9893 if (SDValue foldedExt
=
9894 tryToFoldExtOfLoad(DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
,
9895 ISD::ZEXTLOAD
, ISD::ZERO_EXTEND
))
9898 // fold (zext (load x)) to multiple smaller zextloads.
9899 // Only on illegal but splittable vectors.
9900 if (SDValue ExtLoad
= CombineExtLoad(N
))
9903 // fold (zext (and/or/xor (load x), cst)) ->
9904 // (and/or/xor (zextload x), (zext cst))
9905 // Unless (and (load x) cst) will match as a zextload already and has
9906 // additional users.
9907 if ((N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9908 N0
.getOpcode() == ISD::XOR
) &&
9909 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
9910 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9911 (!LegalOperations
&& TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
9912 LoadSDNode
*LN00
= cast
<LoadSDNode
>(N0
.getOperand(0));
9913 EVT MemVT
= LN00
->getMemoryVT();
9914 if (TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
) &&
9915 LN00
->getExtensionType() != ISD::SEXTLOAD
&& LN00
->isUnindexed()) {
9916 bool DoXform
= true;
9917 SmallVector
<SDNode
*, 4> SetCCs
;
9918 if (!N0
.hasOneUse()) {
9919 if (N0
.getOpcode() == ISD::AND
) {
9920 auto *AndC
= cast
<ConstantSDNode
>(N0
.getOperand(1));
9921 EVT LoadResultTy
= AndC
->getValueType(0);
9923 if (isAndLoadExtLoad(AndC
, LN00
, LoadResultTy
, ExtVT
))
9928 DoXform
= ExtendUsesToFormExtLoad(VT
, N0
.getNode(), N0
.getOperand(0),
9929 ISD::ZERO_EXTEND
, SetCCs
, TLI
);
9931 SDValue ExtLoad
= DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(LN00
), VT
,
9932 LN00
->getChain(), LN00
->getBasePtr(),
9933 LN00
->getMemoryVT(),
9934 LN00
->getMemOperand());
9935 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9936 Mask
= Mask
.zext(VT
.getSizeInBits());
9938 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL
, VT
,
9939 ExtLoad
, DAG
.getConstant(Mask
, DL
, VT
));
9940 ExtendSetCCUses(SetCCs
, N0
.getOperand(0), ExtLoad
, ISD::ZERO_EXTEND
);
9941 bool NoReplaceTruncAnd
= !N0
.hasOneUse();
9942 bool NoReplaceTrunc
= SDValue(LN00
, 0).hasOneUse();
9944 // If N0 has multiple uses, change other uses as well.
9945 if (NoReplaceTruncAnd
) {
9947 DAG
.getNode(ISD::TRUNCATE
, DL
, N0
.getValueType(), And
);
9948 CombineTo(N0
.getNode(), TruncAnd
);
9950 if (NoReplaceTrunc
) {
9951 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN00
, 1), ExtLoad
.getValue(1));
9953 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LN00
),
9954 LN00
->getValueType(0), ExtLoad
);
9955 CombineTo(LN00
, Trunc
, ExtLoad
.getValue(1));
9957 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9962 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9963 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9964 if (SDValue ZExtLoad
= CombineZExtLogicopShiftLoad(N
))
9967 // Try to simplify (zext (zextload x)).
9968 if (SDValue foldedExt
= tryToFoldExtOfExtload(
9969 DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
, ISD::ZEXTLOAD
))
9972 if (SDValue V
= foldExtendedSignBitTest(N
, DAG
, LegalOperations
))
9975 if (N0
.getOpcode() == ISD::SETCC
) {
9976 // Only do this before legalize for now.
9977 if (!LegalOperations
&& VT
.isVector() &&
9978 N0
.getValueType().getVectorElementType() == MVT::i1
) {
9979 EVT N00VT
= N0
.getOperand(0).getValueType();
9980 if (getSetCCResultType(N00VT
) == N0
.getValueType())
9983 // We know that the # elements of the results is the same as the #
9984 // elements of the compare (and the # elements of the compare result for
9985 // that matter). Check to see that they are the same size. If so, we know
9986 // that the element size of the sext'd result matches the element size of
9987 // the compare operands.
9989 SDValue VecOnes
= DAG
.getConstant(1, DL
, VT
);
9990 if (VT
.getSizeInBits() == N00VT
.getSizeInBits()) {
9991 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
9992 SDValue VSetCC
= DAG
.getNode(ISD::SETCC
, DL
, VT
, N0
.getOperand(0),
9993 N0
.getOperand(1), N0
.getOperand(2));
9994 return DAG
.getNode(ISD::AND
, DL
, VT
, VSetCC
, VecOnes
);
9997 // If the desired elements are smaller or larger than the source
9998 // elements we can use a matching integer vector type and then
9999 // truncate/sign extend.
10000 EVT MatchingVectorType
= N00VT
.changeVectorElementTypeToInteger();
10002 DAG
.getNode(ISD::SETCC
, DL
, MatchingVectorType
, N0
.getOperand(0),
10003 N0
.getOperand(1), N0
.getOperand(2));
10004 return DAG
.getNode(ISD::AND
, DL
, VT
, DAG
.getSExtOrTrunc(VsetCC
, DL
, VT
),
10008 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
10010 if (SDValue SCC
= SimplifySelectCC(
10011 DL
, N0
.getOperand(0), N0
.getOperand(1), DAG
.getConstant(1, DL
, VT
),
10012 DAG
.getConstant(0, DL
, VT
),
10013 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get(), true))
10017 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
10018 if ((N0
.getOpcode() == ISD::SHL
|| N0
.getOpcode() == ISD::SRL
) &&
10019 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
10020 N0
.getOperand(0).getOpcode() == ISD::ZERO_EXTEND
&&
10022 SDValue ShAmt
= N0
.getOperand(1);
10023 if (N0
.getOpcode() == ISD::SHL
) {
10024 SDValue InnerZExt
= N0
.getOperand(0);
10025 // If the original shl may be shifting out bits, do not perform this
10027 unsigned KnownZeroBits
= InnerZExt
.getValueSizeInBits() -
10028 InnerZExt
.getOperand(0).getValueSizeInBits();
10029 if (cast
<ConstantSDNode
>(ShAmt
)->getAPIntValue().ugt(KnownZeroBits
))
10035 // Ensure that the shift amount is wide enough for the shifted value.
10036 if (VT
.getSizeInBits() >= 256)
10037 ShAmt
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i32
, ShAmt
);
10039 return DAG
.getNode(N0
.getOpcode(), DL
, VT
,
10040 DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
.getOperand(0)),
10044 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
10050 SDValue
DAGCombiner::visitANY_EXTEND(SDNode
*N
) {
10051 SDValue N0
= N
->getOperand(0);
10052 EVT VT
= N
->getValueType(0);
10054 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
10057 // fold (aext (aext x)) -> (aext x)
10058 // fold (aext (zext x)) -> (zext x)
10059 // fold (aext (sext x)) -> (sext x)
10060 if (N0
.getOpcode() == ISD::ANY_EXTEND
||
10061 N0
.getOpcode() == ISD::ZERO_EXTEND
||
10062 N0
.getOpcode() == ISD::SIGN_EXTEND
)
10063 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, N0
.getOperand(0));
10065 // fold (aext (truncate (load x))) -> (aext (smaller load x))
10066 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
10067 if (N0
.getOpcode() == ISD::TRUNCATE
) {
10068 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
10069 SDNode
*oye
= N0
.getOperand(0).getNode();
10070 if (NarrowLoad
.getNode() != N0
.getNode()) {
10071 CombineTo(N0
.getNode(), NarrowLoad
);
10072 // CombineTo deleted the truncate, if needed, but not what's under it.
10073 AddToWorklist(oye
);
10075 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10079 // fold (aext (truncate x))
10080 if (N0
.getOpcode() == ISD::TRUNCATE
)
10081 return DAG
.getAnyExtOrTrunc(N0
.getOperand(0), SDLoc(N
), VT
);
10083 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
10084 // if the trunc is not free.
10085 if (N0
.getOpcode() == ISD::AND
&&
10086 N0
.getOperand(0).getOpcode() == ISD::TRUNCATE
&&
10087 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
10088 !TLI
.isTruncateFree(N0
.getOperand(0).getOperand(0).getValueType(),
10089 N0
.getValueType())) {
10091 SDValue X
= N0
.getOperand(0).getOperand(0);
10092 X
= DAG
.getAnyExtOrTrunc(X
, DL
, VT
);
10093 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
10094 Mask
= Mask
.zext(VT
.getSizeInBits());
10095 return DAG
.getNode(ISD::AND
, DL
, VT
,
10096 X
, DAG
.getConstant(Mask
, DL
, VT
));
10099 // fold (aext (load x)) -> (aext (truncate (extload x)))
10100 // None of the supported targets knows how to perform load and any_ext
10101 // on vectors in one instruction. We only perform this transformation on
10103 if (ISD::isNON_EXTLoad(N0
.getNode()) && !VT
.isVector() &&
10104 ISD::isUNINDEXEDLoad(N0
.getNode()) &&
10105 TLI
.isLoadExtLegal(ISD::EXTLOAD
, VT
, N0
.getValueType())) {
10106 bool DoXform
= true;
10107 SmallVector
<SDNode
*, 4> SetCCs
;
10108 if (!N0
.hasOneUse())
10109 DoXform
= ExtendUsesToFormExtLoad(VT
, N
, N0
, ISD::ANY_EXTEND
, SetCCs
,
10112 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10113 SDValue ExtLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, SDLoc(N
), VT
,
10115 LN0
->getBasePtr(), N0
.getValueType(),
10116 LN0
->getMemOperand());
10117 ExtendSetCCUses(SetCCs
, N0
, ExtLoad
, ISD::ANY_EXTEND
);
10118 // If the load value is used only by N, replace it via CombineTo N.
10119 bool NoReplaceTrunc
= N0
.hasOneUse();
10120 CombineTo(N
, ExtLoad
);
10121 if (NoReplaceTrunc
) {
10122 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
10123 recursivelyDeleteUnusedNodes(LN0
);
10125 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
),
10126 N0
.getValueType(), ExtLoad
);
10127 CombineTo(LN0
, Trunc
, ExtLoad
.getValue(1));
10129 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10133 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
10134 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
10135 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
10136 if (N0
.getOpcode() == ISD::LOAD
&& !ISD::isNON_EXTLoad(N0
.getNode()) &&
10137 ISD::isUNINDEXEDLoad(N0
.getNode()) && N0
.hasOneUse()) {
10138 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10139 ISD::LoadExtType ExtType
= LN0
->getExtensionType();
10140 EVT MemVT
= LN0
->getMemoryVT();
10141 if (!LegalOperations
|| TLI
.isLoadExtLegal(ExtType
, VT
, MemVT
)) {
10142 SDValue ExtLoad
= DAG
.getExtLoad(ExtType
, SDLoc(N
),
10143 VT
, LN0
->getChain(), LN0
->getBasePtr(),
10144 MemVT
, LN0
->getMemOperand());
10145 CombineTo(N
, ExtLoad
);
10146 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
10147 recursivelyDeleteUnusedNodes(LN0
);
10148 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10152 if (N0
.getOpcode() == ISD::SETCC
) {
10154 // aext(setcc) -> vsetcc
10155 // aext(setcc) -> truncate(vsetcc)
10156 // aext(setcc) -> aext(vsetcc)
10157 // Only do this before legalize for now.
10158 if (VT
.isVector() && !LegalOperations
) {
10159 EVT N00VT
= N0
.getOperand(0).getValueType();
10160 if (getSetCCResultType(N00VT
) == N0
.getValueType())
10163 // We know that the # elements of the results is the same as the
10164 // # elements of the compare (and the # elements of the compare result
10165 // for that matter). Check to see that they are the same size. If so,
10166 // we know that the element size of the sext'd result matches the
10167 // element size of the compare operands.
10168 if (VT
.getSizeInBits() == N00VT
.getSizeInBits())
10169 return DAG
.getSetCC(SDLoc(N
), VT
, N0
.getOperand(0),
10171 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
10173 // If the desired elements are smaller or larger than the source
10174 // elements we can use a matching integer vector type and then
10175 // truncate/any extend
10176 EVT MatchingVectorType
= N00VT
.changeVectorElementTypeToInteger();
10178 DAG
.getSetCC(SDLoc(N
), MatchingVectorType
, N0
.getOperand(0),
10180 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
10181 return DAG
.getAnyExtOrTrunc(VsetCC
, SDLoc(N
), VT
);
10184 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
10186 if (SDValue SCC
= SimplifySelectCC(
10187 DL
, N0
.getOperand(0), N0
.getOperand(1), DAG
.getConstant(1, DL
, VT
),
10188 DAG
.getConstant(0, DL
, VT
),
10189 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get(), true))
10196 SDValue
DAGCombiner::visitAssertExt(SDNode
*N
) {
10197 unsigned Opcode
= N
->getOpcode();
10198 SDValue N0
= N
->getOperand(0);
10199 SDValue N1
= N
->getOperand(1);
10200 EVT AssertVT
= cast
<VTSDNode
>(N1
)->getVT();
10202 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
10203 if (N0
.getOpcode() == Opcode
&&
10204 AssertVT
== cast
<VTSDNode
>(N0
.getOperand(1))->getVT())
10207 if (N0
.getOpcode() == ISD::TRUNCATE
&& N0
.hasOneUse() &&
10208 N0
.getOperand(0).getOpcode() == Opcode
) {
10209 // We have an assert, truncate, assert sandwich. Make one stronger assert
10210 // by asserting on the smallest asserted type to the larger source type.
10211 // This eliminates the later assert:
10212 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
10213 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
10214 SDValue BigA
= N0
.getOperand(0);
10215 EVT BigA_AssertVT
= cast
<VTSDNode
>(BigA
.getOperand(1))->getVT();
10216 assert(BigA_AssertVT
.bitsLE(N0
.getValueType()) &&
10217 "Asserting zero/sign-extended bits to a type larger than the "
10218 "truncated destination does not provide information");
10221 EVT MinAssertVT
= AssertVT
.bitsLT(BigA_AssertVT
) ? AssertVT
: BigA_AssertVT
;
10222 SDValue MinAssertVTVal
= DAG
.getValueType(MinAssertVT
);
10223 SDValue NewAssert
= DAG
.getNode(Opcode
, DL
, BigA
.getValueType(),
10224 BigA
.getOperand(0), MinAssertVTVal
);
10225 return DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), NewAssert
);
10228 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
10229 // than X. Just move the AssertZext in front of the truncate and drop the
10231 if (N0
.getOpcode() == ISD::TRUNCATE
&& N0
.hasOneUse() &&
10232 N0
.getOperand(0).getOpcode() == ISD::AssertSext
&&
10233 Opcode
== ISD::AssertZext
) {
10234 SDValue BigA
= N0
.getOperand(0);
10235 EVT BigA_AssertVT
= cast
<VTSDNode
>(BigA
.getOperand(1))->getVT();
10236 assert(BigA_AssertVT
.bitsLE(N0
.getValueType()) &&
10237 "Asserting zero/sign-extended bits to a type larger than the "
10238 "truncated destination does not provide information");
10240 if (AssertVT
.bitsLT(BigA_AssertVT
)) {
10242 SDValue NewAssert
= DAG
.getNode(Opcode
, DL
, BigA
.getValueType(),
10243 BigA
.getOperand(0), N1
);
10244 return DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), NewAssert
);
10251 /// If the result of a wider load is shifted to right of N bits and then
10252 /// truncated to a narrower type and where N is a multiple of number of bits of
10253 /// the narrower type, transform it to a narrower load from address + N / num of
10254 /// bits of new type. Also narrow the load if the result is masked with an AND
10255 /// to effectively produce a smaller type. If the result is to be extended, also
10256 /// fold the extension to form a extending load.
10257 SDValue
DAGCombiner::ReduceLoadWidth(SDNode
*N
) {
10258 unsigned Opc
= N
->getOpcode();
10260 ISD::LoadExtType ExtType
= ISD::NON_EXTLOAD
;
10261 SDValue N0
= N
->getOperand(0);
10262 EVT VT
= N
->getValueType(0);
10265 // This transformation isn't valid for vector loads.
10269 unsigned ShAmt
= 0;
10270 bool HasShiftedOffset
= false;
10271 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
10273 if (Opc
== ISD::SIGN_EXTEND_INREG
) {
10274 ExtType
= ISD::SEXTLOAD
;
10275 ExtVT
= cast
<VTSDNode
>(N
->getOperand(1))->getVT();
10276 } else if (Opc
== ISD::SRL
) {
10277 // Another special-case: SRL is basically zero-extending a narrower value,
10278 // or it maybe shifting a higher subword, half or byte into the lowest
10280 ExtType
= ISD::ZEXTLOAD
;
10281 N0
= SDValue(N
, 0);
10283 auto *LN0
= dyn_cast
<LoadSDNode
>(N0
.getOperand(0));
10284 auto *N01
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
10288 uint64_t ShiftAmt
= N01
->getZExtValue();
10289 uint64_t MemoryWidth
= LN0
->getMemoryVT().getSizeInBits();
10290 if (LN0
->getExtensionType() != ISD::SEXTLOAD
&& MemoryWidth
> ShiftAmt
)
10291 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), MemoryWidth
- ShiftAmt
);
10293 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(),
10294 VT
.getSizeInBits() - ShiftAmt
);
10295 } else if (Opc
== ISD::AND
) {
10296 // An AND with a constant mask is the same as a truncate + zero-extend.
10297 auto AndC
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
10301 const APInt
&Mask
= AndC
->getAPIntValue();
10302 unsigned ActiveBits
= 0;
10303 if (Mask
.isMask()) {
10304 ActiveBits
= Mask
.countTrailingOnes();
10305 } else if (Mask
.isShiftedMask()) {
10306 ShAmt
= Mask
.countTrailingZeros();
10307 APInt ShiftedMask
= Mask
.lshr(ShAmt
);
10308 ActiveBits
= ShiftedMask
.countTrailingOnes();
10309 HasShiftedOffset
= true;
10313 ExtType
= ISD::ZEXTLOAD
;
10314 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
10317 if (N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse()) {
10319 if (auto *ConstShift
= dyn_cast
<ConstantSDNode
>(SRL
.getOperand(1))) {
10320 ShAmt
= ConstShift
->getZExtValue();
10321 unsigned EVTBits
= ExtVT
.getSizeInBits();
10322 // Is the shift amount a multiple of size of VT?
10323 if ((ShAmt
& (EVTBits
-1)) == 0) {
10324 N0
= N0
.getOperand(0);
10325 // Is the load width a multiple of size of VT?
10326 if ((N0
.getValueSizeInBits() & (EVTBits
-1)) != 0)
10330 // At this point, we must have a load or else we can't do the transform.
10331 if (!isa
<LoadSDNode
>(N0
)) return SDValue();
10333 auto *LN0
= cast
<LoadSDNode
>(N0
);
10335 // Because a SRL must be assumed to *need* to zero-extend the high bits
10336 // (as opposed to anyext the high bits), we can't combine the zextload
10337 // lowering of SRL and an sextload.
10338 if (LN0
->getExtensionType() == ISD::SEXTLOAD
)
10341 // If the shift amount is larger than the input type then we're not
10342 // accessing any of the loaded bytes. If the load was a zextload/extload
10343 // then the result of the shift+trunc is zero/undef (handled elsewhere).
10344 if (ShAmt
>= LN0
->getMemoryVT().getSizeInBits())
10347 // If the SRL is only used by a masking AND, we may be able to adjust
10348 // the ExtVT to make the AND redundant.
10349 SDNode
*Mask
= *(SRL
->use_begin());
10350 if (Mask
->getOpcode() == ISD::AND
&&
10351 isa
<ConstantSDNode
>(Mask
->getOperand(1))) {
10352 const APInt
&ShiftMask
=
10353 cast
<ConstantSDNode
>(Mask
->getOperand(1))->getAPIntValue();
10354 if (ShiftMask
.isMask()) {
10355 EVT MaskedVT
= EVT::getIntegerVT(*DAG
.getContext(),
10356 ShiftMask
.countTrailingOnes());
10357 // If the mask is smaller, recompute the type.
10358 if ((ExtVT
.getSizeInBits() > MaskedVT
.getSizeInBits()) &&
10359 TLI
.isLoadExtLegal(ExtType
, N0
.getValueType(), MaskedVT
))
10366 // If the load is shifted left (and the result isn't shifted back right),
10367 // we can fold the truncate through the shift.
10368 unsigned ShLeftAmt
= 0;
10369 if (ShAmt
== 0 && N0
.getOpcode() == ISD::SHL
&& N0
.hasOneUse() &&
10370 ExtVT
== VT
&& TLI
.isNarrowingProfitable(N0
.getValueType(), VT
)) {
10371 if (ConstantSDNode
*N01
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
10372 ShLeftAmt
= N01
->getZExtValue();
10373 N0
= N0
.getOperand(0);
10377 // If we haven't found a load, we can't narrow it.
10378 if (!isa
<LoadSDNode
>(N0
))
10381 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10382 if (!isLegalNarrowLdSt(LN0
, ExtType
, ExtVT
, ShAmt
))
10385 auto AdjustBigEndianShift
= [&](unsigned ShAmt
) {
10386 unsigned LVTStoreBits
= LN0
->getMemoryVT().getStoreSizeInBits();
10387 unsigned EVTStoreBits
= ExtVT
.getStoreSizeInBits();
10388 return LVTStoreBits
- EVTStoreBits
- ShAmt
;
10391 // For big endian targets, we need to adjust the offset to the pointer to
10392 // load the correct bytes.
10393 if (DAG
.getDataLayout().isBigEndian())
10394 ShAmt
= AdjustBigEndianShift(ShAmt
);
10396 EVT PtrType
= N0
.getOperand(1).getValueType();
10397 uint64_t PtrOff
= ShAmt
/ 8;
10398 unsigned NewAlign
= MinAlign(LN0
->getAlignment(), PtrOff
);
10400 // The original load itself didn't wrap, so an offset within it doesn't.
10402 Flags
.setNoUnsignedWrap(true);
10403 SDValue NewPtr
= DAG
.getNode(ISD::ADD
, DL
,
10404 PtrType
, LN0
->getBasePtr(),
10405 DAG
.getConstant(PtrOff
, DL
, PtrType
),
10407 AddToWorklist(NewPtr
.getNode());
10410 if (ExtType
== ISD::NON_EXTLOAD
)
10411 Load
= DAG
.getLoad(VT
, DL
, LN0
->getChain(), NewPtr
,
10412 LN0
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
,
10413 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
10415 Load
= DAG
.getExtLoad(ExtType
, DL
, VT
, LN0
->getChain(), NewPtr
,
10416 LN0
->getPointerInfo().getWithOffset(PtrOff
), ExtVT
,
10417 NewAlign
, LN0
->getMemOperand()->getFlags(),
10420 // Replace the old load's chain with the new load's chain.
10421 WorklistRemover
DeadNodes(*this);
10422 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), Load
.getValue(1));
10424 // Shift the result left, if we've swallowed a left shift.
10425 SDValue Result
= Load
;
10426 if (ShLeftAmt
!= 0) {
10427 EVT ShImmTy
= getShiftAmountTy(Result
.getValueType());
10428 if (!isUIntN(ShImmTy
.getSizeInBits(), ShLeftAmt
))
10430 // If the shift amount is as large as the result size (but, presumably,
10431 // no larger than the source) then the useful bits of the result are
10432 // zero; we can't simply return the shortened shift, because the result
10433 // of that operation is undefined.
10434 if (ShLeftAmt
>= VT
.getSizeInBits())
10435 Result
= DAG
.getConstant(0, DL
, VT
);
10437 Result
= DAG
.getNode(ISD::SHL
, DL
, VT
,
10438 Result
, DAG
.getConstant(ShLeftAmt
, DL
, ShImmTy
));
10441 if (HasShiftedOffset
) {
10442 // Recalculate the shift amount after it has been altered to calculate
10444 if (DAG
.getDataLayout().isBigEndian())
10445 ShAmt
= AdjustBigEndianShift(ShAmt
);
10447 // We're using a shifted mask, so the load now has an offset. This means
10448 // that data has been loaded into the lower bytes than it would have been
10449 // before, so we need to shl the loaded data into the correct position in the
10451 SDValue ShiftC
= DAG
.getConstant(ShAmt
, DL
, VT
);
10452 Result
= DAG
.getNode(ISD::SHL
, DL
, VT
, Result
, ShiftC
);
10453 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
);
10456 // Return the new loaded value.
10460 SDValue
DAGCombiner::visitSIGN_EXTEND_INREG(SDNode
*N
) {
10461 SDValue N0
= N
->getOperand(0);
10462 SDValue N1
= N
->getOperand(1);
10463 EVT VT
= N
->getValueType(0);
10464 EVT EVT
= cast
<VTSDNode
>(N1
)->getVT();
10465 unsigned VTBits
= VT
.getScalarSizeInBits();
10466 unsigned EVTBits
= EVT
.getScalarSizeInBits();
10469 return DAG
.getUNDEF(VT
);
10471 // fold (sext_in_reg c1) -> c1
10472 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
10473 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
, N0
, N1
);
10475 // If the input is already sign extended, just drop the extension.
10476 if (DAG
.ComputeNumSignBits(N0
) >= VTBits
-EVTBits
+1)
10479 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
10480 if (N0
.getOpcode() == ISD::SIGN_EXTEND_INREG
&&
10481 EVT
.bitsLT(cast
<VTSDNode
>(N0
.getOperand(1))->getVT()))
10482 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
10483 N0
.getOperand(0), N1
);
10485 // fold (sext_in_reg (sext x)) -> (sext x)
10486 // fold (sext_in_reg (aext x)) -> (sext x)
10487 // if x is small enough or if we know that x has more than 1 sign bit and the
10488 // sign_extend_inreg is extending from one of them.
10489 if (N0
.getOpcode() == ISD::SIGN_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
) {
10490 SDValue N00
= N0
.getOperand(0);
10491 unsigned N00Bits
= N00
.getScalarValueSizeInBits();
10492 if ((N00Bits
<= EVTBits
||
10493 (N00Bits
- DAG
.ComputeNumSignBits(N00
)) < EVTBits
) &&
10494 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND
, VT
)))
10495 return DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, N00
);
10498 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
10499 if ((N0
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
||
10500 N0
.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG
||
10501 N0
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
) &&
10502 N0
.getOperand(0).getScalarValueSizeInBits() == EVTBits
) {
10503 if (!LegalOperations
||
10504 TLI
.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG
, VT
))
10505 return DAG
.getNode(ISD::SIGN_EXTEND_VECTOR_INREG
, SDLoc(N
), VT
,
10509 // fold (sext_in_reg (zext x)) -> (sext x)
10510 // iff we are extending the source sign bit.
10511 if (N0
.getOpcode() == ISD::ZERO_EXTEND
) {
10512 SDValue N00
= N0
.getOperand(0);
10513 if (N00
.getScalarValueSizeInBits() == EVTBits
&&
10514 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND
, VT
)))
10515 return DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, N00
, N1
);
10518 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
10519 if (DAG
.MaskedValueIsZero(N0
, APInt::getOneBitSet(VTBits
, EVTBits
- 1)))
10520 return DAG
.getZeroExtendInReg(N0
, SDLoc(N
), EVT
.getScalarType());
10522 // fold operands of sext_in_reg based on knowledge that the top bits are not
10524 if (SimplifyDemandedBits(SDValue(N
, 0)))
10525 return SDValue(N
, 0);
10527 // fold (sext_in_reg (load x)) -> (smaller sextload x)
10528 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
10529 if (SDValue NarrowLoad
= ReduceLoadWidth(N
))
10532 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
10533 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
10534 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
10535 if (N0
.getOpcode() == ISD::SRL
) {
10536 if (auto *ShAmt
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1)))
10537 if (ShAmt
->getAPIntValue().ule(VTBits
- EVTBits
)) {
10538 // We can turn this into an SRA iff the input to the SRL is already sign
10539 // extended enough.
10540 unsigned InSignBits
= DAG
.ComputeNumSignBits(N0
.getOperand(0));
10541 if (((VTBits
- EVTBits
) - ShAmt
->getZExtValue()) < InSignBits
)
10542 return DAG
.getNode(ISD::SRA
, SDLoc(N
), VT
, N0
.getOperand(0),
10547 // fold (sext_inreg (extload x)) -> (sextload x)
10548 // If sextload is not supported by target, we can only do the combine when
10549 // load has one use. Doing otherwise can block folding the extload with other
10550 // extends that the target does support.
10551 if (ISD::isEXTLoad(N0
.getNode()) &&
10552 ISD::isUNINDEXEDLoad(N0
.getNode()) &&
10553 EVT
== cast
<LoadSDNode
>(N0
)->getMemoryVT() &&
10554 ((!LegalOperations
&& cast
<LoadSDNode
>(N0
)->isSimple() &&
10556 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, EVT
))) {
10557 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10558 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(N
), VT
,
10560 LN0
->getBasePtr(), EVT
,
10561 LN0
->getMemOperand());
10562 CombineTo(N
, ExtLoad
);
10563 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
10564 AddToWorklist(ExtLoad
.getNode());
10565 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10567 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
10568 if (ISD::isZEXTLoad(N0
.getNode()) && ISD::isUNINDEXEDLoad(N0
.getNode()) &&
10570 EVT
== cast
<LoadSDNode
>(N0
)->getMemoryVT() &&
10571 ((!LegalOperations
&& cast
<LoadSDNode
>(N0
)->isSimple()) &&
10572 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, EVT
))) {
10573 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10574 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(N
), VT
,
10576 LN0
->getBasePtr(), EVT
,
10577 LN0
->getMemOperand());
10578 CombineTo(N
, ExtLoad
);
10579 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
10580 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10583 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
10584 if (EVTBits
<= 16 && N0
.getOpcode() == ISD::OR
) {
10585 if (SDValue BSwap
= MatchBSwapHWordLow(N0
.getNode(), N0
.getOperand(0),
10586 N0
.getOperand(1), false))
10587 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
10594 SDValue
DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode
*N
) {
10595 SDValue N0
= N
->getOperand(0);
10596 EVT VT
= N
->getValueType(0);
10599 return DAG
.getUNDEF(VT
);
10601 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
10604 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
10605 return SDValue(N
, 0);
10610 SDValue
DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode
*N
) {
10611 SDValue N0
= N
->getOperand(0);
10612 EVT VT
= N
->getValueType(0);
10615 return DAG
.getUNDEF(VT
);
10617 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
10620 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
10621 return SDValue(N
, 0);
10626 SDValue
DAGCombiner::visitTRUNCATE(SDNode
*N
) {
10627 SDValue N0
= N
->getOperand(0);
10628 EVT VT
= N
->getValueType(0);
10629 EVT SrcVT
= N0
.getValueType();
10630 bool isLE
= DAG
.getDataLayout().isLittleEndian();
10636 // fold (truncate (truncate x)) -> (truncate x)
10637 if (N0
.getOpcode() == ISD::TRUNCATE
)
10638 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
.getOperand(0));
10640 // fold (truncate c1) -> c1
10641 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
10642 SDValue C
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
);
10643 if (C
.getNode() != N
)
10647 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
10648 if (N0
.getOpcode() == ISD::ZERO_EXTEND
||
10649 N0
.getOpcode() == ISD::SIGN_EXTEND
||
10650 N0
.getOpcode() == ISD::ANY_EXTEND
) {
10651 // if the source is smaller than the dest, we still need an extend.
10652 if (N0
.getOperand(0).getValueType().bitsLT(VT
))
10653 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, N0
.getOperand(0));
10654 // if the source is larger than the dest, than we just need the truncate.
10655 if (N0
.getOperand(0).getValueType().bitsGT(VT
))
10656 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
.getOperand(0));
10657 // if the source and dest are the same type, we can drop both the extend
10658 // and the truncate.
10659 return N0
.getOperand(0);
10662 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
10663 if (N
->hasOneUse() && (N
->use_begin()->getOpcode() == ISD::ANY_EXTEND
))
10666 // Fold extract-and-trunc into a narrow extract. For example:
10667 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
10668 // i32 y = TRUNCATE(i64 x)
10670 // v16i8 b = BITCAST (v2i64 val)
10671 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
10673 // Note: We only run this optimization after type legalization (which often
10674 // creates this pattern) and before operation legalization after which
10675 // we need to be more careful about the vector instructions that we generate.
10676 if (N0
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
10677 LegalTypes
&& !LegalOperations
&& N0
->hasOneUse() && VT
!= MVT::i1
) {
10678 EVT VecTy
= N0
.getOperand(0).getValueType();
10679 EVT ExTy
= N0
.getValueType();
10680 EVT TrTy
= N
->getValueType(0);
10682 unsigned NumElem
= VecTy
.getVectorNumElements();
10683 unsigned SizeRatio
= ExTy
.getSizeInBits()/TrTy
.getSizeInBits();
10685 EVT NVT
= EVT::getVectorVT(*DAG
.getContext(), TrTy
, SizeRatio
* NumElem
);
10686 assert(NVT
.getSizeInBits() == VecTy
.getSizeInBits() && "Invalid Size");
10688 SDValue EltNo
= N0
->getOperand(1);
10689 if (isa
<ConstantSDNode
>(EltNo
) && isTypeLegal(NVT
)) {
10690 int Elt
= cast
<ConstantSDNode
>(EltNo
)->getZExtValue();
10691 EVT IndexTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
10692 int Index
= isLE
? (Elt
*SizeRatio
) : (Elt
*SizeRatio
+ (SizeRatio
-1));
10695 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, TrTy
,
10696 DAG
.getBitcast(NVT
, N0
.getOperand(0)),
10697 DAG
.getConstant(Index
, DL
, IndexTy
));
10701 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
10702 if (N0
.getOpcode() == ISD::SELECT
&& N0
.hasOneUse()) {
10703 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::SELECT
, SrcVT
)) &&
10704 TLI
.isTruncateFree(SrcVT
, VT
)) {
10706 SDValue Cond
= N0
.getOperand(0);
10707 SDValue TruncOp0
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(1));
10708 SDValue TruncOp1
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(2));
10709 return DAG
.getNode(ISD::SELECT
, SDLoc(N
), VT
, Cond
, TruncOp0
, TruncOp1
);
10713 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
10714 if (N0
.getOpcode() == ISD::SHL
&& N0
.hasOneUse() &&
10715 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SHL
, VT
)) &&
10716 TLI
.isTypeDesirableForOp(ISD::SHL
, VT
)) {
10717 SDValue Amt
= N0
.getOperand(1);
10718 KnownBits Known
= DAG
.computeKnownBits(Amt
);
10719 unsigned Size
= VT
.getScalarSizeInBits();
10720 if (Known
.getBitWidth() - Known
.countMinLeadingZeros() <= Log2_32(Size
)) {
10722 EVT AmtVT
= TLI
.getShiftAmountTy(VT
, DAG
.getDataLayout());
10724 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(0));
10725 if (AmtVT
!= Amt
.getValueType()) {
10726 Amt
= DAG
.getZExtOrTrunc(Amt
, SL
, AmtVT
);
10727 AddToWorklist(Amt
.getNode());
10729 return DAG
.getNode(ISD::SHL
, SL
, VT
, Trunc
, Amt
);
10733 // Attempt to pre-truncate BUILD_VECTOR sources.
10734 if (N0
.getOpcode() == ISD::BUILD_VECTOR
&& !LegalOperations
&&
10735 TLI
.isTruncateFree(SrcVT
.getScalarType(), VT
.getScalarType())) {
10737 EVT SVT
= VT
.getScalarType();
10738 SmallVector
<SDValue
, 8> TruncOps
;
10739 for (const SDValue
&Op
: N0
->op_values()) {
10740 SDValue TruncOp
= DAG
.getNode(ISD::TRUNCATE
, DL
, SVT
, Op
);
10741 TruncOps
.push_back(TruncOp
);
10743 return DAG
.getBuildVector(VT
, DL
, TruncOps
);
10746 // Fold a series of buildvector, bitcast, and truncate if possible.
10747 // For example fold
10748 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
10749 // (2xi32 (buildvector x, y)).
10750 if (Level
== AfterLegalizeVectorOps
&& VT
.isVector() &&
10751 N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse() &&
10752 N0
.getOperand(0).getOpcode() == ISD::BUILD_VECTOR
&&
10753 N0
.getOperand(0).hasOneUse()) {
10754 SDValue BuildVect
= N0
.getOperand(0);
10755 EVT BuildVectEltTy
= BuildVect
.getValueType().getVectorElementType();
10756 EVT TruncVecEltTy
= VT
.getVectorElementType();
10758 // Check that the element types match.
10759 if (BuildVectEltTy
== TruncVecEltTy
) {
10760 // Now we only need to compute the offset of the truncated elements.
10761 unsigned BuildVecNumElts
= BuildVect
.getNumOperands();
10762 unsigned TruncVecNumElts
= VT
.getVectorNumElements();
10763 unsigned TruncEltOffset
= BuildVecNumElts
/ TruncVecNumElts
;
10765 assert((BuildVecNumElts
% TruncVecNumElts
) == 0 &&
10766 "Invalid number of elements");
10768 SmallVector
<SDValue
, 8> Opnds
;
10769 for (unsigned i
= 0, e
= BuildVecNumElts
; i
!= e
; i
+= TruncEltOffset
)
10770 Opnds
.push_back(BuildVect
.getOperand(i
));
10772 return DAG
.getBuildVector(VT
, SDLoc(N
), Opnds
);
10776 // See if we can simplify the input to this truncate through knowledge that
10777 // only the low bits are being used.
10778 // For example "trunc (or (shl x, 8), y)" // -> trunc y
10779 // Currently we only perform this optimization on scalars because vectors
10780 // may have different active low bits.
10781 if (!VT
.isVector()) {
10783 APInt::getLowBitsSet(N0
.getValueSizeInBits(), VT
.getSizeInBits());
10784 if (SDValue Shorter
= DAG
.GetDemandedBits(N0
, Mask
))
10785 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, Shorter
);
10788 // fold (truncate (load x)) -> (smaller load x)
10789 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
10790 if (!LegalTypes
|| TLI
.isTypeDesirableForOp(N0
.getOpcode(), VT
)) {
10791 if (SDValue Reduced
= ReduceLoadWidth(N
))
10794 // Handle the case where the load remains an extending load even
10795 // after truncation.
10796 if (N0
.hasOneUse() && ISD::isUNINDEXEDLoad(N0
.getNode())) {
10797 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10798 if (LN0
->isSimple() &&
10799 LN0
->getMemoryVT().getStoreSizeInBits() < VT
.getSizeInBits()) {
10800 SDValue NewLoad
= DAG
.getExtLoad(LN0
->getExtensionType(), SDLoc(LN0
),
10801 VT
, LN0
->getChain(), LN0
->getBasePtr(),
10802 LN0
->getMemoryVT(),
10803 LN0
->getMemOperand());
10804 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), NewLoad
.getValue(1));
10810 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
10811 // where ... are all 'undef'.
10812 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&& !LegalTypes
) {
10813 SmallVector
<EVT
, 8> VTs
;
10816 unsigned NumDefs
= 0;
10818 for (unsigned i
= 0, e
= N0
.getNumOperands(); i
!= e
; ++i
) {
10819 SDValue X
= N0
.getOperand(i
);
10820 if (!X
.isUndef()) {
10825 // Stop if more than one members are non-undef.
10828 VTs
.push_back(EVT::getVectorVT(*DAG
.getContext(),
10829 VT
.getVectorElementType(),
10830 X
.getValueType().getVectorNumElements()));
10834 return DAG
.getUNDEF(VT
);
10836 if (NumDefs
== 1) {
10837 assert(V
.getNode() && "The single defined operand is empty!");
10838 SmallVector
<SDValue
, 8> Opnds
;
10839 for (unsigned i
= 0, e
= VTs
.size(); i
!= e
; ++i
) {
10841 Opnds
.push_back(DAG
.getUNDEF(VTs
[i
]));
10844 SDValue NV
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(V
), VTs
[i
], V
);
10845 AddToWorklist(NV
.getNode());
10846 Opnds
.push_back(NV
);
10848 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Opnds
);
10852 // Fold truncate of a bitcast of a vector to an extract of the low vector
10855 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
10856 if (N0
.getOpcode() == ISD::BITCAST
&& !VT
.isVector()) {
10857 SDValue VecSrc
= N0
.getOperand(0);
10858 EVT SrcVT
= VecSrc
.getValueType();
10859 if (SrcVT
.isVector() && SrcVT
.getScalarType() == VT
&&
10860 (!LegalOperations
||
10861 TLI
.isOperationLegal(ISD::EXTRACT_VECTOR_ELT
, SrcVT
))) {
10864 EVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
10865 unsigned Idx
= isLE
? 0 : SrcVT
.getVectorNumElements() - 1;
10866 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, VT
,
10867 VecSrc
, DAG
.getConstant(Idx
, SL
, IdxVT
));
10871 // Simplify the operands using demanded-bits information.
10872 if (!VT
.isVector() &&
10873 SimplifyDemandedBits(SDValue(N
, 0)))
10874 return SDValue(N
, 0);
10876 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
10877 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
10878 // When the adde's carry is not used.
10879 if ((N0
.getOpcode() == ISD::ADDE
|| N0
.getOpcode() == ISD::ADDCARRY
) &&
10880 N0
.hasOneUse() && !N0
.getNode()->hasAnyUseOfValue(1) &&
10881 // We only do for addcarry before legalize operation
10882 ((!LegalOperations
&& N0
.getOpcode() == ISD::ADDCARRY
) ||
10883 TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
10885 auto X
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(0));
10886 auto Y
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(1));
10887 auto VTs
= DAG
.getVTList(VT
, N0
->getValueType(1));
10888 return DAG
.getNode(N0
.getOpcode(), SL
, VTs
, X
, Y
, N0
.getOperand(2));
10891 // fold (truncate (extract_subvector(ext x))) ->
10892 // (extract_subvector x)
10893 // TODO: This can be generalized to cover cases where the truncate and extract
10894 // do not fully cancel each other out.
10895 if (!LegalTypes
&& N0
.getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
10896 SDValue N00
= N0
.getOperand(0);
10897 if (N00
.getOpcode() == ISD::SIGN_EXTEND
||
10898 N00
.getOpcode() == ISD::ZERO_EXTEND
||
10899 N00
.getOpcode() == ISD::ANY_EXTEND
) {
10900 if (N00
.getOperand(0)->getValueType(0).getVectorElementType() ==
10901 VT
.getVectorElementType())
10902 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N0
->getOperand(0)), VT
,
10903 N00
.getOperand(0), N0
.getOperand(1));
10907 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
10910 // Narrow a suitable binary operation with a non-opaque constant operand by
10911 // moving it ahead of the truncate. This is limited to pre-legalization
10912 // because targets may prefer a wider type during later combines and invert
10914 switch (N0
.getOpcode()) {
10921 if (!LegalOperations
&& N0
.hasOneUse() &&
10922 (isConstantOrConstantVector(N0
.getOperand(0), true) ||
10923 isConstantOrConstantVector(N0
.getOperand(1), true))) {
10924 // TODO: We already restricted this to pre-legalization, but for vectors
10925 // we are extra cautious to not create an unsupported operation.
10926 // Target-specific changes are likely needed to avoid regressions here.
10927 if (VT
.isScalarInteger() || TLI
.isOperationLegal(N0
.getOpcode(), VT
)) {
10929 SDValue NarrowL
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N0
.getOperand(0));
10930 SDValue NarrowR
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N0
.getOperand(1));
10931 return DAG
.getNode(N0
.getOpcode(), DL
, VT
, NarrowL
, NarrowR
);
10939 static SDNode
*getBuildPairElt(SDNode
*N
, unsigned i
) {
10940 SDValue Elt
= N
->getOperand(i
);
10941 if (Elt
.getOpcode() != ISD::MERGE_VALUES
)
10942 return Elt
.getNode();
10943 return Elt
.getOperand(Elt
.getResNo()).getNode();
10946 /// build_pair (load, load) -> load
10947 /// if load locations are consecutive.
10948 SDValue
DAGCombiner::CombineConsecutiveLoads(SDNode
*N
, EVT VT
) {
10949 assert(N
->getOpcode() == ISD::BUILD_PAIR
);
10951 LoadSDNode
*LD1
= dyn_cast
<LoadSDNode
>(getBuildPairElt(N
, 0));
10952 LoadSDNode
*LD2
= dyn_cast
<LoadSDNode
>(getBuildPairElt(N
, 1));
10954 // A BUILD_PAIR is always having the least significant part in elt 0 and the
10955 // most significant part in elt 1. So when combining into one large load, we
10956 // need to consider the endianness.
10957 if (DAG
.getDataLayout().isBigEndian())
10958 std::swap(LD1
, LD2
);
10960 if (!LD1
|| !LD2
|| !ISD::isNON_EXTLoad(LD1
) || !LD1
->hasOneUse() ||
10961 LD1
->getAddressSpace() != LD2
->getAddressSpace())
10963 EVT LD1VT
= LD1
->getValueType(0);
10964 unsigned LD1Bytes
= LD1VT
.getStoreSize();
10965 if (ISD::isNON_EXTLoad(LD2
) && LD2
->hasOneUse() &&
10966 DAG
.areNonVolatileConsecutiveLoads(LD2
, LD1
, LD1Bytes
, 1)) {
10967 unsigned Align
= LD1
->getAlignment();
10968 unsigned NewAlign
= DAG
.getDataLayout().getABITypeAlignment(
10969 VT
.getTypeForEVT(*DAG
.getContext()));
10971 if (NewAlign
<= Align
&&
10972 (!LegalOperations
|| TLI
.isOperationLegal(ISD::LOAD
, VT
)))
10973 return DAG
.getLoad(VT
, SDLoc(N
), LD1
->getChain(), LD1
->getBasePtr(),
10974 LD1
->getPointerInfo(), Align
);
10980 static unsigned getPPCf128HiElementSelector(const SelectionDAG
&DAG
) {
10981 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
10982 // and Lo parts; on big-endian machines it doesn't.
10983 return DAG
.getDataLayout().isBigEndian() ? 1 : 0;
10986 static SDValue
foldBitcastedFPLogic(SDNode
*N
, SelectionDAG
&DAG
,
10987 const TargetLowering
&TLI
) {
10988 // If this is not a bitcast to an FP type or if the target doesn't have
10989 // IEEE754-compliant FP logic, we're done.
10990 EVT VT
= N
->getValueType(0);
10991 if (!VT
.isFloatingPoint() || !TLI
.hasBitPreservingFPLogic(VT
))
10994 // TODO: Handle cases where the integer constant is a different scalar
10995 // bitwidth to the FP.
10996 SDValue N0
= N
->getOperand(0);
10997 EVT SourceVT
= N0
.getValueType();
10998 if (VT
.getScalarSizeInBits() != SourceVT
.getScalarSizeInBits())
11003 switch (N0
.getOpcode()) {
11005 FPOpcode
= ISD::FABS
;
11006 SignMask
= ~APInt::getSignMask(SourceVT
.getScalarSizeInBits());
11009 FPOpcode
= ISD::FNEG
;
11010 SignMask
= APInt::getSignMask(SourceVT
.getScalarSizeInBits());
11013 FPOpcode
= ISD::FABS
;
11014 SignMask
= APInt::getSignMask(SourceVT
.getScalarSizeInBits());
11020 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
11021 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
11022 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
11024 SDValue LogicOp0
= N0
.getOperand(0);
11025 ConstantSDNode
*LogicOp1
= isConstOrConstSplat(N0
.getOperand(1), true);
11026 if (LogicOp1
&& LogicOp1
->getAPIntValue() == SignMask
&&
11027 LogicOp0
.getOpcode() == ISD::BITCAST
&&
11028 LogicOp0
.getOperand(0).getValueType() == VT
) {
11029 SDValue FPOp
= DAG
.getNode(FPOpcode
, SDLoc(N
), VT
, LogicOp0
.getOperand(0));
11030 NumFPLogicOpsConv
++;
11031 if (N0
.getOpcode() == ISD::OR
)
11032 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, FPOp
);
11039 SDValue
DAGCombiner::visitBITCAST(SDNode
*N
) {
11040 SDValue N0
= N
->getOperand(0);
11041 EVT VT
= N
->getValueType(0);
11044 return DAG
.getUNDEF(VT
);
11046 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
11047 // Only do this before legalize types, unless both types are integer and the
11048 // scalar type is legal. Only do this before legalize ops, since the target
11049 // maybe depending on the bitcast.
11050 // First check to see if this is all constant.
11051 // TODO: Support FP bitcasts after legalize types.
11052 if (VT
.isVector() &&
11054 (!LegalOperations
&& VT
.isInteger() && N0
.getValueType().isInteger() &&
11055 TLI
.isTypeLegal(VT
.getVectorElementType()))) &&
11056 N0
.getOpcode() == ISD::BUILD_VECTOR
&& N0
.getNode()->hasOneUse() &&
11057 cast
<BuildVectorSDNode
>(N0
)->isConstant())
11058 return ConstantFoldBITCASTofBUILD_VECTOR(N0
.getNode(),
11059 VT
.getVectorElementType());
11061 // If the input is a constant, let getNode fold it.
11062 if (isa
<ConstantSDNode
>(N0
) || isa
<ConstantFPSDNode
>(N0
)) {
11063 // If we can't allow illegal operations, we need to check that this is just
11064 // a fp -> int or int -> conversion and that the resulting operation will
11066 if (!LegalOperations
||
11067 (isa
<ConstantSDNode
>(N0
) && VT
.isFloatingPoint() && !VT
.isVector() &&
11068 TLI
.isOperationLegal(ISD::ConstantFP
, VT
)) ||
11069 (isa
<ConstantFPSDNode
>(N0
) && VT
.isInteger() && !VT
.isVector() &&
11070 TLI
.isOperationLegal(ISD::Constant
, VT
))) {
11071 SDValue C
= DAG
.getBitcast(VT
, N0
);
11072 if (C
.getNode() != N
)
11077 // (conv (conv x, t1), t2) -> (conv x, t2)
11078 if (N0
.getOpcode() == ISD::BITCAST
)
11079 return DAG
.getBitcast(VT
, N0
.getOperand(0));
11081 // fold (conv (load x)) -> (load (conv*)x)
11082 // If the resultant load doesn't need a higher alignment than the original!
11083 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
11084 // Do not remove the cast if the types differ in endian layout.
11085 TLI
.hasBigEndianPartOrdering(N0
.getValueType(), DAG
.getDataLayout()) ==
11086 TLI
.hasBigEndianPartOrdering(VT
, DAG
.getDataLayout()) &&
11087 // If the load is volatile, we only want to change the load type if the
11088 // resulting load is legal. Otherwise we might increase the number of
11089 // memory accesses. We don't care if the original type was legal or not
11090 // as we assume software couldn't rely on the number of accesses of an
11092 ((!LegalOperations
&& cast
<LoadSDNode
>(N0
)->isSimple()) ||
11093 TLI
.isOperationLegal(ISD::LOAD
, VT
))) {
11094 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
11096 if (TLI
.isLoadBitCastBeneficial(N0
.getValueType(), VT
, DAG
,
11097 *LN0
->getMemOperand())) {
11099 DAG
.getLoad(VT
, SDLoc(N
), LN0
->getChain(), LN0
->getBasePtr(),
11100 LN0
->getPointerInfo(), LN0
->getAlignment(),
11101 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
11102 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), Load
.getValue(1));
11107 if (SDValue V
= foldBitcastedFPLogic(N
, DAG
, TLI
))
11110 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
11111 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
11114 // fold (bitcast (fneg x)) ->
11115 // flipbit = signbit
11116 // (xor (bitcast x) (build_pair flipbit, flipbit))
11118 // fold (bitcast (fabs x)) ->
11119 // flipbit = (and (extract_element (bitcast x), 0), signbit)
11120 // (xor (bitcast x) (build_pair flipbit, flipbit))
11121 // This often reduces constant pool loads.
11122 if (((N0
.getOpcode() == ISD::FNEG
&& !TLI
.isFNegFree(N0
.getValueType())) ||
11123 (N0
.getOpcode() == ISD::FABS
&& !TLI
.isFAbsFree(N0
.getValueType()))) &&
11124 N0
.getNode()->hasOneUse() && VT
.isInteger() &&
11125 !VT
.isVector() && !N0
.getValueType().isVector()) {
11126 SDValue NewConv
= DAG
.getBitcast(VT
, N0
.getOperand(0));
11127 AddToWorklist(NewConv
.getNode());
11130 if (N0
.getValueType() == MVT::ppcf128
&& !LegalTypes
) {
11131 assert(VT
.getSizeInBits() == 128);
11132 SDValue SignBit
= DAG
.getConstant(
11133 APInt::getSignMask(VT
.getSizeInBits() / 2), SDLoc(N0
), MVT::i64
);
11135 if (N0
.getOpcode() == ISD::FNEG
) {
11137 AddToWorklist(FlipBit
.getNode());
11139 assert(N0
.getOpcode() == ISD::FABS
);
11141 DAG
.getNode(ISD::EXTRACT_ELEMENT
, SDLoc(NewConv
), MVT::i64
, NewConv
,
11142 DAG
.getIntPtrConstant(getPPCf128HiElementSelector(DAG
),
11144 AddToWorklist(Hi
.getNode());
11145 FlipBit
= DAG
.getNode(ISD::AND
, SDLoc(N0
), MVT::i64
, Hi
, SignBit
);
11146 AddToWorklist(FlipBit
.getNode());
11149 DAG
.getNode(ISD::BUILD_PAIR
, SDLoc(N0
), VT
, FlipBit
, FlipBit
);
11150 AddToWorklist(FlipBits
.getNode());
11151 return DAG
.getNode(ISD::XOR
, DL
, VT
, NewConv
, FlipBits
);
11153 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits());
11154 if (N0
.getOpcode() == ISD::FNEG
)
11155 return DAG
.getNode(ISD::XOR
, DL
, VT
,
11156 NewConv
, DAG
.getConstant(SignBit
, DL
, VT
));
11157 assert(N0
.getOpcode() == ISD::FABS
);
11158 return DAG
.getNode(ISD::AND
, DL
, VT
,
11159 NewConv
, DAG
.getConstant(~SignBit
, DL
, VT
));
11162 // fold (bitconvert (fcopysign cst, x)) ->
11163 // (or (and (bitconvert x), sign), (and cst, (not sign)))
11164 // Note that we don't handle (copysign x, cst) because this can always be
11165 // folded to an fneg or fabs.
11168 // fold (bitcast (fcopysign cst, x)) ->
11169 // flipbit = (and (extract_element
11170 // (xor (bitcast cst), (bitcast x)), 0),
11172 // (xor (bitcast cst) (build_pair flipbit, flipbit))
11173 if (N0
.getOpcode() == ISD::FCOPYSIGN
&& N0
.getNode()->hasOneUse() &&
11174 isa
<ConstantFPSDNode
>(N0
.getOperand(0)) &&
11175 VT
.isInteger() && !VT
.isVector()) {
11176 unsigned OrigXWidth
= N0
.getOperand(1).getValueSizeInBits();
11177 EVT IntXVT
= EVT::getIntegerVT(*DAG
.getContext(), OrigXWidth
);
11178 if (isTypeLegal(IntXVT
)) {
11179 SDValue X
= DAG
.getBitcast(IntXVT
, N0
.getOperand(1));
11180 AddToWorklist(X
.getNode());
11182 // If X has a different width than the result/lhs, sext it or truncate it.
11183 unsigned VTWidth
= VT
.getSizeInBits();
11184 if (OrigXWidth
< VTWidth
) {
11185 X
= DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, X
);
11186 AddToWorklist(X
.getNode());
11187 } else if (OrigXWidth
> VTWidth
) {
11188 // To get the sign bit in the right place, we have to shift it right
11189 // before truncating.
11191 X
= DAG
.getNode(ISD::SRL
, DL
,
11192 X
.getValueType(), X
,
11193 DAG
.getConstant(OrigXWidth
-VTWidth
, DL
,
11194 X
.getValueType()));
11195 AddToWorklist(X
.getNode());
11196 X
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(X
), VT
, X
);
11197 AddToWorklist(X
.getNode());
11200 if (N0
.getValueType() == MVT::ppcf128
&& !LegalTypes
) {
11201 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits() / 2);
11202 SDValue Cst
= DAG
.getBitcast(VT
, N0
.getOperand(0));
11203 AddToWorklist(Cst
.getNode());
11204 SDValue X
= DAG
.getBitcast(VT
, N0
.getOperand(1));
11205 AddToWorklist(X
.getNode());
11206 SDValue XorResult
= DAG
.getNode(ISD::XOR
, SDLoc(N0
), VT
, Cst
, X
);
11207 AddToWorklist(XorResult
.getNode());
11208 SDValue XorResult64
= DAG
.getNode(
11209 ISD::EXTRACT_ELEMENT
, SDLoc(XorResult
), MVT::i64
, XorResult
,
11210 DAG
.getIntPtrConstant(getPPCf128HiElementSelector(DAG
),
11211 SDLoc(XorResult
)));
11212 AddToWorklist(XorResult64
.getNode());
11214 DAG
.getNode(ISD::AND
, SDLoc(XorResult64
), MVT::i64
, XorResult64
,
11215 DAG
.getConstant(SignBit
, SDLoc(XorResult64
), MVT::i64
));
11216 AddToWorklist(FlipBit
.getNode());
11218 DAG
.getNode(ISD::BUILD_PAIR
, SDLoc(N0
), VT
, FlipBit
, FlipBit
);
11219 AddToWorklist(FlipBits
.getNode());
11220 return DAG
.getNode(ISD::XOR
, SDLoc(N
), VT
, Cst
, FlipBits
);
11222 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits());
11223 X
= DAG
.getNode(ISD::AND
, SDLoc(X
), VT
,
11224 X
, DAG
.getConstant(SignBit
, SDLoc(X
), VT
));
11225 AddToWorklist(X
.getNode());
11227 SDValue Cst
= DAG
.getBitcast(VT
, N0
.getOperand(0));
11228 Cst
= DAG
.getNode(ISD::AND
, SDLoc(Cst
), VT
,
11229 Cst
, DAG
.getConstant(~SignBit
, SDLoc(Cst
), VT
));
11230 AddToWorklist(Cst
.getNode());
11232 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, X
, Cst
);
11236 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
11237 if (N0
.getOpcode() == ISD::BUILD_PAIR
)
11238 if (SDValue CombineLD
= CombineConsecutiveLoads(N0
.getNode(), VT
))
11241 // Remove double bitcasts from shuffles - this is often a legacy of
11242 // XformToShuffleWithZero being used to combine bitmaskings (of
11243 // float vectors bitcast to integer vectors) into shuffles.
11244 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
11245 if (Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
) && VT
.isVector() &&
11246 N0
->getOpcode() == ISD::VECTOR_SHUFFLE
&& N0
.hasOneUse() &&
11247 VT
.getVectorNumElements() >= N0
.getValueType().getVectorNumElements() &&
11248 !(VT
.getVectorNumElements() % N0
.getValueType().getVectorNumElements())) {
11249 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N0
);
11251 // If operands are a bitcast, peek through if it casts the original VT.
11252 // If operands are a constant, just bitcast back to original VT.
11253 auto PeekThroughBitcast
= [&](SDValue Op
) {
11254 if (Op
.getOpcode() == ISD::BITCAST
&&
11255 Op
.getOperand(0).getValueType() == VT
)
11256 return SDValue(Op
.getOperand(0));
11257 if (Op
.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op
.getNode()) ||
11258 ISD::isBuildVectorOfConstantFPSDNodes(Op
.getNode()))
11259 return DAG
.getBitcast(VT
, Op
);
11263 // FIXME: If either input vector is bitcast, try to convert the shuffle to
11264 // the result type of this bitcast. This would eliminate at least one
11265 // bitcast. See the transform in InstCombine.
11266 SDValue SV0
= PeekThroughBitcast(N0
->getOperand(0));
11267 SDValue SV1
= PeekThroughBitcast(N0
->getOperand(1));
11272 VT
.getVectorNumElements() / N0
.getValueType().getVectorNumElements();
11273 SmallVector
<int, 8> NewMask
;
11274 for (int M
: SVN
->getMask())
11275 for (int i
= 0; i
!= MaskScale
; ++i
)
11276 NewMask
.push_back(M
< 0 ? -1 : M
* MaskScale
+ i
);
11278 SDValue LegalShuffle
=
11279 TLI
.buildLegalVectorShuffle(VT
, SDLoc(N
), SV0
, SV1
, NewMask
, DAG
);
11281 return LegalShuffle
;
11287 SDValue
DAGCombiner::visitBUILD_PAIR(SDNode
*N
) {
11288 EVT VT
= N
->getValueType(0);
11289 return CombineConsecutiveLoads(N
, VT
);
11292 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
11293 /// operands. DstEltVT indicates the destination element value type.
11294 SDValue
DAGCombiner::
11295 ConstantFoldBITCASTofBUILD_VECTOR(SDNode
*BV
, EVT DstEltVT
) {
11296 EVT SrcEltVT
= BV
->getValueType(0).getVectorElementType();
11298 // If this is already the right type, we're done.
11299 if (SrcEltVT
== DstEltVT
) return SDValue(BV
, 0);
11301 unsigned SrcBitSize
= SrcEltVT
.getSizeInBits();
11302 unsigned DstBitSize
= DstEltVT
.getSizeInBits();
11304 // If this is a conversion of N elements of one type to N elements of another
11305 // type, convert each element. This handles FP<->INT cases.
11306 if (SrcBitSize
== DstBitSize
) {
11307 SmallVector
<SDValue
, 8> Ops
;
11308 for (SDValue Op
: BV
->op_values()) {
11309 // If the vector element type is not legal, the BUILD_VECTOR operands
11310 // are promoted and implicitly truncated. Make that explicit here.
11311 if (Op
.getValueType() != SrcEltVT
)
11312 Op
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(BV
), SrcEltVT
, Op
);
11313 Ops
.push_back(DAG
.getBitcast(DstEltVT
, Op
));
11314 AddToWorklist(Ops
.back().getNode());
11316 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
,
11317 BV
->getValueType(0).getVectorNumElements());
11318 return DAG
.getBuildVector(VT
, SDLoc(BV
), Ops
);
11321 // Otherwise, we're growing or shrinking the elements. To avoid having to
11322 // handle annoying details of growing/shrinking FP values, we convert them to
11324 if (SrcEltVT
.isFloatingPoint()) {
11325 // Convert the input float vector to a int vector where the elements are the
11327 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), SrcEltVT
.getSizeInBits());
11328 BV
= ConstantFoldBITCASTofBUILD_VECTOR(BV
, IntVT
).getNode();
11332 // Now we know the input is an integer vector. If the output is a FP type,
11333 // convert to integer first, then to FP of the right size.
11334 if (DstEltVT
.isFloatingPoint()) {
11335 EVT TmpVT
= EVT::getIntegerVT(*DAG
.getContext(), DstEltVT
.getSizeInBits());
11336 SDNode
*Tmp
= ConstantFoldBITCASTofBUILD_VECTOR(BV
, TmpVT
).getNode();
11338 // Next, convert to FP elements of the same size.
11339 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp
, DstEltVT
);
11344 // Okay, we know the src/dst types are both integers of differing types.
11345 // Handling growing first.
11346 assert(SrcEltVT
.isInteger() && DstEltVT
.isInteger());
11347 if (SrcBitSize
< DstBitSize
) {
11348 unsigned NumInputsPerOutput
= DstBitSize
/SrcBitSize
;
11350 SmallVector
<SDValue
, 8> Ops
;
11351 for (unsigned i
= 0, e
= BV
->getNumOperands(); i
!= e
;
11352 i
+= NumInputsPerOutput
) {
11353 bool isLE
= DAG
.getDataLayout().isLittleEndian();
11354 APInt NewBits
= APInt(DstBitSize
, 0);
11355 bool EltIsUndef
= true;
11356 for (unsigned j
= 0; j
!= NumInputsPerOutput
; ++j
) {
11357 // Shift the previously computed bits over.
11358 NewBits
<<= SrcBitSize
;
11359 SDValue Op
= BV
->getOperand(i
+ (isLE
? (NumInputsPerOutput
-j
-1) : j
));
11360 if (Op
.isUndef()) continue;
11361 EltIsUndef
= false;
11363 NewBits
|= cast
<ConstantSDNode
>(Op
)->getAPIntValue().
11364 zextOrTrunc(SrcBitSize
).zext(DstBitSize
);
11368 Ops
.push_back(DAG
.getUNDEF(DstEltVT
));
11370 Ops
.push_back(DAG
.getConstant(NewBits
, DL
, DstEltVT
));
11373 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
, Ops
.size());
11374 return DAG
.getBuildVector(VT
, DL
, Ops
);
11377 // Finally, this must be the case where we are shrinking elements: each input
11378 // turns into multiple outputs.
11379 unsigned NumOutputsPerInput
= SrcBitSize
/DstBitSize
;
11380 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
,
11381 NumOutputsPerInput
*BV
->getNumOperands());
11382 SmallVector
<SDValue
, 8> Ops
;
11384 for (const SDValue
&Op
: BV
->op_values()) {
11385 if (Op
.isUndef()) {
11386 Ops
.append(NumOutputsPerInput
, DAG
.getUNDEF(DstEltVT
));
11390 APInt OpVal
= cast
<ConstantSDNode
>(Op
)->
11391 getAPIntValue().zextOrTrunc(SrcBitSize
);
11393 for (unsigned j
= 0; j
!= NumOutputsPerInput
; ++j
) {
11394 APInt ThisVal
= OpVal
.trunc(DstBitSize
);
11395 Ops
.push_back(DAG
.getConstant(ThisVal
, DL
, DstEltVT
));
11396 OpVal
.lshrInPlace(DstBitSize
);
11399 // For big endian targets, swap the order of the pieces of each element.
11400 if (DAG
.getDataLayout().isBigEndian())
11401 std::reverse(Ops
.end()-NumOutputsPerInput
, Ops
.end());
11404 return DAG
.getBuildVector(VT
, DL
, Ops
);
11407 static bool isContractable(SDNode
*N
) {
11408 SDNodeFlags F
= N
->getFlags();
11409 return F
.hasAllowContract() || F
.hasAllowReassociation();
11412 /// Try to perform FMA combining on a given FADD node.
11413 SDValue
DAGCombiner::visitFADDForFMACombine(SDNode
*N
) {
11414 SDValue N0
= N
->getOperand(0);
11415 SDValue N1
= N
->getOperand(1);
11416 EVT VT
= N
->getValueType(0);
11419 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11421 // Floating-point multiply-add with intermediate rounding.
11422 bool HasFMAD
= (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11424 // Floating-point multiply-add without intermediate rounding.
11426 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11427 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11429 // No valid opcode, do not combine.
11430 if (!HasFMAD
&& !HasFMA
)
11433 SDNodeFlags Flags
= N
->getFlags();
11434 bool CanFuse
= Options
.UnsafeFPMath
|| isContractable(N
);
11435 bool AllowFusionGlobally
= (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
11436 CanFuse
|| HasFMAD
);
11437 // If the addition is not contractable, do not combine.
11438 if (!AllowFusionGlobally
&& !isContractable(N
))
11441 const SelectionDAGTargetInfo
*STI
= DAG
.getSubtarget().getSelectionDAGInfo();
11442 if (STI
&& STI
->generateFMAsInMachineCombiner(OptLevel
))
11445 // Always prefer FMAD to FMA for precision.
11446 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11447 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11449 // Is the node an FMUL and contractable either due to global flags or
11451 auto isContractableFMUL
= [AllowFusionGlobally
](SDValue N
) {
11452 if (N
.getOpcode() != ISD::FMUL
)
11454 return AllowFusionGlobally
|| isContractable(N
.getNode());
11456 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
11457 // prefer to fold the multiply with fewer uses.
11458 if (Aggressive
&& isContractableFMUL(N0
) && isContractableFMUL(N1
)) {
11459 if (N0
.getNode()->use_size() > N1
.getNode()->use_size())
11463 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
11464 if (isContractableFMUL(N0
) && (Aggressive
|| N0
->hasOneUse())) {
11465 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11466 N0
.getOperand(0), N0
.getOperand(1), N1
, Flags
);
11469 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
11470 // Note: Commutes FADD operands.
11471 if (isContractableFMUL(N1
) && (Aggressive
|| N1
->hasOneUse())) {
11472 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11473 N1
.getOperand(0), N1
.getOperand(1), N0
, Flags
);
11476 // Look through FP_EXTEND nodes to do more combining.
11478 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
11479 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11480 SDValue N00
= N0
.getOperand(0);
11481 if (isContractableFMUL(N00
) &&
11482 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11483 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11484 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11485 N00
.getOperand(0)),
11486 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11487 N00
.getOperand(1)), N1
, Flags
);
11491 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
11492 // Note: Commutes FADD operands.
11493 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11494 SDValue N10
= N1
.getOperand(0);
11495 if (isContractableFMUL(N10
) &&
11496 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11497 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11498 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11499 N10
.getOperand(0)),
11500 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11501 N10
.getOperand(1)), N0
, Flags
);
11505 // More folding opportunities when target permits.
11507 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
11509 N0
.getOpcode() == PreferredFusedOpcode
&&
11510 N0
.getOperand(2).getOpcode() == ISD::FMUL
&&
11511 N0
->hasOneUse() && N0
.getOperand(2)->hasOneUse()) {
11512 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11513 N0
.getOperand(0), N0
.getOperand(1),
11514 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11515 N0
.getOperand(2).getOperand(0),
11516 N0
.getOperand(2).getOperand(1),
11517 N1
, Flags
), Flags
);
11520 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
11522 N1
->getOpcode() == PreferredFusedOpcode
&&
11523 N1
.getOperand(2).getOpcode() == ISD::FMUL
&&
11524 N1
->hasOneUse() && N1
.getOperand(2)->hasOneUse()) {
11525 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11526 N1
.getOperand(0), N1
.getOperand(1),
11527 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11528 N1
.getOperand(2).getOperand(0),
11529 N1
.getOperand(2).getOperand(1),
11530 N0
, Flags
), Flags
);
11534 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
11535 // -> (fma x, y, (fma (fpext u), (fpext v), z))
11536 auto FoldFAddFMAFPExtFMul
= [&] (
11537 SDValue X
, SDValue Y
, SDValue U
, SDValue V
, SDValue Z
,
11538 SDNodeFlags Flags
) {
11539 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
, Y
,
11540 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11541 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, U
),
11542 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, V
),
11545 if (N0
.getOpcode() == PreferredFusedOpcode
) {
11546 SDValue N02
= N0
.getOperand(2);
11547 if (N02
.getOpcode() == ISD::FP_EXTEND
) {
11548 SDValue N020
= N02
.getOperand(0);
11549 if (isContractableFMUL(N020
) &&
11550 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N020
.getValueType())) {
11551 return FoldFAddFMAFPExtFMul(N0
.getOperand(0), N0
.getOperand(1),
11552 N020
.getOperand(0), N020
.getOperand(1),
11558 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
11559 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
11560 // FIXME: This turns two single-precision and one double-precision
11561 // operation into two double-precision operations, which might not be
11562 // interesting for all targets, especially GPUs.
11563 auto FoldFAddFPExtFMAFMul
= [&] (
11564 SDValue X
, SDValue Y
, SDValue U
, SDValue V
, SDValue Z
,
11565 SDNodeFlags Flags
) {
11566 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11567 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, X
),
11568 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, Y
),
11569 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11570 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, U
),
11571 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, V
),
11574 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11575 SDValue N00
= N0
.getOperand(0);
11576 if (N00
.getOpcode() == PreferredFusedOpcode
) {
11577 SDValue N002
= N00
.getOperand(2);
11578 if (isContractableFMUL(N002
) &&
11579 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11580 return FoldFAddFPExtFMAFMul(N00
.getOperand(0), N00
.getOperand(1),
11581 N002
.getOperand(0), N002
.getOperand(1),
11587 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
11588 // -> (fma y, z, (fma (fpext u), (fpext v), x))
11589 if (N1
.getOpcode() == PreferredFusedOpcode
) {
11590 SDValue N12
= N1
.getOperand(2);
11591 if (N12
.getOpcode() == ISD::FP_EXTEND
) {
11592 SDValue N120
= N12
.getOperand(0);
11593 if (isContractableFMUL(N120
) &&
11594 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N120
.getValueType())) {
11595 return FoldFAddFMAFPExtFMul(N1
.getOperand(0), N1
.getOperand(1),
11596 N120
.getOperand(0), N120
.getOperand(1),
11602 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
11603 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
11604 // FIXME: This turns two single-precision and one double-precision
11605 // operation into two double-precision operations, which might not be
11606 // interesting for all targets, especially GPUs.
11607 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11608 SDValue N10
= N1
.getOperand(0);
11609 if (N10
.getOpcode() == PreferredFusedOpcode
) {
11610 SDValue N102
= N10
.getOperand(2);
11611 if (isContractableFMUL(N102
) &&
11612 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11613 return FoldFAddFPExtFMAFMul(N10
.getOperand(0), N10
.getOperand(1),
11614 N102
.getOperand(0), N102
.getOperand(1),
11624 /// Try to perform FMA combining on a given FSUB node.
11625 SDValue
DAGCombiner::visitFSUBForFMACombine(SDNode
*N
) {
11626 SDValue N0
= N
->getOperand(0);
11627 SDValue N1
= N
->getOperand(1);
11628 EVT VT
= N
->getValueType(0);
11631 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11632 // Floating-point multiply-add with intermediate rounding.
11633 bool HasFMAD
= (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11635 // Floating-point multiply-add without intermediate rounding.
11637 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11638 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11640 // No valid opcode, do not combine.
11641 if (!HasFMAD
&& !HasFMA
)
11644 const SDNodeFlags Flags
= N
->getFlags();
11645 bool CanFuse
= Options
.UnsafeFPMath
|| isContractable(N
);
11646 bool AllowFusionGlobally
= (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
11647 CanFuse
|| HasFMAD
);
11649 // If the subtraction is not contractable, do not combine.
11650 if (!AllowFusionGlobally
&& !isContractable(N
))
11653 const SelectionDAGTargetInfo
*STI
= DAG
.getSubtarget().getSelectionDAGInfo();
11654 if (STI
&& STI
->generateFMAsInMachineCombiner(OptLevel
))
11657 // Always prefer FMAD to FMA for precision.
11658 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11659 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11661 // Is the node an FMUL and contractable either due to global flags or
11663 auto isContractableFMUL
= [AllowFusionGlobally
](SDValue N
) {
11664 if (N
.getOpcode() != ISD::FMUL
)
11666 return AllowFusionGlobally
|| isContractable(N
.getNode());
11669 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
11670 if (isContractableFMUL(N0
) && (Aggressive
|| N0
->hasOneUse())) {
11671 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11672 N0
.getOperand(0), N0
.getOperand(1),
11673 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11676 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
11677 // Note: Commutes FSUB operands.
11678 if (isContractableFMUL(N1
) && (Aggressive
|| N1
->hasOneUse())) {
11679 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11680 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11682 N1
.getOperand(1), N0
, Flags
);
11685 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
11686 if (N0
.getOpcode() == ISD::FNEG
&& isContractableFMUL(N0
.getOperand(0)) &&
11687 (Aggressive
|| (N0
->hasOneUse() && N0
.getOperand(0).hasOneUse()))) {
11688 SDValue N00
= N0
.getOperand(0).getOperand(0);
11689 SDValue N01
= N0
.getOperand(0).getOperand(1);
11690 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11691 DAG
.getNode(ISD::FNEG
, SL
, VT
, N00
), N01
,
11692 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11695 // Look through FP_EXTEND nodes to do more combining.
11697 // fold (fsub (fpext (fmul x, y)), z)
11698 // -> (fma (fpext x), (fpext y), (fneg z))
11699 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11700 SDValue N00
= N0
.getOperand(0);
11701 if (isContractableFMUL(N00
) &&
11702 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11703 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11704 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11705 N00
.getOperand(0)),
11706 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11707 N00
.getOperand(1)),
11708 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11712 // fold (fsub x, (fpext (fmul y, z)))
11713 // -> (fma (fneg (fpext y)), (fpext z), x)
11714 // Note: Commutes FSUB operands.
11715 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11716 SDValue N10
= N1
.getOperand(0);
11717 if (isContractableFMUL(N10
) &&
11718 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11719 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11720 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11721 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11722 N10
.getOperand(0))),
11723 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11724 N10
.getOperand(1)),
11729 // fold (fsub (fpext (fneg (fmul, x, y))), z)
11730 // -> (fneg (fma (fpext x), (fpext y), z))
11731 // Note: This could be removed with appropriate canonicalization of the
11732 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11733 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11734 // from implementing the canonicalization in visitFSUB.
11735 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11736 SDValue N00
= N0
.getOperand(0);
11737 if (N00
.getOpcode() == ISD::FNEG
) {
11738 SDValue N000
= N00
.getOperand(0);
11739 if (isContractableFMUL(N000
) &&
11740 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11741 return DAG
.getNode(ISD::FNEG
, SL
, VT
,
11742 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11743 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11744 N000
.getOperand(0)),
11745 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11746 N000
.getOperand(1)),
11752 // fold (fsub (fneg (fpext (fmul, x, y))), z)
11753 // -> (fneg (fma (fpext x)), (fpext y), z)
11754 // Note: This could be removed with appropriate canonicalization of the
11755 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11756 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11757 // from implementing the canonicalization in visitFSUB.
11758 if (N0
.getOpcode() == ISD::FNEG
) {
11759 SDValue N00
= N0
.getOperand(0);
11760 if (N00
.getOpcode() == ISD::FP_EXTEND
) {
11761 SDValue N000
= N00
.getOperand(0);
11762 if (isContractableFMUL(N000
) &&
11763 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N000
.getValueType())) {
11764 return DAG
.getNode(ISD::FNEG
, SL
, VT
,
11765 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11766 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11767 N000
.getOperand(0)),
11768 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11769 N000
.getOperand(1)),
11775 // More folding opportunities when target permits.
11777 // fold (fsub (fma x, y, (fmul u, v)), z)
11778 // -> (fma x, y (fma u, v, (fneg z)))
11779 if (CanFuse
&& N0
.getOpcode() == PreferredFusedOpcode
&&
11780 isContractableFMUL(N0
.getOperand(2)) && N0
->hasOneUse() &&
11781 N0
.getOperand(2)->hasOneUse()) {
11782 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11783 N0
.getOperand(0), N0
.getOperand(1),
11784 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11785 N0
.getOperand(2).getOperand(0),
11786 N0
.getOperand(2).getOperand(1),
11787 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11788 N1
), Flags
), Flags
);
11791 // fold (fsub x, (fma y, z, (fmul u, v)))
11792 // -> (fma (fneg y), z, (fma (fneg u), v, x))
11793 if (CanFuse
&& N1
.getOpcode() == PreferredFusedOpcode
&&
11794 isContractableFMUL(N1
.getOperand(2))) {
11795 SDValue N20
= N1
.getOperand(2).getOperand(0);
11796 SDValue N21
= N1
.getOperand(2).getOperand(1);
11797 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11798 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11801 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11802 DAG
.getNode(ISD::FNEG
, SL
, VT
, N20
),
11803 N21
, N0
, Flags
), Flags
);
11807 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
11808 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
11809 if (N0
.getOpcode() == PreferredFusedOpcode
) {
11810 SDValue N02
= N0
.getOperand(2);
11811 if (N02
.getOpcode() == ISD::FP_EXTEND
) {
11812 SDValue N020
= N02
.getOperand(0);
11813 if (isContractableFMUL(N020
) &&
11814 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N020
.getValueType())) {
11815 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11816 N0
.getOperand(0), N0
.getOperand(1),
11817 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11818 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11819 N020
.getOperand(0)),
11820 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11821 N020
.getOperand(1)),
11822 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11823 N1
), Flags
), Flags
);
11828 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
11829 // -> (fma (fpext x), (fpext y),
11830 // (fma (fpext u), (fpext v), (fneg z)))
11831 // FIXME: This turns two single-precision and one double-precision
11832 // operation into two double-precision operations, which might not be
11833 // interesting for all targets, especially GPUs.
11834 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11835 SDValue N00
= N0
.getOperand(0);
11836 if (N00
.getOpcode() == PreferredFusedOpcode
) {
11837 SDValue N002
= N00
.getOperand(2);
11838 if (isContractableFMUL(N002
) &&
11839 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11840 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11841 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11842 N00
.getOperand(0)),
11843 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11844 N00
.getOperand(1)),
11845 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11846 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11847 N002
.getOperand(0)),
11848 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11849 N002
.getOperand(1)),
11850 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11851 N1
), Flags
), Flags
);
11856 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
11857 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
11858 if (N1
.getOpcode() == PreferredFusedOpcode
&&
11859 N1
.getOperand(2).getOpcode() == ISD::FP_EXTEND
) {
11860 SDValue N120
= N1
.getOperand(2).getOperand(0);
11861 if (isContractableFMUL(N120
) &&
11862 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N120
.getValueType())) {
11863 SDValue N1200
= N120
.getOperand(0);
11864 SDValue N1201
= N120
.getOperand(1);
11865 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11866 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
.getOperand(0)),
11868 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11869 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11870 DAG
.getNode(ISD::FP_EXTEND
, SL
,
11872 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11874 N0
, Flags
), Flags
);
11878 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
11879 // -> (fma (fneg (fpext y)), (fpext z),
11880 // (fma (fneg (fpext u)), (fpext v), x))
11881 // FIXME: This turns two single-precision and one double-precision
11882 // operation into two double-precision operations, which might not be
11883 // interesting for all targets, especially GPUs.
11884 if (N1
.getOpcode() == ISD::FP_EXTEND
&&
11885 N1
.getOperand(0).getOpcode() == PreferredFusedOpcode
) {
11886 SDValue CvtSrc
= N1
.getOperand(0);
11887 SDValue N100
= CvtSrc
.getOperand(0);
11888 SDValue N101
= CvtSrc
.getOperand(1);
11889 SDValue N102
= CvtSrc
.getOperand(2);
11890 if (isContractableFMUL(N102
) &&
11891 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, CvtSrc
.getValueType())) {
11892 SDValue N1020
= N102
.getOperand(0);
11893 SDValue N1021
= N102
.getOperand(1);
11894 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11895 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11896 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11898 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, N101
),
11899 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11900 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11901 DAG
.getNode(ISD::FP_EXTEND
, SL
,
11903 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11905 N0
, Flags
), Flags
);
11913 /// Try to perform FMA combining on a given FMUL node based on the distributive
11914 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
11915 /// subtraction instead of addition).
11916 SDValue
DAGCombiner::visitFMULForFMADistributiveCombine(SDNode
*N
) {
11917 SDValue N0
= N
->getOperand(0);
11918 SDValue N1
= N
->getOperand(1);
11919 EVT VT
= N
->getValueType(0);
11921 const SDNodeFlags Flags
= N
->getFlags();
11923 assert(N
->getOpcode() == ISD::FMUL
&& "Expected FMUL Operation");
11925 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11927 // The transforms below are incorrect when x == 0 and y == inf, because the
11928 // intermediate multiplication produces a nan.
11929 if (!Options
.NoInfsFPMath
)
11932 // Floating-point multiply-add without intermediate rounding.
11934 (Options
.AllowFPOpFusion
== FPOpFusion::Fast
|| Options
.UnsafeFPMath
) &&
11935 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11936 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11938 // Floating-point multiply-add with intermediate rounding. This can result
11939 // in a less precise result due to the changed rounding order.
11940 bool HasFMAD
= Options
.UnsafeFPMath
&&
11941 (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11943 // No valid opcode, do not combine.
11944 if (!HasFMAD
&& !HasFMA
)
11947 // Always prefer FMAD to FMA for precision.
11948 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11949 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11951 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
11952 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
11953 auto FuseFADD
= [&](SDValue X
, SDValue Y
, const SDNodeFlags Flags
) {
11954 if (X
.getOpcode() == ISD::FADD
&& (Aggressive
|| X
->hasOneUse())) {
11955 if (auto *C
= isConstOrConstSplatFP(X
.getOperand(1), true)) {
11956 if (C
->isExactlyValue(+1.0))
11957 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11959 if (C
->isExactlyValue(-1.0))
11960 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11961 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11967 if (SDValue FMA
= FuseFADD(N0
, N1
, Flags
))
11969 if (SDValue FMA
= FuseFADD(N1
, N0
, Flags
))
11972 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
11973 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
11974 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
11975 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
11976 auto FuseFSUB
= [&](SDValue X
, SDValue Y
, const SDNodeFlags Flags
) {
11977 if (X
.getOpcode() == ISD::FSUB
&& (Aggressive
|| X
->hasOneUse())) {
11978 if (auto *C0
= isConstOrConstSplatFP(X
.getOperand(0), true)) {
11979 if (C0
->isExactlyValue(+1.0))
11980 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11981 DAG
.getNode(ISD::FNEG
, SL
, VT
, X
.getOperand(1)), Y
,
11983 if (C0
->isExactlyValue(-1.0))
11984 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11985 DAG
.getNode(ISD::FNEG
, SL
, VT
, X
.getOperand(1)), Y
,
11986 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11988 if (auto *C1
= isConstOrConstSplatFP(X
.getOperand(1), true)) {
11989 if (C1
->isExactlyValue(+1.0))
11990 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11991 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11992 if (C1
->isExactlyValue(-1.0))
11993 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
12000 if (SDValue FMA
= FuseFSUB(N0
, N1
, Flags
))
12002 if (SDValue FMA
= FuseFSUB(N1
, N0
, Flags
))
12008 SDValue
DAGCombiner::visitFADD(SDNode
*N
) {
12009 SDValue N0
= N
->getOperand(0);
12010 SDValue N1
= N
->getOperand(1);
12011 bool N0CFP
= isConstantFPBuildVectorOrConstantFP(N0
);
12012 bool N1CFP
= isConstantFPBuildVectorOrConstantFP(N1
);
12013 EVT VT
= N
->getValueType(0);
12015 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12016 const SDNodeFlags Flags
= N
->getFlags();
12020 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12023 // fold (fadd c1, c2) -> c1 + c2
12024 if (N0CFP
&& N1CFP
)
12025 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N1
, Flags
);
12027 // canonicalize constant to RHS
12028 if (N0CFP
&& !N1CFP
)
12029 return DAG
.getNode(ISD::FADD
, DL
, VT
, N1
, N0
, Flags
);
12031 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
12032 ConstantFPSDNode
*N1C
= isConstOrConstSplatFP(N1
, true);
12033 if (N1C
&& N1C
->isZero())
12034 if (N1C
->isNegative() || Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros())
12037 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12040 // fold (fadd A, (fneg B)) -> (fsub A, B)
12041 if ((!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
)) &&
12042 isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
) == 2)
12043 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
,
12044 GetNegatedExpression(N1
, DAG
, LegalOperations
,
12045 ForCodeSize
), Flags
);
12047 // fold (fadd (fneg A), B) -> (fsub B, A)
12048 if ((!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
)) &&
12049 isNegatibleForFree(N0
, LegalOperations
, TLI
, &Options
, ForCodeSize
) == 2)
12050 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N1
,
12051 GetNegatedExpression(N0
, DAG
, LegalOperations
,
12052 ForCodeSize
), Flags
);
12054 auto isFMulNegTwo
= [](SDValue FMul
) {
12055 if (!FMul
.hasOneUse() || FMul
.getOpcode() != ISD::FMUL
)
12057 auto *C
= isConstOrConstSplatFP(FMul
.getOperand(1), true);
12058 return C
&& C
->isExactlyValue(-2.0);
12061 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
12062 if (isFMulNegTwo(N0
)) {
12063 SDValue B
= N0
.getOperand(0);
12064 SDValue Add
= DAG
.getNode(ISD::FADD
, DL
, VT
, B
, B
, Flags
);
12065 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N1
, Add
, Flags
);
12067 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
12068 if (isFMulNegTwo(N1
)) {
12069 SDValue B
= N1
.getOperand(0);
12070 SDValue Add
= DAG
.getNode(ISD::FADD
, DL
, VT
, B
, B
, Flags
);
12071 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
, Add
, Flags
);
12074 // No FP constant should be created after legalization as Instruction
12075 // Selection pass has a hard time dealing with FP constants.
12076 bool AllowNewConst
= (Level
< AfterLegalizeDAG
);
12078 // If nnan is enabled, fold lots of things.
12079 if ((Options
.NoNaNsFPMath
|| Flags
.hasNoNaNs()) && AllowNewConst
) {
12080 // If allowed, fold (fadd (fneg x), x) -> 0.0
12081 if (N0
.getOpcode() == ISD::FNEG
&& N0
.getOperand(0) == N1
)
12082 return DAG
.getConstantFP(0.0, DL
, VT
);
12084 // If allowed, fold (fadd x, (fneg x)) -> 0.0
12085 if (N1
.getOpcode() == ISD::FNEG
&& N1
.getOperand(0) == N0
)
12086 return DAG
.getConstantFP(0.0, DL
, VT
);
12089 // If 'unsafe math' or reassoc and nsz, fold lots of things.
12090 // TODO: break out portions of the transformations below for which Unsafe is
12091 // considered and which do not require both nsz and reassoc
12092 if (((Options
.UnsafeFPMath
&& Options
.NoSignedZerosFPMath
) ||
12093 (Flags
.hasAllowReassociation() && Flags
.hasNoSignedZeros())) &&
12095 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
12096 if (N1CFP
&& N0
.getOpcode() == ISD::FADD
&&
12097 isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1))) {
12098 SDValue NewC
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1), N1
, Flags
);
12099 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(0), NewC
, Flags
);
12102 // We can fold chains of FADD's of the same value into multiplications.
12103 // This transform is not safe in general because we are reducing the number
12104 // of rounding steps.
12105 if (TLI
.isOperationLegalOrCustom(ISD::FMUL
, VT
) && !N0CFP
&& !N1CFP
) {
12106 if (N0
.getOpcode() == ISD::FMUL
) {
12107 bool CFP00
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(0));
12108 bool CFP01
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1));
12110 // (fadd (fmul x, c), x) -> (fmul x, c+1)
12111 if (CFP01
&& !CFP00
&& N0
.getOperand(0) == N1
) {
12112 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1),
12113 DAG
.getConstantFP(1.0, DL
, VT
), Flags
);
12114 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, NewCFP
, Flags
);
12117 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
12118 if (CFP01
&& !CFP00
&& N1
.getOpcode() == ISD::FADD
&&
12119 N1
.getOperand(0) == N1
.getOperand(1) &&
12120 N0
.getOperand(0) == N1
.getOperand(0)) {
12121 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1),
12122 DAG
.getConstantFP(2.0, DL
, VT
), Flags
);
12123 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0), NewCFP
, Flags
);
12127 if (N1
.getOpcode() == ISD::FMUL
) {
12128 bool CFP10
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(0));
12129 bool CFP11
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(1));
12131 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
12132 if (CFP11
&& !CFP10
&& N1
.getOperand(0) == N0
) {
12133 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N1
.getOperand(1),
12134 DAG
.getConstantFP(1.0, DL
, VT
), Flags
);
12135 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, NewCFP
, Flags
);
12138 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
12139 if (CFP11
&& !CFP10
&& N0
.getOpcode() == ISD::FADD
&&
12140 N0
.getOperand(0) == N0
.getOperand(1) &&
12141 N1
.getOperand(0) == N0
.getOperand(0)) {
12142 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N1
.getOperand(1),
12143 DAG
.getConstantFP(2.0, DL
, VT
), Flags
);
12144 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
.getOperand(0), NewCFP
, Flags
);
12148 if (N0
.getOpcode() == ISD::FADD
) {
12149 bool CFP00
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(0));
12150 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
12151 if (!CFP00
&& N0
.getOperand(0) == N0
.getOperand(1) &&
12152 (N0
.getOperand(0) == N1
)) {
12153 return DAG
.getNode(ISD::FMUL
, DL
, VT
,
12154 N1
, DAG
.getConstantFP(3.0, DL
, VT
), Flags
);
12158 if (N1
.getOpcode() == ISD::FADD
) {
12159 bool CFP10
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(0));
12160 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
12161 if (!CFP10
&& N1
.getOperand(0) == N1
.getOperand(1) &&
12162 N1
.getOperand(0) == N0
) {
12163 return DAG
.getNode(ISD::FMUL
, DL
, VT
,
12164 N0
, DAG
.getConstantFP(3.0, DL
, VT
), Flags
);
12168 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
12169 if (N0
.getOpcode() == ISD::FADD
&& N1
.getOpcode() == ISD::FADD
&&
12170 N0
.getOperand(0) == N0
.getOperand(1) &&
12171 N1
.getOperand(0) == N1
.getOperand(1) &&
12172 N0
.getOperand(0) == N1
.getOperand(0)) {
12173 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0),
12174 DAG
.getConstantFP(4.0, DL
, VT
), Flags
);
12177 } // enable-unsafe-fp-math
12179 // FADD -> FMA combines:
12180 if (SDValue Fused
= visitFADDForFMACombine(N
)) {
12181 AddToWorklist(Fused
.getNode());
12187 SDValue
DAGCombiner::visitFSUB(SDNode
*N
) {
12188 SDValue N0
= N
->getOperand(0);
12189 SDValue N1
= N
->getOperand(1);
12190 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, true);
12191 ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
, true);
12192 EVT VT
= N
->getValueType(0);
12194 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12195 const SDNodeFlags Flags
= N
->getFlags();
12199 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12202 // fold (fsub c1, c2) -> c1-c2
12203 if (N0CFP
&& N1CFP
)
12204 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
, N1
, Flags
);
12206 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12209 // (fsub A, 0) -> A
12210 if (N1CFP
&& N1CFP
->isZero()) {
12211 if (!N1CFP
->isNegative() || Options
.NoSignedZerosFPMath
||
12212 Flags
.hasNoSignedZeros()) {
12218 // (fsub x, x) -> 0.0
12219 if (Options
.NoNaNsFPMath
|| Flags
.hasNoNaNs())
12220 return DAG
.getConstantFP(0.0f
, DL
, VT
);
12223 // (fsub -0.0, N1) -> -N1
12224 // NOTE: It is safe to transform an FSUB(-0.0,X) into an FNEG(X), since the
12225 // FSUB does not specify the sign bit of a NaN. Also note that for
12226 // the same reason, the inverse transform is not safe, unless fast math
12227 // flags are in play.
12228 if (N0CFP
&& N0CFP
->isZero()) {
12229 if (N0CFP
->isNegative() ||
12230 (Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros())) {
12231 if (isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
))
12232 return GetNegatedExpression(N1
, DAG
, LegalOperations
, ForCodeSize
);
12233 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12234 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
, Flags
);
12238 if (((Options
.UnsafeFPMath
&& Options
.NoSignedZerosFPMath
) ||
12239 (Flags
.hasAllowReassociation() && Flags
.hasNoSignedZeros()))
12240 && N1
.getOpcode() == ISD::FADD
) {
12241 // X - (X + Y) -> -Y
12242 if (N0
== N1
->getOperand(0))
12243 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
->getOperand(1), Flags
);
12244 // X - (Y + X) -> -Y
12245 if (N0
== N1
->getOperand(1))
12246 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
->getOperand(0), Flags
);
12249 // fold (fsub A, (fneg B)) -> (fadd A, B)
12250 if (isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
))
12251 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
,
12252 GetNegatedExpression(N1
, DAG
, LegalOperations
,
12253 ForCodeSize
), Flags
);
12255 // FSUB -> FMA combines:
12256 if (SDValue Fused
= visitFSUBForFMACombine(N
)) {
12257 AddToWorklist(Fused
.getNode());
12264 /// Return true if both inputs are at least as cheap in negated form and at
12265 /// least one input is strictly cheaper in negated form.
12266 bool DAGCombiner::isCheaperToUseNegatedFPOps(SDValue X
, SDValue Y
) {
12267 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12268 if (char LHSNeg
= isNegatibleForFree(X
, LegalOperations
, TLI
, &Options
,
12270 if (char RHSNeg
= isNegatibleForFree(Y
, LegalOperations
, TLI
, &Options
,
12272 // Both negated operands are at least as cheap as their counterparts.
12273 // Check to see if at least one is cheaper negated.
12274 if (LHSNeg
== 2 || RHSNeg
== 2)
12280 SDValue
DAGCombiner::visitFMUL(SDNode
*N
) {
12281 SDValue N0
= N
->getOperand(0);
12282 SDValue N1
= N
->getOperand(1);
12283 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, true);
12284 ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
, true);
12285 EVT VT
= N
->getValueType(0);
12287 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12288 const SDNodeFlags Flags
= N
->getFlags();
12291 if (VT
.isVector()) {
12292 // This just handles C1 * C2 for vectors. Other vector folds are below.
12293 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12297 // fold (fmul c1, c2) -> c1*c2
12298 if (N0CFP
&& N1CFP
)
12299 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, N1
, Flags
);
12301 // canonicalize constant to RHS
12302 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
12303 !isConstantFPBuildVectorOrConstantFP(N1
))
12304 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, N0
, Flags
);
12306 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12309 if ((Options
.NoNaNsFPMath
&& Options
.NoSignedZerosFPMath
) ||
12310 (Flags
.hasNoNaNs() && Flags
.hasNoSignedZeros())) {
12311 // fold (fmul A, 0) -> 0
12312 if (N1CFP
&& N1CFP
->isZero())
12316 if (Options
.UnsafeFPMath
|| Flags
.hasAllowReassociation()) {
12317 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
12318 if (isConstantFPBuildVectorOrConstantFP(N1
) &&
12319 N0
.getOpcode() == ISD::FMUL
) {
12320 SDValue N00
= N0
.getOperand(0);
12321 SDValue N01
= N0
.getOperand(1);
12322 // Avoid an infinite loop by making sure that N00 is not a constant
12323 // (the inner multiply has not been constant folded yet).
12324 if (isConstantFPBuildVectorOrConstantFP(N01
) &&
12325 !isConstantFPBuildVectorOrConstantFP(N00
)) {
12326 SDValue MulConsts
= DAG
.getNode(ISD::FMUL
, DL
, VT
, N01
, N1
, Flags
);
12327 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N00
, MulConsts
, Flags
);
12331 // Match a special-case: we convert X * 2.0 into fadd.
12332 // fmul (fadd X, X), C -> fmul X, 2.0 * C
12333 if (N0
.getOpcode() == ISD::FADD
&& N0
.hasOneUse() &&
12334 N0
.getOperand(0) == N0
.getOperand(1)) {
12335 const SDValue Two
= DAG
.getConstantFP(2.0, DL
, VT
);
12336 SDValue MulConsts
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Two
, N1
, Flags
);
12337 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0), MulConsts
, Flags
);
12341 // fold (fmul X, 2.0) -> (fadd X, X)
12342 if (N1CFP
&& N1CFP
->isExactlyValue(+2.0))
12343 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N0
, Flags
);
12345 // fold (fmul X, -1.0) -> (fneg X)
12346 if (N1CFP
&& N1CFP
->isExactlyValue(-1.0))
12347 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12348 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N0
);
12350 // -N0 * -N1 --> N0 * N1
12351 if (isCheaperToUseNegatedFPOps(N0
, N1
)) {
12352 SDValue NegN0
= GetNegatedExpression(N0
, DAG
, LegalOperations
, ForCodeSize
);
12353 SDValue NegN1
= GetNegatedExpression(N1
, DAG
, LegalOperations
, ForCodeSize
);
12354 return DAG
.getNode(ISD::FMUL
, DL
, VT
, NegN0
, NegN1
, Flags
);
12357 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
12358 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
12359 if (Flags
.hasNoNaNs() && Flags
.hasNoSignedZeros() &&
12360 (N0
.getOpcode() == ISD::SELECT
|| N1
.getOpcode() == ISD::SELECT
) &&
12361 TLI
.isOperationLegal(ISD::FABS
, VT
)) {
12362 SDValue Select
= N0
, X
= N1
;
12363 if (Select
.getOpcode() != ISD::SELECT
)
12364 std::swap(Select
, X
);
12366 SDValue Cond
= Select
.getOperand(0);
12367 auto TrueOpnd
= dyn_cast
<ConstantFPSDNode
>(Select
.getOperand(1));
12368 auto FalseOpnd
= dyn_cast
<ConstantFPSDNode
>(Select
.getOperand(2));
12370 if (TrueOpnd
&& FalseOpnd
&&
12371 Cond
.getOpcode() == ISD::SETCC
&& Cond
.getOperand(0) == X
&&
12372 isa
<ConstantFPSDNode
>(Cond
.getOperand(1)) &&
12373 cast
<ConstantFPSDNode
>(Cond
.getOperand(1))->isExactlyValue(0.0)) {
12374 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Cond
.getOperand(2))->get();
12383 std::swap(TrueOpnd
, FalseOpnd
);
12391 if (TrueOpnd
->isExactlyValue(-1.0) && FalseOpnd
->isExactlyValue(1.0) &&
12392 TLI
.isOperationLegal(ISD::FNEG
, VT
))
12393 return DAG
.getNode(ISD::FNEG
, DL
, VT
,
12394 DAG
.getNode(ISD::FABS
, DL
, VT
, X
));
12395 if (TrueOpnd
->isExactlyValue(1.0) && FalseOpnd
->isExactlyValue(-1.0))
12396 return DAG
.getNode(ISD::FABS
, DL
, VT
, X
);
12403 // FMUL -> FMA combines:
12404 if (SDValue Fused
= visitFMULForFMADistributiveCombine(N
)) {
12405 AddToWorklist(Fused
.getNode());
12412 SDValue
DAGCombiner::visitFMA(SDNode
*N
) {
12413 SDValue N0
= N
->getOperand(0);
12414 SDValue N1
= N
->getOperand(1);
12415 SDValue N2
= N
->getOperand(2);
12416 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12417 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12418 EVT VT
= N
->getValueType(0);
12420 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12422 // FMA nodes have flags that propagate to the created nodes.
12423 const SDNodeFlags Flags
= N
->getFlags();
12424 bool UnsafeFPMath
= Options
.UnsafeFPMath
|| isContractable(N
);
12426 // Constant fold FMA.
12427 if (isa
<ConstantFPSDNode
>(N0
) &&
12428 isa
<ConstantFPSDNode
>(N1
) &&
12429 isa
<ConstantFPSDNode
>(N2
)) {
12430 return DAG
.getNode(ISD::FMA
, DL
, VT
, N0
, N1
, N2
);
12433 // (-N0 * -N1) + N2 --> (N0 * N1) + N2
12434 if (isCheaperToUseNegatedFPOps(N0
, N1
)) {
12435 SDValue NegN0
= GetNegatedExpression(N0
, DAG
, LegalOperations
, ForCodeSize
);
12436 SDValue NegN1
= GetNegatedExpression(N1
, DAG
, LegalOperations
, ForCodeSize
);
12437 return DAG
.getNode(ISD::FMA
, DL
, VT
, NegN0
, NegN1
, N2
, Flags
);
12440 if (UnsafeFPMath
) {
12441 if (N0CFP
&& N0CFP
->isZero())
12443 if (N1CFP
&& N1CFP
->isZero())
12446 // TODO: The FMA node should have flags that propagate to these nodes.
12447 if (N0CFP
&& N0CFP
->isExactlyValue(1.0))
12448 return DAG
.getNode(ISD::FADD
, SDLoc(N
), VT
, N1
, N2
);
12449 if (N1CFP
&& N1CFP
->isExactlyValue(1.0))
12450 return DAG
.getNode(ISD::FADD
, SDLoc(N
), VT
, N0
, N2
);
12452 // Canonicalize (fma c, x, y) -> (fma x, c, y)
12453 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
12454 !isConstantFPBuildVectorOrConstantFP(N1
))
12455 return DAG
.getNode(ISD::FMA
, SDLoc(N
), VT
, N1
, N0
, N2
);
12457 if (UnsafeFPMath
) {
12458 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
12459 if (N2
.getOpcode() == ISD::FMUL
&& N0
== N2
.getOperand(0) &&
12460 isConstantFPBuildVectorOrConstantFP(N1
) &&
12461 isConstantFPBuildVectorOrConstantFP(N2
.getOperand(1))) {
12462 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12463 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
, N2
.getOperand(1),
12467 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
12468 if (N0
.getOpcode() == ISD::FMUL
&&
12469 isConstantFPBuildVectorOrConstantFP(N1
) &&
12470 isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1))) {
12471 return DAG
.getNode(ISD::FMA
, DL
, VT
,
12473 DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, N0
.getOperand(1),
12479 // (fma x, 1, y) -> (fadd x, y)
12480 // (fma x, -1, y) -> (fadd (fneg x), y)
12482 if (N1CFP
->isExactlyValue(1.0))
12483 // TODO: The FMA node should have flags that propagate to this node.
12484 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N2
);
12486 if (N1CFP
->isExactlyValue(-1.0) &&
12487 (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))) {
12488 SDValue RHSNeg
= DAG
.getNode(ISD::FNEG
, DL
, VT
, N0
);
12489 AddToWorklist(RHSNeg
.getNode());
12490 // TODO: The FMA node should have flags that propagate to this node.
12491 return DAG
.getNode(ISD::FADD
, DL
, VT
, N2
, RHSNeg
);
12494 // fma (fneg x), K, y -> fma x -K, y
12495 if (N0
.getOpcode() == ISD::FNEG
&&
12496 (TLI
.isOperationLegal(ISD::ConstantFP
, VT
) ||
12497 (N1
.hasOneUse() && !TLI
.isFPImmLegal(N1CFP
->getValueAPF(), VT
,
12499 return DAG
.getNode(ISD::FMA
, DL
, VT
, N0
.getOperand(0),
12500 DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
, Flags
), N2
);
12504 if (UnsafeFPMath
) {
12505 // (fma x, c, x) -> (fmul x, (c+1))
12506 if (N1CFP
&& N0
== N2
) {
12507 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12508 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
,
12509 DAG
.getConstantFP(1.0, DL
, VT
), Flags
),
12513 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
12514 if (N1CFP
&& N2
.getOpcode() == ISD::FNEG
&& N2
.getOperand(0) == N0
) {
12515 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12516 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
,
12517 DAG
.getConstantFP(-1.0, DL
, VT
), Flags
),
12525 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12527 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
12528 // Notice that this is not always beneficial. One reason is different targets
12529 // may have different costs for FDIV and FMUL, so sometimes the cost of two
12530 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
12531 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
12532 SDValue
DAGCombiner::combineRepeatedFPDivisors(SDNode
*N
) {
12533 // TODO: Limit this transform based on optsize/minsize - it always creates at
12534 // least 1 extra instruction. But the perf win may be substantial enough
12535 // that only minsize should restrict this.
12536 bool UnsafeMath
= DAG
.getTarget().Options
.UnsafeFPMath
;
12537 const SDNodeFlags Flags
= N
->getFlags();
12538 if (!UnsafeMath
&& !Flags
.hasAllowReciprocal())
12541 // Skip if current node is a reciprocal/fneg-reciprocal.
12542 SDValue N0
= N
->getOperand(0);
12543 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, /* AllowUndefs */ true);
12544 if (N0CFP
&& (N0CFP
->isExactlyValue(1.0) || N0CFP
->isExactlyValue(-1.0)))
12547 // Exit early if the target does not want this transform or if there can't
12548 // possibly be enough uses of the divisor to make the transform worthwhile.
12549 SDValue N1
= N
->getOperand(1);
12550 unsigned MinUses
= TLI
.combineRepeatedFPDivisors();
12552 // For splat vectors, scale the number of uses by the splat factor. If we can
12553 // convert the division into a scalar op, that will likely be much faster.
12554 unsigned NumElts
= 1;
12555 EVT VT
= N
->getValueType(0);
12556 if (VT
.isVector() && DAG
.isSplatValue(N1
))
12557 NumElts
= VT
.getVectorNumElements();
12559 if (!MinUses
|| (N1
->use_size() * NumElts
) < MinUses
)
12562 // Find all FDIV users of the same divisor.
12563 // Use a set because duplicates may be present in the user list.
12564 SetVector
<SDNode
*> Users
;
12565 for (auto *U
: N1
->uses()) {
12566 if (U
->getOpcode() == ISD::FDIV
&& U
->getOperand(1) == N1
) {
12567 // This division is eligible for optimization only if global unsafe math
12568 // is enabled or if this division allows reciprocal formation.
12569 if (UnsafeMath
|| U
->getFlags().hasAllowReciprocal())
12574 // Now that we have the actual number of divisor uses, make sure it meets
12575 // the minimum threshold specified by the target.
12576 if ((Users
.size() * NumElts
) < MinUses
)
12580 SDValue FPOne
= DAG
.getConstantFP(1.0, DL
, VT
);
12581 SDValue Reciprocal
= DAG
.getNode(ISD::FDIV
, DL
, VT
, FPOne
, N1
, Flags
);
12583 // Dividend / Divisor -> Dividend * Reciprocal
12584 for (auto *U
: Users
) {
12585 SDValue Dividend
= U
->getOperand(0);
12586 if (Dividend
!= FPOne
) {
12587 SDValue NewNode
= DAG
.getNode(ISD::FMUL
, SDLoc(U
), VT
, Dividend
,
12588 Reciprocal
, Flags
);
12589 CombineTo(U
, NewNode
);
12590 } else if (U
!= Reciprocal
.getNode()) {
12591 // In the absence of fast-math-flags, this user node is always the
12592 // same node as Reciprocal, but with FMF they may be different nodes.
12593 CombineTo(U
, Reciprocal
);
12596 return SDValue(N
, 0); // N was replaced.
12599 SDValue
DAGCombiner::visitFDIV(SDNode
*N
) {
12600 SDValue N0
= N
->getOperand(0);
12601 SDValue N1
= N
->getOperand(1);
12602 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12603 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12604 EVT VT
= N
->getValueType(0);
12606 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12607 SDNodeFlags Flags
= N
->getFlags();
12611 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12614 // fold (fdiv c1, c2) -> c1/c2
12615 if (N0CFP
&& N1CFP
)
12616 return DAG
.getNode(ISD::FDIV
, SDLoc(N
), VT
, N0
, N1
, Flags
);
12618 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12621 if (SDValue V
= combineRepeatedFPDivisors(N
))
12624 if (Options
.UnsafeFPMath
|| Flags
.hasAllowReciprocal()) {
12625 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
12627 // Compute the reciprocal 1.0 / c2.
12628 const APFloat
&N1APF
= N1CFP
->getValueAPF();
12629 APFloat
Recip(N1APF
.getSemantics(), 1); // 1.0
12630 APFloat::opStatus st
= Recip
.divide(N1APF
, APFloat::rmNearestTiesToEven
);
12631 // Only do the transform if the reciprocal is a legal fp immediate that
12632 // isn't too nasty (eg NaN, denormal, ...).
12633 if ((st
== APFloat::opOK
|| st
== APFloat::opInexact
) && // Not too nasty
12634 (!LegalOperations
||
12635 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
12636 // backend)... we should handle this gracefully after Legalize.
12637 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
12638 TLI
.isOperationLegal(ISD::ConstantFP
, VT
) ||
12639 TLI
.isFPImmLegal(Recip
, VT
, ForCodeSize
)))
12640 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12641 DAG
.getConstantFP(Recip
, DL
, VT
), Flags
);
12644 // If this FDIV is part of a reciprocal square root, it may be folded
12645 // into a target-specific square root estimate instruction.
12646 if (N1
.getOpcode() == ISD::FSQRT
) {
12647 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0), Flags
))
12648 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12649 } else if (N1
.getOpcode() == ISD::FP_EXTEND
&&
12650 N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12651 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0).getOperand(0),
12653 RV
= DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N1
), VT
, RV
);
12654 AddToWorklist(RV
.getNode());
12655 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12657 } else if (N1
.getOpcode() == ISD::FP_ROUND
&&
12658 N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12659 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0).getOperand(0),
12661 RV
= DAG
.getNode(ISD::FP_ROUND
, SDLoc(N1
), VT
, RV
, N1
.getOperand(1));
12662 AddToWorklist(RV
.getNode());
12663 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12665 } else if (N1
.getOpcode() == ISD::FMUL
) {
12666 // Look through an FMUL. Even though this won't remove the FDIV directly,
12667 // it's still worthwhile to get rid of the FSQRT if possible.
12670 if (N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12671 SqrtOp
= N1
.getOperand(0);
12672 OtherOp
= N1
.getOperand(1);
12673 } else if (N1
.getOperand(1).getOpcode() == ISD::FSQRT
) {
12674 SqrtOp
= N1
.getOperand(1);
12675 OtherOp
= N1
.getOperand(0);
12677 if (SqrtOp
.getNode()) {
12678 // We found a FSQRT, so try to make this fold:
12679 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
12680 if (SDValue RV
= buildRsqrtEstimate(SqrtOp
.getOperand(0), Flags
)) {
12681 RV
= DAG
.getNode(ISD::FDIV
, SDLoc(N1
), VT
, RV
, OtherOp
, Flags
);
12682 AddToWorklist(RV
.getNode());
12683 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12688 // Fold into a reciprocal estimate and multiply instead of a real divide.
12689 if (SDValue RV
= BuildDivEstimate(N0
, N1
, Flags
))
12693 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
12694 if (isCheaperToUseNegatedFPOps(N0
, N1
))
12695 return DAG
.getNode(
12696 ISD::FDIV
, SDLoc(N
), VT
,
12697 GetNegatedExpression(N0
, DAG
, LegalOperations
, ForCodeSize
),
12698 GetNegatedExpression(N1
, DAG
, LegalOperations
, ForCodeSize
), Flags
);
12703 SDValue
DAGCombiner::visitFREM(SDNode
*N
) {
12704 SDValue N0
= N
->getOperand(0);
12705 SDValue N1
= N
->getOperand(1);
12706 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12707 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12708 EVT VT
= N
->getValueType(0);
12710 // fold (frem c1, c2) -> fmod(c1,c2)
12711 if (N0CFP
&& N1CFP
)
12712 return DAG
.getNode(ISD::FREM
, SDLoc(N
), VT
, N0
, N1
, N
->getFlags());
12714 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12720 SDValue
DAGCombiner::visitFSQRT(SDNode
*N
) {
12721 SDNodeFlags Flags
= N
->getFlags();
12722 if (!DAG
.getTarget().Options
.UnsafeFPMath
&&
12723 !Flags
.hasApproximateFuncs())
12726 SDValue N0
= N
->getOperand(0);
12727 if (TLI
.isFsqrtCheap(N0
, DAG
))
12730 // FSQRT nodes have flags that propagate to the created nodes.
12731 return buildSqrtEstimate(N0
, Flags
);
12734 /// copysign(x, fp_extend(y)) -> copysign(x, y)
12735 /// copysign(x, fp_round(y)) -> copysign(x, y)
12736 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode
*N
) {
12737 SDValue N1
= N
->getOperand(1);
12738 if ((N1
.getOpcode() == ISD::FP_EXTEND
||
12739 N1
.getOpcode() == ISD::FP_ROUND
)) {
12740 // Do not optimize out type conversion of f128 type yet.
12741 // For some targets like x86_64, configuration is changed to keep one f128
12742 // value in one SSE register, but instruction selection cannot handle
12743 // FCOPYSIGN on SSE registers yet.
12744 EVT N1VT
= N1
->getValueType(0);
12745 EVT N1Op0VT
= N1
->getOperand(0).getValueType();
12746 return (N1VT
== N1Op0VT
|| N1Op0VT
!= MVT::f128
);
12751 SDValue
DAGCombiner::visitFCOPYSIGN(SDNode
*N
) {
12752 SDValue N0
= N
->getOperand(0);
12753 SDValue N1
= N
->getOperand(1);
12754 bool N0CFP
= isConstantFPBuildVectorOrConstantFP(N0
);
12755 bool N1CFP
= isConstantFPBuildVectorOrConstantFP(N1
);
12756 EVT VT
= N
->getValueType(0);
12758 if (N0CFP
&& N1CFP
) // Constant fold
12759 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
);
12761 if (ConstantFPSDNode
*N1C
= isConstOrConstSplatFP(N
->getOperand(1))) {
12762 const APFloat
&V
= N1C
->getValueAPF();
12763 // copysign(x, c1) -> fabs(x) iff ispos(c1)
12764 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
12765 if (!V
.isNegative()) {
12766 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FABS
, VT
))
12767 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
12769 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12770 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
,
12771 DAG
.getNode(ISD::FABS
, SDLoc(N0
), VT
, N0
));
12775 // copysign(fabs(x), y) -> copysign(x, y)
12776 // copysign(fneg(x), y) -> copysign(x, y)
12777 // copysign(copysign(x,z), y) -> copysign(x, y)
12778 if (N0
.getOpcode() == ISD::FABS
|| N0
.getOpcode() == ISD::FNEG
||
12779 N0
.getOpcode() == ISD::FCOPYSIGN
)
12780 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
12782 // copysign(x, abs(y)) -> abs(x)
12783 if (N1
.getOpcode() == ISD::FABS
)
12784 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
12786 // copysign(x, copysign(y,z)) -> copysign(x, z)
12787 if (N1
.getOpcode() == ISD::FCOPYSIGN
)
12788 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
.getOperand(1));
12790 // copysign(x, fp_extend(y)) -> copysign(x, y)
12791 // copysign(x, fp_round(y)) -> copysign(x, y)
12792 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N
))
12793 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
.getOperand(0));
12798 SDValue
DAGCombiner::visitFPOW(SDNode
*N
) {
12799 ConstantFPSDNode
*ExponentC
= isConstOrConstSplatFP(N
->getOperand(1));
12803 // Try to convert x ** (1/3) into cube root.
12804 // TODO: Handle the various flavors of long double.
12805 // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
12806 // Some range near 1/3 should be fine.
12807 EVT VT
= N
->getValueType(0);
12808 if ((VT
== MVT::f32
&& ExponentC
->getValueAPF().isExactlyValue(1.0f
/3.0f
)) ||
12809 (VT
== MVT::f64
&& ExponentC
->getValueAPF().isExactlyValue(1.0/3.0))) {
12810 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
12811 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
12812 // pow(-val, 1/3) = nan; cbrt(-val) = -num.
12813 // For regular numbers, rounding may cause the results to differ.
12814 // Therefore, we require { nsz ninf nnan afn } for this transform.
12815 // TODO: We could select out the special cases if we don't have nsz/ninf.
12816 SDNodeFlags Flags
= N
->getFlags();
12817 if (!Flags
.hasNoSignedZeros() || !Flags
.hasNoInfs() || !Flags
.hasNoNaNs() ||
12818 !Flags
.hasApproximateFuncs())
12821 // Do not create a cbrt() libcall if the target does not have it, and do not
12822 // turn a pow that has lowering support into a cbrt() libcall.
12823 if (!DAG
.getLibInfo().has(LibFunc_cbrt
) ||
12824 (!DAG
.getTargetLoweringInfo().isOperationExpand(ISD::FPOW
, VT
) &&
12825 DAG
.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT
, VT
)))
12828 return DAG
.getNode(ISD::FCBRT
, SDLoc(N
), VT
, N
->getOperand(0), Flags
);
12831 // Try to convert x ** (1/4) and x ** (3/4) into square roots.
12832 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
12833 // TODO: This could be extended (using a target hook) to handle smaller
12834 // power-of-2 fractional exponents.
12835 bool ExponentIs025
= ExponentC
->getValueAPF().isExactlyValue(0.25);
12836 bool ExponentIs075
= ExponentC
->getValueAPF().isExactlyValue(0.75);
12837 if (ExponentIs025
|| ExponentIs075
) {
12838 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
12839 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
12840 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
12841 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
12842 // For regular numbers, rounding may cause the results to differ.
12843 // Therefore, we require { nsz ninf afn } for this transform.
12844 // TODO: We could select out the special cases if we don't have nsz/ninf.
12845 SDNodeFlags Flags
= N
->getFlags();
12847 // We only need no signed zeros for the 0.25 case.
12848 if ((!Flags
.hasNoSignedZeros() && ExponentIs025
) || !Flags
.hasNoInfs() ||
12849 !Flags
.hasApproximateFuncs())
12852 // Don't double the number of libcalls. We are trying to inline fast code.
12853 if (!DAG
.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT
, VT
))
12856 // Assume that libcalls are the smallest code.
12857 // TODO: This restriction should probably be lifted for vectors.
12858 if (DAG
.getMachineFunction().getFunction().hasOptSize())
12861 // pow(X, 0.25) --> sqrt(sqrt(X))
12863 SDValue Sqrt
= DAG
.getNode(ISD::FSQRT
, DL
, VT
, N
->getOperand(0), Flags
);
12864 SDValue SqrtSqrt
= DAG
.getNode(ISD::FSQRT
, DL
, VT
, Sqrt
, Flags
);
12867 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
12868 return DAG
.getNode(ISD::FMUL
, DL
, VT
, Sqrt
, SqrtSqrt
, Flags
);
12874 static SDValue
foldFPToIntToFP(SDNode
*N
, SelectionDAG
&DAG
,
12875 const TargetLowering
&TLI
) {
12876 // This optimization is guarded by a function attribute because it may produce
12877 // unexpected results. Ie, programs may be relying on the platform-specific
12878 // undefined behavior when the float-to-int conversion overflows.
12879 const Function
&F
= DAG
.getMachineFunction().getFunction();
12880 Attribute StrictOverflow
= F
.getFnAttribute("strict-float-cast-overflow");
12881 if (StrictOverflow
.getValueAsString().equals("false"))
12884 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
12885 // replacing casts with a libcall. We also must be allowed to ignore -0.0
12886 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
12887 // conversions would return +0.0.
12888 // FIXME: We should be able to use node-level FMF here.
12889 // TODO: If strict math, should we use FABS (+ range check for signed cast)?
12890 EVT VT
= N
->getValueType(0);
12891 if (!TLI
.isOperationLegal(ISD::FTRUNC
, VT
) ||
12892 !DAG
.getTarget().Options
.NoSignedZerosFPMath
)
12895 // fptosi/fptoui round towards zero, so converting from FP to integer and
12896 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
12897 SDValue N0
= N
->getOperand(0);
12898 if (N
->getOpcode() == ISD::SINT_TO_FP
&& N0
.getOpcode() == ISD::FP_TO_SINT
&&
12899 N0
.getOperand(0).getValueType() == VT
)
12900 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
.getOperand(0));
12902 if (N
->getOpcode() == ISD::UINT_TO_FP
&& N0
.getOpcode() == ISD::FP_TO_UINT
&&
12903 N0
.getOperand(0).getValueType() == VT
)
12904 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
.getOperand(0));
12909 SDValue
DAGCombiner::visitSINT_TO_FP(SDNode
*N
) {
12910 SDValue N0
= N
->getOperand(0);
12911 EVT VT
= N
->getValueType(0);
12912 EVT OpVT
= N0
.getValueType();
12914 // [us]itofp(undef) = 0, because the result value is bounded.
12916 return DAG
.getConstantFP(0.0, SDLoc(N
), VT
);
12918 // fold (sint_to_fp c1) -> c1fp
12919 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
12920 // ...but only if the target supports immediate floating-point values
12921 (!LegalOperations
||
12922 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
)))
12923 return DAG
.getNode(ISD::SINT_TO_FP
, SDLoc(N
), VT
, N0
);
12925 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
12926 // but UINT_TO_FP is legal on this target, try to convert.
12927 if (!hasOperation(ISD::SINT_TO_FP
, OpVT
) &&
12928 hasOperation(ISD::UINT_TO_FP
, OpVT
)) {
12929 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
12930 if (DAG
.SignBitIsZero(N0
))
12931 return DAG
.getNode(ISD::UINT_TO_FP
, SDLoc(N
), VT
, N0
);
12934 // The next optimizations are desirable only if SELECT_CC can be lowered.
12935 if (TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
) || !LegalOperations
) {
12936 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12937 if (N0
.getOpcode() == ISD::SETCC
&& N0
.getValueType() == MVT::i1
&&
12939 (!LegalOperations
||
12940 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
12943 { N0
.getOperand(0), N0
.getOperand(1),
12944 DAG
.getConstantFP(-1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
12945 N0
.getOperand(2) };
12946 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
12949 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
12950 // (select_cc x, y, 1.0, 0.0,, cc)
12951 if (N0
.getOpcode() == ISD::ZERO_EXTEND
&&
12952 N0
.getOperand(0).getOpcode() == ISD::SETCC
&&!VT
.isVector() &&
12953 (!LegalOperations
||
12954 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
12957 { N0
.getOperand(0).getOperand(0), N0
.getOperand(0).getOperand(1),
12958 DAG
.getConstantFP(1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
12959 N0
.getOperand(0).getOperand(2) };
12960 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
12964 if (SDValue FTrunc
= foldFPToIntToFP(N
, DAG
, TLI
))
12970 SDValue
DAGCombiner::visitUINT_TO_FP(SDNode
*N
) {
12971 SDValue N0
= N
->getOperand(0);
12972 EVT VT
= N
->getValueType(0);
12973 EVT OpVT
= N0
.getValueType();
12975 // [us]itofp(undef) = 0, because the result value is bounded.
12977 return DAG
.getConstantFP(0.0, SDLoc(N
), VT
);
12979 // fold (uint_to_fp c1) -> c1fp
12980 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
12981 // ...but only if the target supports immediate floating-point values
12982 (!LegalOperations
||
12983 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
)))
12984 return DAG
.getNode(ISD::UINT_TO_FP
, SDLoc(N
), VT
, N0
);
12986 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
12987 // but SINT_TO_FP is legal on this target, try to convert.
12988 if (!hasOperation(ISD::UINT_TO_FP
, OpVT
) &&
12989 hasOperation(ISD::SINT_TO_FP
, OpVT
)) {
12990 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
12991 if (DAG
.SignBitIsZero(N0
))
12992 return DAG
.getNode(ISD::SINT_TO_FP
, SDLoc(N
), VT
, N0
);
12995 // The next optimizations are desirable only if SELECT_CC can be lowered.
12996 if (TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
) || !LegalOperations
) {
12997 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12998 if (N0
.getOpcode() == ISD::SETCC
&& !VT
.isVector() &&
12999 (!LegalOperations
||
13000 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
13003 { N0
.getOperand(0), N0
.getOperand(1),
13004 DAG
.getConstantFP(1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
13005 N0
.getOperand(2) };
13006 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
13010 if (SDValue FTrunc
= foldFPToIntToFP(N
, DAG
, TLI
))
13016 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
13017 static SDValue
FoldIntToFPToInt(SDNode
*N
, SelectionDAG
&DAG
) {
13018 SDValue N0
= N
->getOperand(0);
13019 EVT VT
= N
->getValueType(0);
13021 if (N0
.getOpcode() != ISD::UINT_TO_FP
&& N0
.getOpcode() != ISD::SINT_TO_FP
)
13024 SDValue Src
= N0
.getOperand(0);
13025 EVT SrcVT
= Src
.getValueType();
13026 bool IsInputSigned
= N0
.getOpcode() == ISD::SINT_TO_FP
;
13027 bool IsOutputSigned
= N
->getOpcode() == ISD::FP_TO_SINT
;
13029 // We can safely assume the conversion won't overflow the output range,
13030 // because (for example) (uint8_t)18293.f is undefined behavior.
13032 // Since we can assume the conversion won't overflow, our decision as to
13033 // whether the input will fit in the float should depend on the minimum
13034 // of the input range and output range.
13036 // This means this is also safe for a signed input and unsigned output, since
13037 // a negative input would lead to undefined behavior.
13038 unsigned InputSize
= (int)SrcVT
.getScalarSizeInBits() - IsInputSigned
;
13039 unsigned OutputSize
= (int)VT
.getScalarSizeInBits() - IsOutputSigned
;
13040 unsigned ActualSize
= std::min(InputSize
, OutputSize
);
13041 const fltSemantics
&sem
= DAG
.EVTToAPFloatSemantics(N0
.getValueType());
13043 // We can only fold away the float conversion if the input range can be
13044 // represented exactly in the float range.
13045 if (APFloat::semanticsPrecision(sem
) >= ActualSize
) {
13046 if (VT
.getScalarSizeInBits() > SrcVT
.getScalarSizeInBits()) {
13047 unsigned ExtOp
= IsInputSigned
&& IsOutputSigned
? ISD::SIGN_EXTEND
13048 : ISD::ZERO_EXTEND
;
13049 return DAG
.getNode(ExtOp
, SDLoc(N
), VT
, Src
);
13051 if (VT
.getScalarSizeInBits() < SrcVT
.getScalarSizeInBits())
13052 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, Src
);
13053 return DAG
.getBitcast(VT
, Src
);
13058 SDValue
DAGCombiner::visitFP_TO_SINT(SDNode
*N
) {
13059 SDValue N0
= N
->getOperand(0);
13060 EVT VT
= N
->getValueType(0);
13062 // fold (fp_to_sint undef) -> undef
13064 return DAG
.getUNDEF(VT
);
13066 // fold (fp_to_sint c1fp) -> c1
13067 if (isConstantFPBuildVectorOrConstantFP(N0
))
13068 return DAG
.getNode(ISD::FP_TO_SINT
, SDLoc(N
), VT
, N0
);
13070 return FoldIntToFPToInt(N
, DAG
);
13073 SDValue
DAGCombiner::visitFP_TO_UINT(SDNode
*N
) {
13074 SDValue N0
= N
->getOperand(0);
13075 EVT VT
= N
->getValueType(0);
13077 // fold (fp_to_uint undef) -> undef
13079 return DAG
.getUNDEF(VT
);
13081 // fold (fp_to_uint c1fp) -> c1
13082 if (isConstantFPBuildVectorOrConstantFP(N0
))
13083 return DAG
.getNode(ISD::FP_TO_UINT
, SDLoc(N
), VT
, N0
);
13085 return FoldIntToFPToInt(N
, DAG
);
13088 SDValue
DAGCombiner::visitFP_ROUND(SDNode
*N
) {
13089 SDValue N0
= N
->getOperand(0);
13090 SDValue N1
= N
->getOperand(1);
13091 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
13092 EVT VT
= N
->getValueType(0);
13094 // fold (fp_round c1fp) -> c1fp
13096 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(N
), VT
, N0
, N1
);
13098 // fold (fp_round (fp_extend x)) -> x
13099 if (N0
.getOpcode() == ISD::FP_EXTEND
&& VT
== N0
.getOperand(0).getValueType())
13100 return N0
.getOperand(0);
13102 // fold (fp_round (fp_round x)) -> (fp_round x)
13103 if (N0
.getOpcode() == ISD::FP_ROUND
) {
13104 const bool NIsTrunc
= N
->getConstantOperandVal(1) == 1;
13105 const bool N0IsTrunc
= N0
.getConstantOperandVal(1) == 1;
13107 // Skip this folding if it results in an fp_round from f80 to f16.
13109 // f80 to f16 always generates an expensive (and as yet, unimplemented)
13110 // libcall to __truncxfhf2 instead of selecting native f16 conversion
13111 // instructions from f32 or f64. Moreover, the first (value-preserving)
13112 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
13114 if (N0
.getOperand(0).getValueType() == MVT::f80
&& VT
== MVT::f16
)
13117 // If the first fp_round isn't a value preserving truncation, it might
13118 // introduce a tie in the second fp_round, that wouldn't occur in the
13119 // single-step fp_round we want to fold to.
13120 // In other words, double rounding isn't the same as rounding.
13121 // Also, this is a value preserving truncation iff both fp_round's are.
13122 if (DAG
.getTarget().Options
.UnsafeFPMath
|| N0IsTrunc
) {
13124 return DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, N0
.getOperand(0),
13125 DAG
.getIntPtrConstant(NIsTrunc
&& N0IsTrunc
, DL
));
13129 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
13130 if (N0
.getOpcode() == ISD::FCOPYSIGN
&& N0
.getNode()->hasOneUse()) {
13131 SDValue Tmp
= DAG
.getNode(ISD::FP_ROUND
, SDLoc(N0
), VT
,
13132 N0
.getOperand(0), N1
);
13133 AddToWorklist(Tmp
.getNode());
13134 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
,
13135 Tmp
, N0
.getOperand(1));
13138 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
13144 SDValue
DAGCombiner::visitFP_EXTEND(SDNode
*N
) {
13145 SDValue N0
= N
->getOperand(0);
13146 EVT VT
= N
->getValueType(0);
13148 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
13149 if (N
->hasOneUse() &&
13150 N
->use_begin()->getOpcode() == ISD::FP_ROUND
)
13153 // fold (fp_extend c1fp) -> c1fp
13154 if (isConstantFPBuildVectorOrConstantFP(N0
))
13155 return DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N
), VT
, N0
);
13157 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
13158 if (N0
.getOpcode() == ISD::FP16_TO_FP
&&
13159 TLI
.getOperationAction(ISD::FP16_TO_FP
, VT
) == TargetLowering::Legal
)
13160 return DAG
.getNode(ISD::FP16_TO_FP
, SDLoc(N
), VT
, N0
.getOperand(0));
13162 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
13164 if (N0
.getOpcode() == ISD::FP_ROUND
13165 && N0
.getConstantOperandVal(1) == 1) {
13166 SDValue In
= N0
.getOperand(0);
13167 if (In
.getValueType() == VT
) return In
;
13168 if (VT
.bitsLT(In
.getValueType()))
13169 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(N
), VT
,
13170 In
, N0
.getOperand(1));
13171 return DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N
), VT
, In
);
13174 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
13175 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
13176 TLI
.isLoadExtLegal(ISD::EXTLOAD
, VT
, N0
.getValueType())) {
13177 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
13178 SDValue ExtLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, SDLoc(N
), VT
,
13180 LN0
->getBasePtr(), N0
.getValueType(),
13181 LN0
->getMemOperand());
13182 CombineTo(N
, ExtLoad
);
13183 CombineTo(N0
.getNode(),
13184 DAG
.getNode(ISD::FP_ROUND
, SDLoc(N0
),
13185 N0
.getValueType(), ExtLoad
,
13186 DAG
.getIntPtrConstant(1, SDLoc(N0
))),
13187 ExtLoad
.getValue(1));
13188 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
13191 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
13197 SDValue
DAGCombiner::visitFCEIL(SDNode
*N
) {
13198 SDValue N0
= N
->getOperand(0);
13199 EVT VT
= N
->getValueType(0);
13201 // fold (fceil c1) -> fceil(c1)
13202 if (isConstantFPBuildVectorOrConstantFP(N0
))
13203 return DAG
.getNode(ISD::FCEIL
, SDLoc(N
), VT
, N0
);
13208 SDValue
DAGCombiner::visitFTRUNC(SDNode
*N
) {
13209 SDValue N0
= N
->getOperand(0);
13210 EVT VT
= N
->getValueType(0);
13212 // fold (ftrunc c1) -> ftrunc(c1)
13213 if (isConstantFPBuildVectorOrConstantFP(N0
))
13214 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
);
13216 // fold ftrunc (known rounded int x) -> x
13217 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
13218 // likely to be generated to extract integer from a rounded floating value.
13219 switch (N0
.getOpcode()) {
13223 case ISD::FNEARBYINT
:
13232 SDValue
DAGCombiner::visitFFLOOR(SDNode
*N
) {
13233 SDValue N0
= N
->getOperand(0);
13234 EVT VT
= N
->getValueType(0);
13236 // fold (ffloor c1) -> ffloor(c1)
13237 if (isConstantFPBuildVectorOrConstantFP(N0
))
13238 return DAG
.getNode(ISD::FFLOOR
, SDLoc(N
), VT
, N0
);
13243 // FIXME: FNEG and FABS have a lot in common; refactor.
13244 SDValue
DAGCombiner::visitFNEG(SDNode
*N
) {
13245 SDValue N0
= N
->getOperand(0);
13246 EVT VT
= N
->getValueType(0);
13248 // Constant fold FNEG.
13249 if (isConstantFPBuildVectorOrConstantFP(N0
))
13250 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, N0
);
13252 if (isNegatibleForFree(N0
, LegalOperations
, DAG
.getTargetLoweringInfo(),
13253 &DAG
.getTarget().Options
, ForCodeSize
))
13254 return GetNegatedExpression(N0
, DAG
, LegalOperations
, ForCodeSize
);
13256 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
13257 // constant pool values.
13258 if (!TLI
.isFNegFree(VT
) &&
13259 N0
.getOpcode() == ISD::BITCAST
&&
13260 N0
.getNode()->hasOneUse()) {
13261 SDValue Int
= N0
.getOperand(0);
13262 EVT IntVT
= Int
.getValueType();
13263 if (IntVT
.isInteger() && !IntVT
.isVector()) {
13265 if (N0
.getValueType().isVector()) {
13266 // For a vector, get a mask such as 0x80... per scalar element
13268 SignMask
= APInt::getSignMask(N0
.getScalarValueSizeInBits());
13269 SignMask
= APInt::getSplat(IntVT
.getSizeInBits(), SignMask
);
13271 // For a scalar, just generate 0x80...
13272 SignMask
= APInt::getSignMask(IntVT
.getSizeInBits());
13275 Int
= DAG
.getNode(ISD::XOR
, DL0
, IntVT
, Int
,
13276 DAG
.getConstant(SignMask
, DL0
, IntVT
));
13277 AddToWorklist(Int
.getNode());
13278 return DAG
.getBitcast(VT
, Int
);
13282 // (fneg (fmul c, x)) -> (fmul -c, x)
13283 if (N0
.getOpcode() == ISD::FMUL
&&
13284 (N0
.getNode()->hasOneUse() || !TLI
.isFNegFree(VT
))) {
13285 ConstantFPSDNode
*CFP1
= dyn_cast
<ConstantFPSDNode
>(N0
.getOperand(1));
13287 APFloat CVal
= CFP1
->getValueAPF();
13289 if (Level
>= AfterLegalizeDAG
&&
13290 (TLI
.isFPImmLegal(CVal
, VT
, ForCodeSize
) ||
13291 TLI
.isOperationLegal(ISD::ConstantFP
, VT
)))
13292 return DAG
.getNode(
13293 ISD::FMUL
, SDLoc(N
), VT
, N0
.getOperand(0),
13294 DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, N0
.getOperand(1)),
13302 static SDValue
visitFMinMax(SelectionDAG
&DAG
, SDNode
*N
,
13303 APFloat (*Op
)(const APFloat
&, const APFloat
&)) {
13304 SDValue N0
= N
->getOperand(0);
13305 SDValue N1
= N
->getOperand(1);
13306 EVT VT
= N
->getValueType(0);
13307 const ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
);
13308 const ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
);
13310 if (N0CFP
&& N1CFP
) {
13311 const APFloat
&C0
= N0CFP
->getValueAPF();
13312 const APFloat
&C1
= N1CFP
->getValueAPF();
13313 return DAG
.getConstantFP(Op(C0
, C1
), SDLoc(N
), VT
);
13316 // Canonicalize to constant on RHS.
13317 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
13318 !isConstantFPBuildVectorOrConstantFP(N1
))
13319 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
);
13324 SDValue
DAGCombiner::visitFMINNUM(SDNode
*N
) {
13325 return visitFMinMax(DAG
, N
, minnum
);
13328 SDValue
DAGCombiner::visitFMAXNUM(SDNode
*N
) {
13329 return visitFMinMax(DAG
, N
, maxnum
);
13332 SDValue
DAGCombiner::visitFMINIMUM(SDNode
*N
) {
13333 return visitFMinMax(DAG
, N
, minimum
);
13336 SDValue
DAGCombiner::visitFMAXIMUM(SDNode
*N
) {
13337 return visitFMinMax(DAG
, N
, maximum
);
13340 SDValue
DAGCombiner::visitFABS(SDNode
*N
) {
13341 SDValue N0
= N
->getOperand(0);
13342 EVT VT
= N
->getValueType(0);
13344 // fold (fabs c1) -> fabs(c1)
13345 if (isConstantFPBuildVectorOrConstantFP(N0
))
13346 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
13348 // fold (fabs (fabs x)) -> (fabs x)
13349 if (N0
.getOpcode() == ISD::FABS
)
13350 return N
->getOperand(0);
13352 // fold (fabs (fneg x)) -> (fabs x)
13353 // fold (fabs (fcopysign x, y)) -> (fabs x)
13354 if (N0
.getOpcode() == ISD::FNEG
|| N0
.getOpcode() == ISD::FCOPYSIGN
)
13355 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
.getOperand(0));
13357 // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads.
13358 if (!TLI
.isFAbsFree(VT
) && N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse()) {
13359 SDValue Int
= N0
.getOperand(0);
13360 EVT IntVT
= Int
.getValueType();
13361 if (IntVT
.isInteger() && !IntVT
.isVector()) {
13363 if (N0
.getValueType().isVector()) {
13364 // For a vector, get a mask such as 0x7f... per scalar element
13366 SignMask
= ~APInt::getSignMask(N0
.getScalarValueSizeInBits());
13367 SignMask
= APInt::getSplat(IntVT
.getSizeInBits(), SignMask
);
13369 // For a scalar, just generate 0x7f...
13370 SignMask
= ~APInt::getSignMask(IntVT
.getSizeInBits());
13373 Int
= DAG
.getNode(ISD::AND
, DL
, IntVT
, Int
,
13374 DAG
.getConstant(SignMask
, DL
, IntVT
));
13375 AddToWorklist(Int
.getNode());
13376 return DAG
.getBitcast(N
->getValueType(0), Int
);
13383 SDValue
DAGCombiner::visitBRCOND(SDNode
*N
) {
13384 SDValue Chain
= N
->getOperand(0);
13385 SDValue N1
= N
->getOperand(1);
13386 SDValue N2
= N
->getOperand(2);
13388 // If N is a constant we could fold this into a fallthrough or unconditional
13389 // branch. However that doesn't happen very often in normal code, because
13390 // Instcombine/SimplifyCFG should have handled the available opportunities.
13391 // If we did this folding here, it would be necessary to update the
13392 // MachineBasicBlock CFG, which is awkward.
13394 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
13396 if (N1
.getOpcode() == ISD::SETCC
&&
13397 TLI
.isOperationLegalOrCustom(ISD::BR_CC
,
13398 N1
.getOperand(0).getValueType())) {
13399 return DAG
.getNode(ISD::BR_CC
, SDLoc(N
), MVT::Other
,
13400 Chain
, N1
.getOperand(2),
13401 N1
.getOperand(0), N1
.getOperand(1), N2
);
13404 if (N1
.hasOneUse()) {
13405 if (SDValue NewN1
= rebuildSetCC(N1
))
13406 return DAG
.getNode(ISD::BRCOND
, SDLoc(N
), MVT::Other
, Chain
, NewN1
, N2
);
13412 SDValue
DAGCombiner::rebuildSetCC(SDValue N
) {
13413 if (N
.getOpcode() == ISD::SRL
||
13414 (N
.getOpcode() == ISD::TRUNCATE
&&
13415 (N
.getOperand(0).hasOneUse() &&
13416 N
.getOperand(0).getOpcode() == ISD::SRL
))) {
13417 // Look pass the truncate.
13418 if (N
.getOpcode() == ISD::TRUNCATE
)
13419 N
= N
.getOperand(0);
13421 // Match this pattern so that we can generate simpler code:
13424 // %b = and i32 %a, 2
13425 // %c = srl i32 %b, 1
13426 // brcond i32 %c ...
13431 // %b = and i32 %a, 2
13432 // %c = setcc eq %b, 0
13435 // This applies only when the AND constant value has one bit set and the
13436 // SRL constant is equal to the log2 of the AND constant. The back-end is
13437 // smart enough to convert the result into a TEST/JMP sequence.
13438 SDValue Op0
= N
.getOperand(0);
13439 SDValue Op1
= N
.getOperand(1);
13441 if (Op0
.getOpcode() == ISD::AND
&& Op1
.getOpcode() == ISD::Constant
) {
13442 SDValue AndOp1
= Op0
.getOperand(1);
13444 if (AndOp1
.getOpcode() == ISD::Constant
) {
13445 const APInt
&AndConst
= cast
<ConstantSDNode
>(AndOp1
)->getAPIntValue();
13447 if (AndConst
.isPowerOf2() &&
13448 cast
<ConstantSDNode
>(Op1
)->getAPIntValue() == AndConst
.logBase2()) {
13450 return DAG
.getSetCC(DL
, getSetCCResultType(Op0
.getValueType()),
13451 Op0
, DAG
.getConstant(0, DL
, Op0
.getValueType()),
13458 // Transform br(xor(x, y)) -> br(x != y)
13459 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
13460 if (N
.getOpcode() == ISD::XOR
) {
13461 // Because we may call this on a speculatively constructed
13462 // SimplifiedSetCC Node, we need to simplify this node first.
13463 // Ideally this should be folded into SimplifySetCC and not
13464 // here. For now, grab a handle to N so we don't lose it from
13465 // replacements interal to the visit.
13466 HandleSDNode
XORHandle(N
);
13467 while (N
.getOpcode() == ISD::XOR
) {
13468 SDValue Tmp
= visitXOR(N
.getNode());
13469 // No simplification done.
13470 if (!Tmp
.getNode())
13472 // Returning N is form in-visit replacement that may invalidated
13473 // N. Grab value from Handle.
13474 if (Tmp
.getNode() == N
.getNode())
13475 N
= XORHandle
.getValue();
13476 else // Node simplified. Try simplifying again.
13480 if (N
.getOpcode() != ISD::XOR
)
13483 SDNode
*TheXor
= N
.getNode();
13485 SDValue Op0
= TheXor
->getOperand(0);
13486 SDValue Op1
= TheXor
->getOperand(1);
13488 if (Op0
.getOpcode() != ISD::SETCC
&& Op1
.getOpcode() != ISD::SETCC
) {
13489 bool Equal
= false;
13490 if (isOneConstant(Op0
) && Op0
.hasOneUse() &&
13491 Op0
.getOpcode() == ISD::XOR
) {
13492 TheXor
= Op0
.getNode();
13496 EVT SetCCVT
= N
.getValueType();
13498 SetCCVT
= getSetCCResultType(SetCCVT
);
13499 // Replace the uses of XOR with SETCC
13500 return DAG
.getSetCC(SDLoc(TheXor
), SetCCVT
, Op0
, Op1
,
13501 Equal
? ISD::SETEQ
: ISD::SETNE
);
13508 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
13510 SDValue
DAGCombiner::visitBR_CC(SDNode
*N
) {
13511 CondCodeSDNode
*CC
= cast
<CondCodeSDNode
>(N
->getOperand(1));
13512 SDValue CondLHS
= N
->getOperand(2), CondRHS
= N
->getOperand(3);
13514 // If N is a constant we could fold this into a fallthrough or unconditional
13515 // branch. However that doesn't happen very often in normal code, because
13516 // Instcombine/SimplifyCFG should have handled the available opportunities.
13517 // If we did this folding here, it would be necessary to update the
13518 // MachineBasicBlock CFG, which is awkward.
13520 // Use SimplifySetCC to simplify SETCC's.
13521 SDValue Simp
= SimplifySetCC(getSetCCResultType(CondLHS
.getValueType()),
13522 CondLHS
, CondRHS
, CC
->get(), SDLoc(N
),
13524 if (Simp
.getNode()) AddToWorklist(Simp
.getNode());
13526 // fold to a simpler setcc
13527 if (Simp
.getNode() && Simp
.getOpcode() == ISD::SETCC
)
13528 return DAG
.getNode(ISD::BR_CC
, SDLoc(N
), MVT::Other
,
13529 N
->getOperand(0), Simp
.getOperand(2),
13530 Simp
.getOperand(0), Simp
.getOperand(1),
13536 /// Return true if 'Use' is a load or a store that uses N as its base pointer
13537 /// and that N may be folded in the load / store addressing mode.
13538 static bool canFoldInAddressingMode(SDNode
*N
, SDNode
*Use
,
13540 const TargetLowering
&TLI
) {
13544 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(Use
)) {
13545 if (LD
->isIndexed() || LD
->getBasePtr().getNode() != N
)
13547 VT
= LD
->getMemoryVT();
13548 AS
= LD
->getAddressSpace();
13549 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Use
)) {
13550 if (ST
->isIndexed() || ST
->getBasePtr().getNode() != N
)
13552 VT
= ST
->getMemoryVT();
13553 AS
= ST
->getAddressSpace();
13557 TargetLowering::AddrMode AM
;
13558 if (N
->getOpcode() == ISD::ADD
) {
13559 AM
.HasBaseReg
= true;
13560 ConstantSDNode
*Offset
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
13563 AM
.BaseOffs
= Offset
->getSExtValue();
13567 } else if (N
->getOpcode() == ISD::SUB
) {
13568 AM
.HasBaseReg
= true;
13569 ConstantSDNode
*Offset
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
13572 AM
.BaseOffs
= -Offset
->getSExtValue();
13579 return TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
,
13580 VT
.getTypeForEVT(*DAG
.getContext()), AS
);
13583 /// Try turning a load/store into a pre-indexed load/store when the base
13584 /// pointer is an add or subtract and it has other uses besides the load/store.
13585 /// After the transformation, the new indexed load/store has effectively folded
13586 /// the add/subtract in and all of its other uses are redirected to the
13587 /// new load/store.
13588 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode
*N
) {
13589 if (Level
< AfterLegalizeDAG
)
13592 bool isLoad
= true;
13595 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
13596 if (LD
->isIndexed())
13598 VT
= LD
->getMemoryVT();
13599 if (!TLI
.isIndexedLoadLegal(ISD::PRE_INC
, VT
) &&
13600 !TLI
.isIndexedLoadLegal(ISD::PRE_DEC
, VT
))
13602 Ptr
= LD
->getBasePtr();
13603 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
13604 if (ST
->isIndexed())
13606 VT
= ST
->getMemoryVT();
13607 if (!TLI
.isIndexedStoreLegal(ISD::PRE_INC
, VT
) &&
13608 !TLI
.isIndexedStoreLegal(ISD::PRE_DEC
, VT
))
13610 Ptr
= ST
->getBasePtr();
13616 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
13617 // out. There is no reason to make this a preinc/predec.
13618 if ((Ptr
.getOpcode() != ISD::ADD
&& Ptr
.getOpcode() != ISD::SUB
) ||
13619 Ptr
.getNode()->hasOneUse())
13622 // Ask the target to do addressing mode selection.
13625 ISD::MemIndexedMode AM
= ISD::UNINDEXED
;
13626 if (!TLI
.getPreIndexedAddressParts(N
, BasePtr
, Offset
, AM
, DAG
))
13629 // Backends without true r+i pre-indexed forms may need to pass a
13630 // constant base with a variable offset so that constant coercion
13631 // will work with the patterns in canonical form.
13632 bool Swapped
= false;
13633 if (isa
<ConstantSDNode
>(BasePtr
)) {
13634 std::swap(BasePtr
, Offset
);
13638 // Don't create a indexed load / store with zero offset.
13639 if (isNullConstant(Offset
))
13642 // Try turning it into a pre-indexed load / store except when:
13643 // 1) The new base ptr is a frame index.
13644 // 2) If N is a store and the new base ptr is either the same as or is a
13645 // predecessor of the value being stored.
13646 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
13647 // that would create a cycle.
13648 // 4) All uses are load / store ops that use it as old base ptr.
13650 // Check #1. Preinc'ing a frame index would require copying the stack pointer
13651 // (plus the implicit offset) to a register to preinc anyway.
13652 if (isa
<FrameIndexSDNode
>(BasePtr
) || isa
<RegisterSDNode
>(BasePtr
))
13657 SDValue Val
= cast
<StoreSDNode
>(N
)->getValue();
13659 // Would require a copy.
13660 if (Val
== BasePtr
)
13663 // Would create a cycle.
13664 if (Val
== Ptr
|| Ptr
->isPredecessorOf(Val
.getNode()))
13668 // Caches for hasPredecessorHelper.
13669 SmallPtrSet
<const SDNode
*, 32> Visited
;
13670 SmallVector
<const SDNode
*, 16> Worklist
;
13671 Worklist
.push_back(N
);
13673 // If the offset is a constant, there may be other adds of constants that
13674 // can be folded with this one. We should do this to avoid having to keep
13675 // a copy of the original base pointer.
13676 SmallVector
<SDNode
*, 16> OtherUses
;
13677 if (isa
<ConstantSDNode
>(Offset
))
13678 for (SDNode::use_iterator UI
= BasePtr
.getNode()->use_begin(),
13679 UE
= BasePtr
.getNode()->use_end();
13681 SDUse
&Use
= UI
.getUse();
13682 // Skip the use that is Ptr and uses of other results from BasePtr's
13683 // node (important for nodes that return multiple results).
13684 if (Use
.getUser() == Ptr
.getNode() || Use
!= BasePtr
)
13687 if (SDNode::hasPredecessorHelper(Use
.getUser(), Visited
, Worklist
))
13690 if (Use
.getUser()->getOpcode() != ISD::ADD
&&
13691 Use
.getUser()->getOpcode() != ISD::SUB
) {
13696 SDValue Op1
= Use
.getUser()->getOperand((UI
.getOperandNo() + 1) & 1);
13697 if (!isa
<ConstantSDNode
>(Op1
)) {
13702 // FIXME: In some cases, we can be smarter about this.
13703 if (Op1
.getValueType() != Offset
.getValueType()) {
13708 OtherUses
.push_back(Use
.getUser());
13712 std::swap(BasePtr
, Offset
);
13714 // Now check for #3 and #4.
13715 bool RealUse
= false;
13717 for (SDNode
*Use
: Ptr
.getNode()->uses()) {
13720 if (SDNode::hasPredecessorHelper(Use
, Visited
, Worklist
))
13723 // If Ptr may be folded in addressing mode of other use, then it's
13724 // not profitable to do this transformation.
13725 if (!canFoldInAddressingMode(Ptr
.getNode(), Use
, DAG
, TLI
))
13734 Result
= DAG
.getIndexedLoad(SDValue(N
,0), SDLoc(N
),
13735 BasePtr
, Offset
, AM
);
13737 Result
= DAG
.getIndexedStore(SDValue(N
,0), SDLoc(N
),
13738 BasePtr
, Offset
, AM
);
13741 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N
->dump(&DAG
); dbgs() << "\nWith: ";
13742 Result
.getNode()->dump(&DAG
); dbgs() << '\n');
13743 WorklistRemover
DeadNodes(*this);
13745 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(0));
13746 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Result
.getValue(2));
13748 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(1));
13751 // Finally, since the node is now dead, remove it from the graph.
13752 deleteAndRecombine(N
);
13755 std::swap(BasePtr
, Offset
);
13757 // Replace other uses of BasePtr that can be updated to use Ptr
13758 for (unsigned i
= 0, e
= OtherUses
.size(); i
!= e
; ++i
) {
13759 unsigned OffsetIdx
= 1;
13760 if (OtherUses
[i
]->getOperand(OffsetIdx
).getNode() == BasePtr
.getNode())
13762 assert(OtherUses
[i
]->getOperand(!OffsetIdx
).getNode() ==
13763 BasePtr
.getNode() && "Expected BasePtr operand");
13765 // We need to replace ptr0 in the following expression:
13766 // x0 * offset0 + y0 * ptr0 = t0
13768 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
13770 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
13771 // indexed load/store and the expression that needs to be re-written.
13773 // Therefore, we have:
13774 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
13776 ConstantSDNode
*CN
=
13777 cast
<ConstantSDNode
>(OtherUses
[i
]->getOperand(OffsetIdx
));
13778 int X0
, X1
, Y0
, Y1
;
13779 const APInt
&Offset0
= CN
->getAPIntValue();
13780 APInt Offset1
= cast
<ConstantSDNode
>(Offset
)->getAPIntValue();
13782 X0
= (OtherUses
[i
]->getOpcode() == ISD::SUB
&& OffsetIdx
== 1) ? -1 : 1;
13783 Y0
= (OtherUses
[i
]->getOpcode() == ISD::SUB
&& OffsetIdx
== 0) ? -1 : 1;
13784 X1
= (AM
== ISD::PRE_DEC
&& !Swapped
) ? -1 : 1;
13785 Y1
= (AM
== ISD::PRE_DEC
&& Swapped
) ? -1 : 1;
13787 unsigned Opcode
= (Y0
* Y1
< 0) ? ISD::SUB
: ISD::ADD
;
13789 APInt CNV
= Offset0
;
13790 if (X0
< 0) CNV
= -CNV
;
13791 if (X1
* Y0
* Y1
< 0) CNV
= CNV
+ Offset1
;
13792 else CNV
= CNV
- Offset1
;
13794 SDLoc
DL(OtherUses
[i
]);
13796 // We can now generate the new expression.
13797 SDValue NewOp1
= DAG
.getConstant(CNV
, DL
, CN
->getValueType(0));
13798 SDValue NewOp2
= Result
.getValue(isLoad
? 1 : 0);
13800 SDValue NewUse
= DAG
.getNode(Opcode
,
13802 OtherUses
[i
]->getValueType(0), NewOp1
, NewOp2
);
13803 DAG
.ReplaceAllUsesOfValueWith(SDValue(OtherUses
[i
], 0), NewUse
);
13804 deleteAndRecombine(OtherUses
[i
]);
13807 // Replace the uses of Ptr with uses of the updated base value.
13808 DAG
.ReplaceAllUsesOfValueWith(Ptr
, Result
.getValue(isLoad
? 1 : 0));
13809 deleteAndRecombine(Ptr
.getNode());
13810 AddToWorklist(Result
.getNode());
13815 /// Try to combine a load/store with a add/sub of the base pointer node into a
13816 /// post-indexed load/store. The transformation folded the add/subtract into the
13817 /// new indexed load/store effectively and all of its uses are redirected to the
13818 /// new load/store.
13819 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode
*N
) {
13820 if (Level
< AfterLegalizeDAG
)
13823 bool isLoad
= true;
13826 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
13827 if (LD
->isIndexed())
13829 VT
= LD
->getMemoryVT();
13830 if (!TLI
.isIndexedLoadLegal(ISD::POST_INC
, VT
) &&
13831 !TLI
.isIndexedLoadLegal(ISD::POST_DEC
, VT
))
13833 Ptr
= LD
->getBasePtr();
13834 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
13835 if (ST
->isIndexed())
13837 VT
= ST
->getMemoryVT();
13838 if (!TLI
.isIndexedStoreLegal(ISD::POST_INC
, VT
) &&
13839 !TLI
.isIndexedStoreLegal(ISD::POST_DEC
, VT
))
13841 Ptr
= ST
->getBasePtr();
13847 if (Ptr
.getNode()->hasOneUse())
13850 for (SDNode
*Op
: Ptr
.getNode()->uses()) {
13852 (Op
->getOpcode() != ISD::ADD
&& Op
->getOpcode() != ISD::SUB
))
13857 ISD::MemIndexedMode AM
= ISD::UNINDEXED
;
13858 if (TLI
.getPostIndexedAddressParts(N
, Op
, BasePtr
, Offset
, AM
, DAG
)) {
13859 // Don't create a indexed load / store with zero offset.
13860 if (isNullConstant(Offset
))
13863 // Try turning it into a post-indexed load / store except when
13864 // 1) All uses are load / store ops that use it as base ptr (and
13865 // it may be folded as addressing mmode).
13866 // 2) Op must be independent of N, i.e. Op is neither a predecessor
13867 // nor a successor of N. Otherwise, if Op is folded that would
13870 if (isa
<FrameIndexSDNode
>(BasePtr
) || isa
<RegisterSDNode
>(BasePtr
))
13874 bool TryNext
= false;
13875 for (SDNode
*Use
: BasePtr
.getNode()->uses()) {
13876 if (Use
== Ptr
.getNode())
13879 // If all the uses are load / store addresses, then don't do the
13881 if (Use
->getOpcode() == ISD::ADD
|| Use
->getOpcode() == ISD::SUB
){
13882 bool RealUse
= false;
13883 for (SDNode
*UseUse
: Use
->uses()) {
13884 if (!canFoldInAddressingMode(Use
, UseUse
, DAG
, TLI
))
13899 SmallPtrSet
<const SDNode
*, 32> Visited
;
13900 SmallVector
<const SDNode
*, 8> Worklist
;
13901 // Ptr is predecessor to both N and Op.
13902 Visited
.insert(Ptr
.getNode());
13903 Worklist
.push_back(N
);
13904 Worklist
.push_back(Op
);
13905 if (!SDNode::hasPredecessorHelper(N
, Visited
, Worklist
) &&
13906 !SDNode::hasPredecessorHelper(Op
, Visited
, Worklist
)) {
13907 SDValue Result
= isLoad
13908 ? DAG
.getIndexedLoad(SDValue(N
,0), SDLoc(N
),
13909 BasePtr
, Offset
, AM
)
13910 : DAG
.getIndexedStore(SDValue(N
,0), SDLoc(N
),
13911 BasePtr
, Offset
, AM
);
13912 ++PostIndexedNodes
;
13914 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N
->dump(&DAG
);
13915 dbgs() << "\nWith: "; Result
.getNode()->dump(&DAG
);
13917 WorklistRemover
DeadNodes(*this);
13919 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(0));
13920 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Result
.getValue(2));
13922 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(1));
13925 // Finally, since the node is now dead, remove it from the graph.
13926 deleteAndRecombine(N
);
13928 // Replace the uses of Use with uses of the updated base value.
13929 DAG
.ReplaceAllUsesOfValueWith(SDValue(Op
, 0),
13930 Result
.getValue(isLoad
? 1 : 0));
13931 deleteAndRecombine(Op
);
13940 /// Return the base-pointer arithmetic from an indexed \p LD.
13941 SDValue
DAGCombiner::SplitIndexingFromLoad(LoadSDNode
*LD
) {
13942 ISD::MemIndexedMode AM
= LD
->getAddressingMode();
13943 assert(AM
!= ISD::UNINDEXED
);
13944 SDValue BP
= LD
->getOperand(1);
13945 SDValue Inc
= LD
->getOperand(2);
13947 // Some backends use TargetConstants for load offsets, but don't expect
13948 // TargetConstants in general ADD nodes. We can convert these constants into
13949 // regular Constants (if the constant is not opaque).
13950 assert((Inc
.getOpcode() != ISD::TargetConstant
||
13951 !cast
<ConstantSDNode
>(Inc
)->isOpaque()) &&
13952 "Cannot split out indexing using opaque target constants");
13953 if (Inc
.getOpcode() == ISD::TargetConstant
) {
13954 ConstantSDNode
*ConstInc
= cast
<ConstantSDNode
>(Inc
);
13955 Inc
= DAG
.getConstant(*ConstInc
->getConstantIntValue(), SDLoc(Inc
),
13956 ConstInc
->getValueType(0));
13960 (AM
== ISD::PRE_INC
|| AM
== ISD::POST_INC
? ISD::ADD
: ISD::SUB
);
13961 return DAG
.getNode(Opc
, SDLoc(LD
), BP
.getSimpleValueType(), BP
, Inc
);
13964 static inline int numVectorEltsOrZero(EVT T
) {
13965 return T
.isVector() ? T
.getVectorNumElements() : 0;
13968 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode
*ST
, SDValue
&Val
) {
13969 Val
= ST
->getValue();
13970 EVT STType
= Val
.getValueType();
13971 EVT STMemType
= ST
->getMemoryVT();
13972 if (STType
== STMemType
)
13974 if (isTypeLegal(STMemType
))
13975 return false; // fail.
13976 if (STType
.isFloatingPoint() && STMemType
.isFloatingPoint() &&
13977 TLI
.isOperationLegal(ISD::FTRUNC
, STMemType
)) {
13978 Val
= DAG
.getNode(ISD::FTRUNC
, SDLoc(ST
), STMemType
, Val
);
13981 if (numVectorEltsOrZero(STType
) == numVectorEltsOrZero(STMemType
) &&
13982 STType
.isInteger() && STMemType
.isInteger()) {
13983 Val
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(ST
), STMemType
, Val
);
13986 if (STType
.getSizeInBits() == STMemType
.getSizeInBits()) {
13987 Val
= DAG
.getBitcast(STMemType
, Val
);
13990 return false; // fail.
13993 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode
*LD
, SDValue
&Val
) {
13994 EVT LDMemType
= LD
->getMemoryVT();
13995 EVT LDType
= LD
->getValueType(0);
13996 assert(Val
.getValueType() == LDMemType
&&
13997 "Attempting to extend value of non-matching type");
13998 if (LDType
== LDMemType
)
14000 if (LDMemType
.isInteger() && LDType
.isInteger()) {
14001 switch (LD
->getExtensionType()) {
14002 case ISD::NON_EXTLOAD
:
14003 Val
= DAG
.getBitcast(LDType
, Val
);
14006 Val
= DAG
.getNode(ISD::ANY_EXTEND
, SDLoc(LD
), LDType
, Val
);
14008 case ISD::SEXTLOAD
:
14009 Val
= DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(LD
), LDType
, Val
);
14011 case ISD::ZEXTLOAD
:
14012 Val
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(LD
), LDType
, Val
);
14019 SDValue
DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode
*LD
) {
14020 if (OptLevel
== CodeGenOpt::None
|| !LD
->isSimple())
14022 SDValue Chain
= LD
->getOperand(0);
14023 StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Chain
.getNode());
14024 // TODO: Relax this restriction for unordered atomics (see D66309)
14025 if (!ST
|| !ST
->isSimple())
14028 EVT LDType
= LD
->getValueType(0);
14029 EVT LDMemType
= LD
->getMemoryVT();
14030 EVT STMemType
= ST
->getMemoryVT();
14031 EVT STType
= ST
->getValue().getValueType();
14033 BaseIndexOffset BasePtrLD
= BaseIndexOffset::match(LD
, DAG
);
14034 BaseIndexOffset BasePtrST
= BaseIndexOffset::match(ST
, DAG
);
14036 if (!BasePtrST
.equalBaseIndex(BasePtrLD
, DAG
, Offset
))
14039 // Normalize for Endianness. After this Offset=0 will denote that the least
14040 // significant bit in the loaded value maps to the least significant bit in
14041 // the stored value). With Offset=n (for n > 0) the loaded value starts at the
14042 // n:th least significant byte of the stored value.
14043 if (DAG
.getDataLayout().isBigEndian())
14044 Offset
= (STMemType
.getStoreSizeInBits() -
14045 LDMemType
.getStoreSizeInBits()) / 8 - Offset
;
14047 // Check that the stored value cover all bits that are loaded.
14050 (Offset
* 8 + LDMemType
.getSizeInBits() <= STMemType
.getSizeInBits());
14052 auto ReplaceLd
= [&](LoadSDNode
*LD
, SDValue Val
, SDValue Chain
) -> SDValue
{
14053 if (LD
->isIndexed()) {
14054 bool IsSub
= (LD
->getAddressingMode() == ISD::PRE_DEC
||
14055 LD
->getAddressingMode() == ISD::POST_DEC
);
14056 unsigned Opc
= IsSub
? ISD::SUB
: ISD::ADD
;
14057 SDValue Idx
= DAG
.getNode(Opc
, SDLoc(LD
), LD
->getOperand(1).getValueType(),
14058 LD
->getOperand(1), LD
->getOperand(2));
14059 SDValue Ops
[] = {Val
, Idx
, Chain
};
14060 return CombineTo(LD
, Ops
, 3);
14062 return CombineTo(LD
, Val
, Chain
);
14068 // Memory as copy space (potentially masked).
14069 if (Offset
== 0 && LDType
== STType
&& STMemType
== LDMemType
) {
14070 // Simple case: Direct non-truncating forwarding
14071 if (LDType
.getSizeInBits() == LDMemType
.getSizeInBits())
14072 return ReplaceLd(LD
, ST
->getValue(), Chain
);
14073 // Can we model the truncate and extension with an and mask?
14074 if (STType
.isInteger() && LDMemType
.isInteger() && !STType
.isVector() &&
14075 !LDMemType
.isVector() && LD
->getExtensionType() != ISD::SEXTLOAD
) {
14076 // Mask to size of LDMemType
14078 DAG
.getConstant(APInt::getLowBitsSet(STType
.getSizeInBits(),
14079 STMemType
.getSizeInBits()),
14080 SDLoc(ST
), STType
);
14081 auto Val
= DAG
.getNode(ISD::AND
, SDLoc(LD
), LDType
, ST
->getValue(), Mask
);
14082 return ReplaceLd(LD
, Val
, Chain
);
14086 // TODO: Deal with nonzero offset.
14087 if (LD
->getBasePtr().isUndef() || Offset
!= 0)
14089 // Model necessary truncations / extenstions.
14091 // Truncate Value To Stored Memory Size.
14093 if (!getTruncatedStoreValue(ST
, Val
))
14095 if (!isTypeLegal(LDMemType
))
14097 if (STMemType
!= LDMemType
) {
14098 // TODO: Support vectors? This requires extract_subvector/bitcast.
14099 if (!STMemType
.isVector() && !LDMemType
.isVector() &&
14100 STMemType
.isInteger() && LDMemType
.isInteger())
14101 Val
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LD
), LDMemType
, Val
);
14105 if (!extendLoadedValueToExtension(LD
, Val
))
14107 return ReplaceLd(LD
, Val
, Chain
);
14110 // On failure, cleanup dead nodes we may have created.
14111 if (Val
->use_empty())
14112 deleteAndRecombine(Val
.getNode());
14116 SDValue
DAGCombiner::visitLOAD(SDNode
*N
) {
14117 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
14118 SDValue Chain
= LD
->getChain();
14119 SDValue Ptr
= LD
->getBasePtr();
14121 // If load is not volatile and there are no uses of the loaded value (and
14122 // the updated indexed value in case of indexed loads), change uses of the
14123 // chain value into uses of the chain input (i.e. delete the dead load).
14124 // TODO: Allow this for unordered atomics (see D66309)
14125 if (LD
->isSimple()) {
14126 if (N
->getValueType(1) == MVT::Other
) {
14127 // Unindexed loads.
14128 if (!N
->hasAnyUseOfValue(0)) {
14129 // It's not safe to use the two value CombineTo variant here. e.g.
14130 // v1, chain2 = load chain1, loc
14131 // v2, chain3 = load chain2, loc
14133 // Now we replace use of chain2 with chain1. This makes the second load
14134 // isomorphic to the one we are deleting, and thus makes this load live.
14135 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N
->dump(&DAG
);
14136 dbgs() << "\nWith chain: "; Chain
.getNode()->dump(&DAG
);
14138 WorklistRemover
DeadNodes(*this);
14139 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Chain
);
14140 AddUsersToWorklist(Chain
.getNode());
14141 if (N
->use_empty())
14142 deleteAndRecombine(N
);
14144 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
14148 assert(N
->getValueType(2) == MVT::Other
&& "Malformed indexed loads?");
14150 // If this load has an opaque TargetConstant offset, then we cannot split
14151 // the indexing into an add/sub directly (that TargetConstant may not be
14152 // valid for a different type of node, and we cannot convert an opaque
14153 // target constant into a regular constant).
14154 bool HasOTCInc
= LD
->getOperand(2).getOpcode() == ISD::TargetConstant
&&
14155 cast
<ConstantSDNode
>(LD
->getOperand(2))->isOpaque();
14157 if (!N
->hasAnyUseOfValue(0) &&
14158 ((MaySplitLoadIndex
&& !HasOTCInc
) || !N
->hasAnyUseOfValue(1))) {
14159 SDValue Undef
= DAG
.getUNDEF(N
->getValueType(0));
14161 if (N
->hasAnyUseOfValue(1) && MaySplitLoadIndex
&& !HasOTCInc
) {
14162 Index
= SplitIndexingFromLoad(LD
);
14163 // Try to fold the base pointer arithmetic into subsequent loads and
14165 AddUsersToWorklist(N
);
14167 Index
= DAG
.getUNDEF(N
->getValueType(1));
14168 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N
->dump(&DAG
);
14169 dbgs() << "\nWith: "; Undef
.getNode()->dump(&DAG
);
14170 dbgs() << " and 2 other values\n");
14171 WorklistRemover
DeadNodes(*this);
14172 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Undef
);
14173 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Index
);
14174 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 2), Chain
);
14175 deleteAndRecombine(N
);
14176 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
14181 // If this load is directly stored, replace the load value with the stored
14183 if (auto V
= ForwardStoreValueToDirectLoad(LD
))
14186 // Try to infer better alignment information than the load already has.
14187 if (OptLevel
!= CodeGenOpt::None
&& LD
->isUnindexed()) {
14188 if (unsigned Align
= DAG
.InferPtrAlignment(Ptr
)) {
14189 if (Align
> LD
->getAlignment() && LD
->getSrcValueOffset() % Align
== 0) {
14190 SDValue NewLoad
= DAG
.getExtLoad(
14191 LD
->getExtensionType(), SDLoc(N
), LD
->getValueType(0), Chain
, Ptr
,
14192 LD
->getPointerInfo(), LD
->getMemoryVT(), Align
,
14193 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
14194 // NewLoad will always be N as we are only refining the alignment
14195 assert(NewLoad
.getNode() == N
);
14201 if (LD
->isUnindexed()) {
14202 // Walk up chain skipping non-aliasing memory nodes.
14203 SDValue BetterChain
= FindBetterChain(LD
, Chain
);
14205 // If there is a better chain.
14206 if (Chain
!= BetterChain
) {
14209 // Replace the chain to void dependency.
14210 if (LD
->getExtensionType() == ISD::NON_EXTLOAD
) {
14211 ReplLoad
= DAG
.getLoad(N
->getValueType(0), SDLoc(LD
),
14212 BetterChain
, Ptr
, LD
->getMemOperand());
14214 ReplLoad
= DAG
.getExtLoad(LD
->getExtensionType(), SDLoc(LD
),
14215 LD
->getValueType(0),
14216 BetterChain
, Ptr
, LD
->getMemoryVT(),
14217 LD
->getMemOperand());
14220 // Create token factor to keep old chain connected.
14221 SDValue Token
= DAG
.getNode(ISD::TokenFactor
, SDLoc(N
),
14222 MVT::Other
, Chain
, ReplLoad
.getValue(1));
14224 // Replace uses with load result and token factor
14225 return CombineTo(N
, ReplLoad
.getValue(0), Token
);
14229 // Try transforming N to an indexed load.
14230 if (CombineToPreIndexedLoadStore(N
) || CombineToPostIndexedLoadStore(N
))
14231 return SDValue(N
, 0);
14233 // Try to slice up N to more direct loads if the slices are mapped to
14234 // different register banks or pairing can take place.
14235 if (SliceUpLoad(N
))
14236 return SDValue(N
, 0);
14243 /// Helper structure used to slice a load in smaller loads.
14244 /// Basically a slice is obtained from the following sequence:
14245 /// Origin = load Ty1, Base
14246 /// Shift = srl Ty1 Origin, CstTy Amount
14247 /// Inst = trunc Shift to Ty2
14249 /// Then, it will be rewritten into:
14250 /// Slice = load SliceTy, Base + SliceOffset
14251 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
14253 /// SliceTy is deduced from the number of bits that are actually used to
14255 struct LoadedSlice
{
14256 /// Helper structure used to compute the cost of a slice.
14258 /// Are we optimizing for code size.
14259 bool ForCodeSize
= false;
14262 unsigned Loads
= 0;
14263 unsigned Truncates
= 0;
14264 unsigned CrossRegisterBanksCopies
= 0;
14265 unsigned ZExts
= 0;
14266 unsigned Shift
= 0;
14268 explicit Cost(bool ForCodeSize
) : ForCodeSize(ForCodeSize
) {}
14270 /// Get the cost of one isolated slice.
14271 Cost(const LoadedSlice
&LS
, bool ForCodeSize
)
14272 : ForCodeSize(ForCodeSize
), Loads(1) {
14273 EVT TruncType
= LS
.Inst
->getValueType(0);
14274 EVT LoadedType
= LS
.getLoadedType();
14275 if (TruncType
!= LoadedType
&&
14276 !LS
.DAG
->getTargetLoweringInfo().isZExtFree(LoadedType
, TruncType
))
14280 /// Account for slicing gain in the current cost.
14281 /// Slicing provide a few gains like removing a shift or a
14282 /// truncate. This method allows to grow the cost of the original
14283 /// load with the gain from this slice.
14284 void addSliceGain(const LoadedSlice
&LS
) {
14285 // Each slice saves a truncate.
14286 const TargetLowering
&TLI
= LS
.DAG
->getTargetLoweringInfo();
14287 if (!TLI
.isTruncateFree(LS
.Inst
->getOperand(0).getValueType(),
14288 LS
.Inst
->getValueType(0)))
14290 // If there is a shift amount, this slice gets rid of it.
14293 // If this slice can merge a cross register bank copy, account for it.
14294 if (LS
.canMergeExpensiveCrossRegisterBankCopy())
14295 ++CrossRegisterBanksCopies
;
14298 Cost
&operator+=(const Cost
&RHS
) {
14299 Loads
+= RHS
.Loads
;
14300 Truncates
+= RHS
.Truncates
;
14301 CrossRegisterBanksCopies
+= RHS
.CrossRegisterBanksCopies
;
14302 ZExts
+= RHS
.ZExts
;
14303 Shift
+= RHS
.Shift
;
14307 bool operator==(const Cost
&RHS
) const {
14308 return Loads
== RHS
.Loads
&& Truncates
== RHS
.Truncates
&&
14309 CrossRegisterBanksCopies
== RHS
.CrossRegisterBanksCopies
&&
14310 ZExts
== RHS
.ZExts
&& Shift
== RHS
.Shift
;
14313 bool operator!=(const Cost
&RHS
) const { return !(*this == RHS
); }
14315 bool operator<(const Cost
&RHS
) const {
14316 // Assume cross register banks copies are as expensive as loads.
14317 // FIXME: Do we want some more target hooks?
14318 unsigned ExpensiveOpsLHS
= Loads
+ CrossRegisterBanksCopies
;
14319 unsigned ExpensiveOpsRHS
= RHS
.Loads
+ RHS
.CrossRegisterBanksCopies
;
14320 // Unless we are optimizing for code size, consider the
14321 // expensive operation first.
14322 if (!ForCodeSize
&& ExpensiveOpsLHS
!= ExpensiveOpsRHS
)
14323 return ExpensiveOpsLHS
< ExpensiveOpsRHS
;
14324 return (Truncates
+ ZExts
+ Shift
+ ExpensiveOpsLHS
) <
14325 (RHS
.Truncates
+ RHS
.ZExts
+ RHS
.Shift
+ ExpensiveOpsRHS
);
14328 bool operator>(const Cost
&RHS
) const { return RHS
< *this; }
14330 bool operator<=(const Cost
&RHS
) const { return !(RHS
< *this); }
14332 bool operator>=(const Cost
&RHS
) const { return !(*this < RHS
); }
14335 // The last instruction that represent the slice. This should be a
14336 // truncate instruction.
14339 // The original load instruction.
14340 LoadSDNode
*Origin
;
14342 // The right shift amount in bits from the original load.
14345 // The DAG from which Origin came from.
14346 // This is used to get some contextual information about legal types, etc.
14349 LoadedSlice(SDNode
*Inst
= nullptr, LoadSDNode
*Origin
= nullptr,
14350 unsigned Shift
= 0, SelectionDAG
*DAG
= nullptr)
14351 : Inst(Inst
), Origin(Origin
), Shift(Shift
), DAG(DAG
) {}
14353 /// Get the bits used in a chunk of bits \p BitWidth large.
14354 /// \return Result is \p BitWidth and has used bits set to 1 and
14355 /// not used bits set to 0.
14356 APInt
getUsedBits() const {
14357 // Reproduce the trunc(lshr) sequence:
14358 // - Start from the truncated value.
14359 // - Zero extend to the desired bit width.
14361 assert(Origin
&& "No original load to compare against.");
14362 unsigned BitWidth
= Origin
->getValueSizeInBits(0);
14363 assert(Inst
&& "This slice is not bound to an instruction");
14364 assert(Inst
->getValueSizeInBits(0) <= BitWidth
&&
14365 "Extracted slice is bigger than the whole type!");
14366 APInt
UsedBits(Inst
->getValueSizeInBits(0), 0);
14367 UsedBits
.setAllBits();
14368 UsedBits
= UsedBits
.zext(BitWidth
);
14369 UsedBits
<<= Shift
;
14373 /// Get the size of the slice to be loaded in bytes.
14374 unsigned getLoadedSize() const {
14375 unsigned SliceSize
= getUsedBits().countPopulation();
14376 assert(!(SliceSize
& 0x7) && "Size is not a multiple of a byte.");
14377 return SliceSize
/ 8;
14380 /// Get the type that will be loaded for this slice.
14381 /// Note: This may not be the final type for the slice.
14382 EVT
getLoadedType() const {
14383 assert(DAG
&& "Missing context");
14384 LLVMContext
&Ctxt
= *DAG
->getContext();
14385 return EVT::getIntegerVT(Ctxt
, getLoadedSize() * 8);
14388 /// Get the alignment of the load used for this slice.
14389 unsigned getAlignment() const {
14390 unsigned Alignment
= Origin
->getAlignment();
14391 uint64_t Offset
= getOffsetFromBase();
14393 Alignment
= MinAlign(Alignment
, Alignment
+ Offset
);
14397 /// Check if this slice can be rewritten with legal operations.
14398 bool isLegal() const {
14399 // An invalid slice is not legal.
14400 if (!Origin
|| !Inst
|| !DAG
)
14403 // Offsets are for indexed load only, we do not handle that.
14404 if (!Origin
->getOffset().isUndef())
14407 const TargetLowering
&TLI
= DAG
->getTargetLoweringInfo();
14409 // Check that the type is legal.
14410 EVT SliceType
= getLoadedType();
14411 if (!TLI
.isTypeLegal(SliceType
))
14414 // Check that the load is legal for this type.
14415 if (!TLI
.isOperationLegal(ISD::LOAD
, SliceType
))
14418 // Check that the offset can be computed.
14419 // 1. Check its type.
14420 EVT PtrType
= Origin
->getBasePtr().getValueType();
14421 if (PtrType
== MVT::Untyped
|| PtrType
.isExtended())
14424 // 2. Check that it fits in the immediate.
14425 if (!TLI
.isLegalAddImmediate(getOffsetFromBase()))
14428 // 3. Check that the computation is legal.
14429 if (!TLI
.isOperationLegal(ISD::ADD
, PtrType
))
14432 // Check that the zext is legal if it needs one.
14433 EVT TruncateType
= Inst
->getValueType(0);
14434 if (TruncateType
!= SliceType
&&
14435 !TLI
.isOperationLegal(ISD::ZERO_EXTEND
, TruncateType
))
14441 /// Get the offset in bytes of this slice in the original chunk of
14443 /// \pre DAG != nullptr.
14444 uint64_t getOffsetFromBase() const {
14445 assert(DAG
&& "Missing context.");
14446 bool IsBigEndian
= DAG
->getDataLayout().isBigEndian();
14447 assert(!(Shift
& 0x7) && "Shifts not aligned on Bytes are not supported.");
14448 uint64_t Offset
= Shift
/ 8;
14449 unsigned TySizeInBytes
= Origin
->getValueSizeInBits(0) / 8;
14450 assert(!(Origin
->getValueSizeInBits(0) & 0x7) &&
14451 "The size of the original loaded type is not a multiple of a"
14453 // If Offset is bigger than TySizeInBytes, it means we are loading all
14454 // zeros. This should have been optimized before in the process.
14455 assert(TySizeInBytes
> Offset
&&
14456 "Invalid shift amount for given loaded size");
14458 Offset
= TySizeInBytes
- Offset
- getLoadedSize();
14462 /// Generate the sequence of instructions to load the slice
14463 /// represented by this object and redirect the uses of this slice to
14464 /// this new sequence of instructions.
14465 /// \pre this->Inst && this->Origin are valid Instructions and this
14466 /// object passed the legal check: LoadedSlice::isLegal returned true.
14467 /// \return The last instruction of the sequence used to load the slice.
14468 SDValue
loadSlice() const {
14469 assert(Inst
&& Origin
&& "Unable to replace a non-existing slice.");
14470 const SDValue
&OldBaseAddr
= Origin
->getBasePtr();
14471 SDValue BaseAddr
= OldBaseAddr
;
14472 // Get the offset in that chunk of bytes w.r.t. the endianness.
14473 int64_t Offset
= static_cast<int64_t>(getOffsetFromBase());
14474 assert(Offset
>= 0 && "Offset too big to fit in int64_t!");
14476 // BaseAddr = BaseAddr + Offset.
14477 EVT ArithType
= BaseAddr
.getValueType();
14479 BaseAddr
= DAG
->getNode(ISD::ADD
, DL
, ArithType
, BaseAddr
,
14480 DAG
->getConstant(Offset
, DL
, ArithType
));
14483 // Create the type of the loaded slice according to its size.
14484 EVT SliceType
= getLoadedType();
14486 // Create the load for the slice.
14488 DAG
->getLoad(SliceType
, SDLoc(Origin
), Origin
->getChain(), BaseAddr
,
14489 Origin
->getPointerInfo().getWithOffset(Offset
),
14490 getAlignment(), Origin
->getMemOperand()->getFlags());
14491 // If the final type is not the same as the loaded type, this means that
14492 // we have to pad with zero. Create a zero extend for that.
14493 EVT FinalType
= Inst
->getValueType(0);
14494 if (SliceType
!= FinalType
)
14496 DAG
->getNode(ISD::ZERO_EXTEND
, SDLoc(LastInst
), FinalType
, LastInst
);
14500 /// Check if this slice can be merged with an expensive cross register
14501 /// bank copy. E.g.,
14503 /// f = bitcast i32 i to float
14504 bool canMergeExpensiveCrossRegisterBankCopy() const {
14505 if (!Inst
|| !Inst
->hasOneUse())
14507 SDNode
*Use
= *Inst
->use_begin();
14508 if (Use
->getOpcode() != ISD::BITCAST
)
14510 assert(DAG
&& "Missing context");
14511 const TargetLowering
&TLI
= DAG
->getTargetLoweringInfo();
14512 EVT ResVT
= Use
->getValueType(0);
14513 const TargetRegisterClass
*ResRC
=
14514 TLI
.getRegClassFor(ResVT
.getSimpleVT(), Use
->isDivergent());
14515 const TargetRegisterClass
*ArgRC
=
14516 TLI
.getRegClassFor(Use
->getOperand(0).getValueType().getSimpleVT(),
14517 Use
->getOperand(0)->isDivergent());
14518 if (ArgRC
== ResRC
|| !TLI
.isOperationLegal(ISD::LOAD
, ResVT
))
14521 // At this point, we know that we perform a cross-register-bank copy.
14522 // Check if it is expensive.
14523 const TargetRegisterInfo
*TRI
= DAG
->getSubtarget().getRegisterInfo();
14524 // Assume bitcasts are cheap, unless both register classes do not
14525 // explicitly share a common sub class.
14526 if (!TRI
|| TRI
->getCommonSubClass(ArgRC
, ResRC
))
14529 // Check if it will be merged with the load.
14530 // 1. Check the alignment constraint.
14531 unsigned RequiredAlignment
= DAG
->getDataLayout().getABITypeAlignment(
14532 ResVT
.getTypeForEVT(*DAG
->getContext()));
14534 if (RequiredAlignment
> getAlignment())
14537 // 2. Check that the load is a legal operation for that type.
14538 if (!TLI
.isOperationLegal(ISD::LOAD
, ResVT
))
14541 // 3. Check that we do not have a zext in the way.
14542 if (Inst
->getValueType(0) != getLoadedType())
14549 } // end anonymous namespace
14551 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
14552 /// \p UsedBits looks like 0..0 1..1 0..0.
14553 static bool areUsedBitsDense(const APInt
&UsedBits
) {
14554 // If all the bits are one, this is dense!
14555 if (UsedBits
.isAllOnesValue())
14558 // Get rid of the unused bits on the right.
14559 APInt NarrowedUsedBits
= UsedBits
.lshr(UsedBits
.countTrailingZeros());
14560 // Get rid of the unused bits on the left.
14561 if (NarrowedUsedBits
.countLeadingZeros())
14562 NarrowedUsedBits
= NarrowedUsedBits
.trunc(NarrowedUsedBits
.getActiveBits());
14563 // Check that the chunk of bits is completely used.
14564 return NarrowedUsedBits
.isAllOnesValue();
14567 /// Check whether or not \p First and \p Second are next to each other
14568 /// in memory. This means that there is no hole between the bits loaded
14569 /// by \p First and the bits loaded by \p Second.
14570 static bool areSlicesNextToEachOther(const LoadedSlice
&First
,
14571 const LoadedSlice
&Second
) {
14572 assert(First
.Origin
== Second
.Origin
&& First
.Origin
&&
14573 "Unable to match different memory origins.");
14574 APInt UsedBits
= First
.getUsedBits();
14575 assert((UsedBits
& Second
.getUsedBits()) == 0 &&
14576 "Slices are not supposed to overlap.");
14577 UsedBits
|= Second
.getUsedBits();
14578 return areUsedBitsDense(UsedBits
);
14581 /// Adjust the \p GlobalLSCost according to the target
14582 /// paring capabilities and the layout of the slices.
14583 /// \pre \p GlobalLSCost should account for at least as many loads as
14584 /// there is in the slices in \p LoadedSlices.
14585 static void adjustCostForPairing(SmallVectorImpl
<LoadedSlice
> &LoadedSlices
,
14586 LoadedSlice::Cost
&GlobalLSCost
) {
14587 unsigned NumberOfSlices
= LoadedSlices
.size();
14588 // If there is less than 2 elements, no pairing is possible.
14589 if (NumberOfSlices
< 2)
14592 // Sort the slices so that elements that are likely to be next to each
14593 // other in memory are next to each other in the list.
14594 llvm::sort(LoadedSlices
, [](const LoadedSlice
&LHS
, const LoadedSlice
&RHS
) {
14595 assert(LHS
.Origin
== RHS
.Origin
&& "Different bases not implemented.");
14596 return LHS
.getOffsetFromBase() < RHS
.getOffsetFromBase();
14598 const TargetLowering
&TLI
= LoadedSlices
[0].DAG
->getTargetLoweringInfo();
14599 // First (resp. Second) is the first (resp. Second) potentially candidate
14600 // to be placed in a paired load.
14601 const LoadedSlice
*First
= nullptr;
14602 const LoadedSlice
*Second
= nullptr;
14603 for (unsigned CurrSlice
= 0; CurrSlice
< NumberOfSlices
; ++CurrSlice
,
14604 // Set the beginning of the pair.
14606 Second
= &LoadedSlices
[CurrSlice
];
14608 // If First is NULL, it means we start a new pair.
14609 // Get to the next slice.
14613 EVT LoadedType
= First
->getLoadedType();
14615 // If the types of the slices are different, we cannot pair them.
14616 if (LoadedType
!= Second
->getLoadedType())
14619 // Check if the target supplies paired loads for this type.
14620 unsigned RequiredAlignment
= 0;
14621 if (!TLI
.hasPairedLoad(LoadedType
, RequiredAlignment
)) {
14622 // move to the next pair, this type is hopeless.
14626 // Check if we meet the alignment requirement.
14627 if (RequiredAlignment
> First
->getAlignment())
14630 // Check that both loads are next to each other in memory.
14631 if (!areSlicesNextToEachOther(*First
, *Second
))
14634 assert(GlobalLSCost
.Loads
> 0 && "We save more loads than we created!");
14635 --GlobalLSCost
.Loads
;
14636 // Move to the next pair.
14641 /// Check the profitability of all involved LoadedSlice.
14642 /// Currently, it is considered profitable if there is exactly two
14643 /// involved slices (1) which are (2) next to each other in memory, and
14644 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
14646 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
14647 /// the elements themselves.
14649 /// FIXME: When the cost model will be mature enough, we can relax
14650 /// constraints (1) and (2).
14651 static bool isSlicingProfitable(SmallVectorImpl
<LoadedSlice
> &LoadedSlices
,
14652 const APInt
&UsedBits
, bool ForCodeSize
) {
14653 unsigned NumberOfSlices
= LoadedSlices
.size();
14654 if (StressLoadSlicing
)
14655 return NumberOfSlices
> 1;
14658 if (NumberOfSlices
!= 2)
14662 if (!areUsedBitsDense(UsedBits
))
14666 LoadedSlice::Cost
OrigCost(ForCodeSize
), GlobalSlicingCost(ForCodeSize
);
14667 // The original code has one big load.
14668 OrigCost
.Loads
= 1;
14669 for (unsigned CurrSlice
= 0; CurrSlice
< NumberOfSlices
; ++CurrSlice
) {
14670 const LoadedSlice
&LS
= LoadedSlices
[CurrSlice
];
14671 // Accumulate the cost of all the slices.
14672 LoadedSlice::Cost
SliceCost(LS
, ForCodeSize
);
14673 GlobalSlicingCost
+= SliceCost
;
14675 // Account as cost in the original configuration the gain obtained
14676 // with the current slices.
14677 OrigCost
.addSliceGain(LS
);
14680 // If the target supports paired load, adjust the cost accordingly.
14681 adjustCostForPairing(LoadedSlices
, GlobalSlicingCost
);
14682 return OrigCost
> GlobalSlicingCost
;
14685 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
14686 /// operations, split it in the various pieces being extracted.
14688 /// This sort of thing is introduced by SROA.
14689 /// This slicing takes care not to insert overlapping loads.
14690 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
14691 bool DAGCombiner::SliceUpLoad(SDNode
*N
) {
14692 if (Level
< AfterLegalizeDAG
)
14695 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
14696 if (!LD
->isSimple() || !ISD::isNormalLoad(LD
) ||
14697 !LD
->getValueType(0).isInteger())
14700 // Keep track of already used bits to detect overlapping values.
14701 // In that case, we will just abort the transformation.
14702 APInt
UsedBits(LD
->getValueSizeInBits(0), 0);
14704 SmallVector
<LoadedSlice
, 4> LoadedSlices
;
14706 // Check if this load is used as several smaller chunks of bits.
14707 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
14708 // of computation for each trunc.
14709 for (SDNode::use_iterator UI
= LD
->use_begin(), UIEnd
= LD
->use_end();
14710 UI
!= UIEnd
; ++UI
) {
14711 // Skip the uses of the chain.
14712 if (UI
.getUse().getResNo() != 0)
14715 SDNode
*User
= *UI
;
14716 unsigned Shift
= 0;
14718 // Check if this is a trunc(lshr).
14719 if (User
->getOpcode() == ISD::SRL
&& User
->hasOneUse() &&
14720 isa
<ConstantSDNode
>(User
->getOperand(1))) {
14721 Shift
= User
->getConstantOperandVal(1);
14722 User
= *User
->use_begin();
14725 // At this point, User is a Truncate, iff we encountered, trunc or
14727 if (User
->getOpcode() != ISD::TRUNCATE
)
14730 // The width of the type must be a power of 2 and greater than 8-bits.
14731 // Otherwise the load cannot be represented in LLVM IR.
14732 // Moreover, if we shifted with a non-8-bits multiple, the slice
14733 // will be across several bytes. We do not support that.
14734 unsigned Width
= User
->getValueSizeInBits(0);
14735 if (Width
< 8 || !isPowerOf2_32(Width
) || (Shift
& 0x7))
14738 // Build the slice for this chain of computations.
14739 LoadedSlice
LS(User
, LD
, Shift
, &DAG
);
14740 APInt CurrentUsedBits
= LS
.getUsedBits();
14742 // Check if this slice overlaps with another.
14743 if ((CurrentUsedBits
& UsedBits
) != 0)
14745 // Update the bits used globally.
14746 UsedBits
|= CurrentUsedBits
;
14748 // Check if the new slice would be legal.
14752 // Record the slice.
14753 LoadedSlices
.push_back(LS
);
14756 // Abort slicing if it does not seem to be profitable.
14757 if (!isSlicingProfitable(LoadedSlices
, UsedBits
, ForCodeSize
))
14762 // Rewrite each chain to use an independent load.
14763 // By construction, each chain can be represented by a unique load.
14765 // Prepare the argument for the new token factor for all the slices.
14766 SmallVector
<SDValue
, 8> ArgChains
;
14767 for (SmallVectorImpl
<LoadedSlice
>::const_iterator
14768 LSIt
= LoadedSlices
.begin(),
14769 LSItEnd
= LoadedSlices
.end();
14770 LSIt
!= LSItEnd
; ++LSIt
) {
14771 SDValue SliceInst
= LSIt
->loadSlice();
14772 CombineTo(LSIt
->Inst
, SliceInst
, true);
14773 if (SliceInst
.getOpcode() != ISD::LOAD
)
14774 SliceInst
= SliceInst
.getOperand(0);
14775 assert(SliceInst
->getOpcode() == ISD::LOAD
&&
14776 "It takes more than a zext to get to the loaded slice!!");
14777 ArgChains
.push_back(SliceInst
.getValue(1));
14780 SDValue Chain
= DAG
.getNode(ISD::TokenFactor
, SDLoc(LD
), MVT::Other
,
14782 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Chain
);
14783 AddToWorklist(Chain
.getNode());
14787 /// Check to see if V is (and load (ptr), imm), where the load is having
14788 /// specific bytes cleared out. If so, return the byte size being masked out
14789 /// and the shift amount.
14790 static std::pair
<unsigned, unsigned>
14791 CheckForMaskedLoad(SDValue V
, SDValue Ptr
, SDValue Chain
) {
14792 std::pair
<unsigned, unsigned> Result(0, 0);
14794 // Check for the structure we're looking for.
14795 if (V
->getOpcode() != ISD::AND
||
14796 !isa
<ConstantSDNode
>(V
->getOperand(1)) ||
14797 !ISD::isNormalLoad(V
->getOperand(0).getNode()))
14800 // Check the chain and pointer.
14801 LoadSDNode
*LD
= cast
<LoadSDNode
>(V
->getOperand(0));
14802 if (LD
->getBasePtr() != Ptr
) return Result
; // Not from same pointer.
14804 // This only handles simple types.
14805 if (V
.getValueType() != MVT::i16
&&
14806 V
.getValueType() != MVT::i32
&&
14807 V
.getValueType() != MVT::i64
)
14810 // Check the constant mask. Invert it so that the bits being masked out are
14811 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
14812 // follow the sign bit for uniformity.
14813 uint64_t NotMask
= ~cast
<ConstantSDNode
>(V
->getOperand(1))->getSExtValue();
14814 unsigned NotMaskLZ
= countLeadingZeros(NotMask
);
14815 if (NotMaskLZ
& 7) return Result
; // Must be multiple of a byte.
14816 unsigned NotMaskTZ
= countTrailingZeros(NotMask
);
14817 if (NotMaskTZ
& 7) return Result
; // Must be multiple of a byte.
14818 if (NotMaskLZ
== 64) return Result
; // All zero mask.
14820 // See if we have a continuous run of bits. If so, we have 0*1+0*
14821 if (countTrailingOnes(NotMask
>> NotMaskTZ
) + NotMaskTZ
+ NotMaskLZ
!= 64)
14824 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
14825 if (V
.getValueType() != MVT::i64
&& NotMaskLZ
)
14826 NotMaskLZ
-= 64-V
.getValueSizeInBits();
14828 unsigned MaskedBytes
= (V
.getValueSizeInBits()-NotMaskLZ
-NotMaskTZ
)/8;
14829 switch (MaskedBytes
) {
14833 default: return Result
; // All one mask, or 5-byte mask.
14836 // Verify that the first bit starts at a multiple of mask so that the access
14837 // is aligned the same as the access width.
14838 if (NotMaskTZ
&& NotMaskTZ
/8 % MaskedBytes
) return Result
;
14840 // For narrowing to be valid, it must be the case that the load the
14841 // immediately preceding memory operation before the store.
14842 if (LD
== Chain
.getNode())
14844 else if (Chain
->getOpcode() == ISD::TokenFactor
&&
14845 SDValue(LD
, 1).hasOneUse()) {
14846 // LD has only 1 chain use so they are no indirect dependencies.
14847 if (!LD
->isOperandOf(Chain
.getNode()))
14850 return Result
; // Fail.
14852 Result
.first
= MaskedBytes
;
14853 Result
.second
= NotMaskTZ
/8;
14857 /// Check to see if IVal is something that provides a value as specified by
14858 /// MaskInfo. If so, replace the specified store with a narrower store of
14859 /// truncated IVal.
14861 ShrinkLoadReplaceStoreWithStore(const std::pair
<unsigned, unsigned> &MaskInfo
,
14862 SDValue IVal
, StoreSDNode
*St
,
14864 unsigned NumBytes
= MaskInfo
.first
;
14865 unsigned ByteShift
= MaskInfo
.second
;
14866 SelectionDAG
&DAG
= DC
->getDAG();
14868 // Check to see if IVal is all zeros in the part being masked in by the 'or'
14869 // that uses this. If not, this is not a replacement.
14870 APInt Mask
= ~APInt::getBitsSet(IVal
.getValueSizeInBits(),
14871 ByteShift
*8, (ByteShift
+NumBytes
)*8);
14872 if (!DAG
.MaskedValueIsZero(IVal
, Mask
)) return SDValue();
14874 // Check that it is legal on the target to do this. It is legal if the new
14875 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
14876 // legalization (and the target doesn't explicitly think this is a bad idea).
14877 MVT VT
= MVT::getIntegerVT(NumBytes
* 8);
14878 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
14879 if (!DC
->isTypeLegal(VT
))
14881 if (St
->getMemOperand() &&
14882 !TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(), VT
,
14883 *St
->getMemOperand()))
14886 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
14887 // shifted by ByteShift and truncated down to NumBytes.
14890 IVal
= DAG
.getNode(ISD::SRL
, DL
, IVal
.getValueType(), IVal
,
14891 DAG
.getConstant(ByteShift
*8, DL
,
14892 DC
->getShiftAmountTy(IVal
.getValueType())));
14895 // Figure out the offset for the store and the alignment of the access.
14897 unsigned NewAlign
= St
->getAlignment();
14899 if (DAG
.getDataLayout().isLittleEndian())
14900 StOffset
= ByteShift
;
14902 StOffset
= IVal
.getValueType().getStoreSize() - ByteShift
- NumBytes
;
14904 SDValue Ptr
= St
->getBasePtr();
14907 Ptr
= DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(),
14908 Ptr
, DAG
.getConstant(StOffset
, DL
, Ptr
.getValueType()));
14909 NewAlign
= MinAlign(NewAlign
, StOffset
);
14912 // Truncate down to the new size.
14913 IVal
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(IVal
), VT
, IVal
);
14917 .getStore(St
->getChain(), SDLoc(St
), IVal
, Ptr
,
14918 St
->getPointerInfo().getWithOffset(StOffset
), NewAlign
);
14921 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
14922 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
14923 /// narrowing the load and store if it would end up being a win for performance
14925 SDValue
DAGCombiner::ReduceLoadOpStoreWidth(SDNode
*N
) {
14926 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
14927 if (!ST
->isSimple())
14930 SDValue Chain
= ST
->getChain();
14931 SDValue Value
= ST
->getValue();
14932 SDValue Ptr
= ST
->getBasePtr();
14933 EVT VT
= Value
.getValueType();
14935 if (ST
->isTruncatingStore() || VT
.isVector() || !Value
.hasOneUse())
14938 unsigned Opc
= Value
.getOpcode();
14940 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
14941 // is a byte mask indicating a consecutive number of bytes, check to see if
14942 // Y is known to provide just those bytes. If so, we try to replace the
14943 // load + replace + store sequence with a single (narrower) store, which makes
14945 if (Opc
== ISD::OR
) {
14946 std::pair
<unsigned, unsigned> MaskedLoad
;
14947 MaskedLoad
= CheckForMaskedLoad(Value
.getOperand(0), Ptr
, Chain
);
14948 if (MaskedLoad
.first
)
14949 if (SDValue NewST
= ShrinkLoadReplaceStoreWithStore(MaskedLoad
,
14950 Value
.getOperand(1), ST
,this))
14953 // Or is commutative, so try swapping X and Y.
14954 MaskedLoad
= CheckForMaskedLoad(Value
.getOperand(1), Ptr
, Chain
);
14955 if (MaskedLoad
.first
)
14956 if (SDValue NewST
= ShrinkLoadReplaceStoreWithStore(MaskedLoad
,
14957 Value
.getOperand(0), ST
,this))
14961 if ((Opc
!= ISD::OR
&& Opc
!= ISD::XOR
&& Opc
!= ISD::AND
) ||
14962 Value
.getOperand(1).getOpcode() != ISD::Constant
)
14965 SDValue N0
= Value
.getOperand(0);
14966 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
14967 Chain
== SDValue(N0
.getNode(), 1)) {
14968 LoadSDNode
*LD
= cast
<LoadSDNode
>(N0
);
14969 if (LD
->getBasePtr() != Ptr
||
14970 LD
->getPointerInfo().getAddrSpace() !=
14971 ST
->getPointerInfo().getAddrSpace())
14974 // Find the type to narrow it the load / op / store to.
14975 SDValue N1
= Value
.getOperand(1);
14976 unsigned BitWidth
= N1
.getValueSizeInBits();
14977 APInt Imm
= cast
<ConstantSDNode
>(N1
)->getAPIntValue();
14978 if (Opc
== ISD::AND
)
14979 Imm
^= APInt::getAllOnesValue(BitWidth
);
14980 if (Imm
== 0 || Imm
.isAllOnesValue())
14982 unsigned ShAmt
= Imm
.countTrailingZeros();
14983 unsigned MSB
= BitWidth
- Imm
.countLeadingZeros() - 1;
14984 unsigned NewBW
= NextPowerOf2(MSB
- ShAmt
);
14985 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), NewBW
);
14986 // The narrowing should be profitable, the load/store operation should be
14987 // legal (or custom) and the store size should be equal to the NewVT width.
14988 while (NewBW
< BitWidth
&&
14989 (NewVT
.getStoreSizeInBits() != NewBW
||
14990 !TLI
.isOperationLegalOrCustom(Opc
, NewVT
) ||
14991 !TLI
.isNarrowingProfitable(VT
, NewVT
))) {
14992 NewBW
= NextPowerOf2(NewBW
);
14993 NewVT
= EVT::getIntegerVT(*DAG
.getContext(), NewBW
);
14995 if (NewBW
>= BitWidth
)
14998 // If the lsb changed does not start at the type bitwidth boundary,
14999 // start at the previous one.
15001 ShAmt
= (((ShAmt
+ NewBW
- 1) / NewBW
) * NewBW
) - NewBW
;
15002 APInt Mask
= APInt::getBitsSet(BitWidth
, ShAmt
,
15003 std::min(BitWidth
, ShAmt
+ NewBW
));
15004 if ((Imm
& Mask
) == Imm
) {
15005 APInt NewImm
= (Imm
& Mask
).lshr(ShAmt
).trunc(NewBW
);
15006 if (Opc
== ISD::AND
)
15007 NewImm
^= APInt::getAllOnesValue(NewBW
);
15008 uint64_t PtrOff
= ShAmt
/ 8;
15009 // For big endian targets, we need to adjust the offset to the pointer to
15010 // load the correct bytes.
15011 if (DAG
.getDataLayout().isBigEndian())
15012 PtrOff
= (BitWidth
+ 7 - NewBW
) / 8 - PtrOff
;
15014 unsigned NewAlign
= MinAlign(LD
->getAlignment(), PtrOff
);
15015 Type
*NewVTTy
= NewVT
.getTypeForEVT(*DAG
.getContext());
15016 if (NewAlign
< DAG
.getDataLayout().getABITypeAlignment(NewVTTy
))
15019 SDValue NewPtr
= DAG
.getNode(ISD::ADD
, SDLoc(LD
),
15020 Ptr
.getValueType(), Ptr
,
15021 DAG
.getConstant(PtrOff
, SDLoc(LD
),
15022 Ptr
.getValueType()));
15024 DAG
.getLoad(NewVT
, SDLoc(N0
), LD
->getChain(), NewPtr
,
15025 LD
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
,
15026 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
15027 SDValue NewVal
= DAG
.getNode(Opc
, SDLoc(Value
), NewVT
, NewLD
,
15028 DAG
.getConstant(NewImm
, SDLoc(Value
),
15031 DAG
.getStore(Chain
, SDLoc(N
), NewVal
, NewPtr
,
15032 ST
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
);
15034 AddToWorklist(NewPtr
.getNode());
15035 AddToWorklist(NewLD
.getNode());
15036 AddToWorklist(NewVal
.getNode());
15037 WorklistRemover
DeadNodes(*this);
15038 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), NewLD
.getValue(1));
15047 /// For a given floating point load / store pair, if the load value isn't used
15048 /// by any other operations, then consider transforming the pair to integer
15049 /// load / store operations if the target deems the transformation profitable.
15050 SDValue
DAGCombiner::TransformFPLoadStorePair(SDNode
*N
) {
15051 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
15052 SDValue Value
= ST
->getValue();
15053 if (ISD::isNormalStore(ST
) && ISD::isNormalLoad(Value
.getNode()) &&
15054 Value
.hasOneUse()) {
15055 LoadSDNode
*LD
= cast
<LoadSDNode
>(Value
);
15056 EVT VT
= LD
->getMemoryVT();
15057 if (!VT
.isFloatingPoint() ||
15058 VT
!= ST
->getMemoryVT() ||
15059 LD
->isNonTemporal() ||
15060 ST
->isNonTemporal() ||
15061 LD
->getPointerInfo().getAddrSpace() != 0 ||
15062 ST
->getPointerInfo().getAddrSpace() != 0)
15065 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getSizeInBits());
15066 if (!TLI
.isOperationLegal(ISD::LOAD
, IntVT
) ||
15067 !TLI
.isOperationLegal(ISD::STORE
, IntVT
) ||
15068 !TLI
.isDesirableToTransformToIntegerOp(ISD::LOAD
, VT
) ||
15069 !TLI
.isDesirableToTransformToIntegerOp(ISD::STORE
, VT
))
15072 unsigned LDAlign
= LD
->getAlignment();
15073 unsigned STAlign
= ST
->getAlignment();
15074 Type
*IntVTTy
= IntVT
.getTypeForEVT(*DAG
.getContext());
15075 unsigned ABIAlign
= DAG
.getDataLayout().getABITypeAlignment(IntVTTy
);
15076 if (LDAlign
< ABIAlign
|| STAlign
< ABIAlign
)
15080 DAG
.getLoad(IntVT
, SDLoc(Value
), LD
->getChain(), LD
->getBasePtr(),
15081 LD
->getPointerInfo(), LDAlign
);
15084 DAG
.getStore(ST
->getChain(), SDLoc(N
), NewLD
, ST
->getBasePtr(),
15085 ST
->getPointerInfo(), STAlign
);
15087 AddToWorklist(NewLD
.getNode());
15088 AddToWorklist(NewST
.getNode());
15089 WorklistRemover
DeadNodes(*this);
15090 DAG
.ReplaceAllUsesOfValueWith(Value
.getValue(1), NewLD
.getValue(1));
15098 // This is a helper function for visitMUL to check the profitability
15099 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
15100 // MulNode is the original multiply, AddNode is (add x, c1),
15101 // and ConstNode is c2.
15103 // If the (add x, c1) has multiple uses, we could increase
15104 // the number of adds if we make this transformation.
15105 // It would only be worth doing this if we can remove a
15106 // multiply in the process. Check for that here.
15110 // We're checking for cases where we have common "c3 * A" expressions.
15111 bool DAGCombiner::isMulAddWithConstProfitable(SDNode
*MulNode
,
15113 SDValue
&ConstNode
) {
15116 // If the add only has one use, this would be OK to do.
15117 if (AddNode
.getNode()->hasOneUse())
15120 // Walk all the users of the constant with which we're multiplying.
15121 for (SDNode
*Use
: ConstNode
->uses()) {
15122 if (Use
== MulNode
) // This use is the one we're on right now. Skip it.
15125 if (Use
->getOpcode() == ISD::MUL
) { // We have another multiply use.
15127 SDNode
*MulVar
= AddNode
.getOperand(0).getNode();
15129 // OtherOp is what we're multiplying against the constant.
15130 if (Use
->getOperand(0) == ConstNode
)
15131 OtherOp
= Use
->getOperand(1).getNode();
15133 OtherOp
= Use
->getOperand(0).getNode();
15135 // Check to see if multiply is with the same operand of our "add".
15137 // ConstNode = CONST
15138 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
15140 // AddNode = (A + c1) <-- MulVar is A.
15141 // = AddNode * ConstNode <-- current visiting instruction.
15143 // If we make this transformation, we will have a common
15144 // multiply (ConstNode * A) that we can save.
15145 if (OtherOp
== MulVar
)
15148 // Now check to see if a future expansion will give us a common
15151 // ConstNode = CONST
15152 // AddNode = (A + c1)
15153 // ... = AddNode * ConstNode <-- current visiting instruction.
15155 // OtherOp = (A + c2)
15156 // Use = OtherOp * ConstNode <-- visiting Use.
15158 // If we make this transformation, we will have a common
15159 // multiply (CONST * A) after we also do the same transformation
15160 // to the "t2" instruction.
15161 if (OtherOp
->getOpcode() == ISD::ADD
&&
15162 DAG
.isConstantIntBuildVectorOrConstantInt(OtherOp
->getOperand(1)) &&
15163 OtherOp
->getOperand(0).getNode() == MulVar
)
15168 // Didn't find a case where this would be profitable.
15172 SDValue
DAGCombiner::getMergeStoreChains(SmallVectorImpl
<MemOpLink
> &StoreNodes
,
15173 unsigned NumStores
) {
15174 SmallVector
<SDValue
, 8> Chains
;
15175 SmallPtrSet
<const SDNode
*, 8> Visited
;
15176 SDLoc
StoreDL(StoreNodes
[0].MemNode
);
15178 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15179 Visited
.insert(StoreNodes
[i
].MemNode
);
15182 // don't include nodes that are children or repeated nodes.
15183 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15184 if (Visited
.insert(StoreNodes
[i
].MemNode
->getChain().getNode()).second
)
15185 Chains
.push_back(StoreNodes
[i
].MemNode
->getChain());
15188 assert(Chains
.size() > 0 && "Chain should have generated a chain");
15189 return DAG
.getTokenFactor(StoreDL
, Chains
);
15192 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
15193 SmallVectorImpl
<MemOpLink
> &StoreNodes
, EVT MemVT
, unsigned NumStores
,
15194 bool IsConstantSrc
, bool UseVector
, bool UseTrunc
) {
15195 // Make sure we have something to merge.
15199 // The latest Node in the DAG.
15200 SDLoc
DL(StoreNodes
[0].MemNode
);
15202 int64_t ElementSizeBits
= MemVT
.getStoreSizeInBits();
15203 unsigned SizeInBits
= NumStores
* ElementSizeBits
;
15204 unsigned NumMemElts
= MemVT
.isVector() ? MemVT
.getVectorNumElements() : 1;
15208 unsigned Elts
= NumStores
* NumMemElts
;
15209 // Get the type for the merged vector store.
15210 StoreTy
= EVT::getVectorVT(*DAG
.getContext(), MemVT
.getScalarType(), Elts
);
15212 StoreTy
= EVT::getIntegerVT(*DAG
.getContext(), SizeInBits
);
15216 if (IsConstantSrc
) {
15217 SmallVector
<SDValue
, 8> BuildVector
;
15218 for (unsigned I
= 0; I
!= NumStores
; ++I
) {
15219 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[I
].MemNode
);
15220 SDValue Val
= St
->getValue();
15221 // If constant is of the wrong type, convert it now.
15222 if (MemVT
!= Val
.getValueType()) {
15223 Val
= peekThroughBitcasts(Val
);
15224 // Deal with constants of wrong size.
15225 if (ElementSizeBits
!= Val
.getValueSizeInBits()) {
15227 EVT::getIntegerVT(*DAG
.getContext(), MemVT
.getSizeInBits());
15228 if (isa
<ConstantFPSDNode
>(Val
)) {
15229 // Not clear how to truncate FP values.
15231 } else if (auto *C
= dyn_cast
<ConstantSDNode
>(Val
))
15232 Val
= DAG
.getConstant(C
->getAPIntValue()
15233 .zextOrTrunc(Val
.getValueSizeInBits())
15234 .zextOrTrunc(ElementSizeBits
),
15235 SDLoc(C
), IntMemVT
);
15237 // Make sure correctly size type is the correct type.
15238 Val
= DAG
.getBitcast(MemVT
, Val
);
15240 BuildVector
.push_back(Val
);
15242 StoredVal
= DAG
.getNode(MemVT
.isVector() ? ISD::CONCAT_VECTORS
15243 : ISD::BUILD_VECTOR
,
15244 DL
, StoreTy
, BuildVector
);
15246 SmallVector
<SDValue
, 8> Ops
;
15247 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15248 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15249 SDValue Val
= peekThroughBitcasts(St
->getValue());
15250 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
15251 // type MemVT. If the underlying value is not the correct
15252 // type, but it is an extraction of an appropriate vector we
15253 // can recast Val to be of the correct type. This may require
15254 // converting between EXTRACT_VECTOR_ELT and
15255 // EXTRACT_SUBVECTOR.
15256 if ((MemVT
!= Val
.getValueType()) &&
15257 (Val
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15258 Val
.getOpcode() == ISD::EXTRACT_SUBVECTOR
)) {
15259 EVT MemVTScalarTy
= MemVT
.getScalarType();
15260 // We may need to add a bitcast here to get types to line up.
15261 if (MemVTScalarTy
!= Val
.getValueType().getScalarType()) {
15262 Val
= DAG
.getBitcast(MemVT
, Val
);
15264 unsigned OpC
= MemVT
.isVector() ? ISD::EXTRACT_SUBVECTOR
15265 : ISD::EXTRACT_VECTOR_ELT
;
15266 SDValue Vec
= Val
.getOperand(0);
15267 SDValue Idx
= Val
.getOperand(1);
15268 Val
= DAG
.getNode(OpC
, SDLoc(Val
), MemVT
, Vec
, Idx
);
15271 Ops
.push_back(Val
);
15274 // Build the extracted vector elements back into a vector.
15275 StoredVal
= DAG
.getNode(MemVT
.isVector() ? ISD::CONCAT_VECTORS
15276 : ISD::BUILD_VECTOR
,
15280 // We should always use a vector store when merging extracted vector
15281 // elements, so this path implies a store of constants.
15282 assert(IsConstantSrc
&& "Merged vector elements should use vector store");
15284 APInt
StoreInt(SizeInBits
, 0);
15286 // Construct a single integer constant which is made of the smaller
15287 // constant inputs.
15288 bool IsLE
= DAG
.getDataLayout().isLittleEndian();
15289 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15290 unsigned Idx
= IsLE
? (NumStores
- 1 - i
) : i
;
15291 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[Idx
].MemNode
);
15293 SDValue Val
= St
->getValue();
15294 Val
= peekThroughBitcasts(Val
);
15295 StoreInt
<<= ElementSizeBits
;
15296 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Val
)) {
15297 StoreInt
|= C
->getAPIntValue()
15298 .zextOrTrunc(ElementSizeBits
)
15299 .zextOrTrunc(SizeInBits
);
15300 } else if (ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(Val
)) {
15301 StoreInt
|= C
->getValueAPF()
15303 .zextOrTrunc(ElementSizeBits
)
15304 .zextOrTrunc(SizeInBits
);
15305 // If fp truncation is necessary give up for now.
15306 if (MemVT
.getSizeInBits() != ElementSizeBits
)
15309 llvm_unreachable("Invalid constant element type");
15313 // Create the new Load and Store operations.
15314 StoredVal
= DAG
.getConstant(StoreInt
, DL
, StoreTy
);
15317 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15318 SDValue NewChain
= getMergeStoreChains(StoreNodes
, NumStores
);
15320 // make sure we use trunc store if it's necessary to be legal.
15323 NewStore
= DAG
.getStore(NewChain
, DL
, StoredVal
, FirstInChain
->getBasePtr(),
15324 FirstInChain
->getPointerInfo(),
15325 FirstInChain
->getAlignment());
15326 } else { // Must be realized as a trunc store
15327 EVT LegalizedStoredValTy
=
15328 TLI
.getTypeToTransformTo(*DAG
.getContext(), StoredVal
.getValueType());
15329 unsigned LegalizedStoreSize
= LegalizedStoredValTy
.getSizeInBits();
15330 ConstantSDNode
*C
= cast
<ConstantSDNode
>(StoredVal
);
15331 SDValue ExtendedStoreVal
=
15332 DAG
.getConstant(C
->getAPIntValue().zextOrTrunc(LegalizedStoreSize
), DL
,
15333 LegalizedStoredValTy
);
15334 NewStore
= DAG
.getTruncStore(
15335 NewChain
, DL
, ExtendedStoreVal
, FirstInChain
->getBasePtr(),
15336 FirstInChain
->getPointerInfo(), StoredVal
.getValueType() /*TVT*/,
15337 FirstInChain
->getAlignment(),
15338 FirstInChain
->getMemOperand()->getFlags());
15341 // Replace all merged stores with the new store.
15342 for (unsigned i
= 0; i
< NumStores
; ++i
)
15343 CombineTo(StoreNodes
[i
].MemNode
, NewStore
);
15345 AddToWorklist(NewChain
.getNode());
15349 void DAGCombiner::getStoreMergeCandidates(
15350 StoreSDNode
*St
, SmallVectorImpl
<MemOpLink
> &StoreNodes
,
15351 SDNode
*&RootNode
) {
15352 // This holds the base pointer, index, and the offset in bytes from the base
15354 BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
15355 EVT MemVT
= St
->getMemoryVT();
15357 SDValue Val
= peekThroughBitcasts(St
->getValue());
15358 // We must have a base and an offset.
15359 if (!BasePtr
.getBase().getNode())
15362 // Do not handle stores to undef base pointers.
15363 if (BasePtr
.getBase().isUndef())
15366 bool IsConstantSrc
= isa
<ConstantSDNode
>(Val
) || isa
<ConstantFPSDNode
>(Val
);
15367 bool IsExtractVecSrc
= (Val
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15368 Val
.getOpcode() == ISD::EXTRACT_SUBVECTOR
);
15369 bool IsLoadSrc
= isa
<LoadSDNode
>(Val
);
15370 BaseIndexOffset LBasePtr
;
15371 // Match on loadbaseptr if relevant.
15374 auto *Ld
= cast
<LoadSDNode
>(Val
);
15375 LBasePtr
= BaseIndexOffset::match(Ld
, DAG
);
15376 LoadVT
= Ld
->getMemoryVT();
15377 // Load and store should be the same type.
15378 if (MemVT
!= LoadVT
)
15380 // Loads must only have one use.
15381 if (!Ld
->hasNUsesOfValue(1, 0))
15383 // The memory operands must not be volatile/indexed/atomic.
15384 // TODO: May be able to relax for unordered atomics (see D66309)
15385 if (!Ld
->isSimple() || Ld
->isIndexed())
15388 auto CandidateMatch
= [&](StoreSDNode
*Other
, BaseIndexOffset
&Ptr
,
15389 int64_t &Offset
) -> bool {
15390 // The memory operands must not be volatile/indexed/atomic.
15391 // TODO: May be able to relax for unordered atomics (see D66309)
15392 if (!Other
->isSimple() || Other
->isIndexed())
15394 // Don't mix temporal stores with non-temporal stores.
15395 if (St
->isNonTemporal() != Other
->isNonTemporal())
15397 SDValue OtherBC
= peekThroughBitcasts(Other
->getValue());
15398 // Allow merging constants of different types as integers.
15399 bool NoTypeMatch
= (MemVT
.isInteger()) ? !MemVT
.bitsEq(Other
->getMemoryVT())
15400 : Other
->getMemoryVT() != MemVT
;
15404 // The Load's Base Ptr must also match
15405 if (LoadSDNode
*OtherLd
= dyn_cast
<LoadSDNode
>(OtherBC
)) {
15406 BaseIndexOffset LPtr
= BaseIndexOffset::match(OtherLd
, DAG
);
15407 if (LoadVT
!= OtherLd
->getMemoryVT())
15409 // Loads must only have one use.
15410 if (!OtherLd
->hasNUsesOfValue(1, 0))
15412 // The memory operands must not be volatile/indexed/atomic.
15413 // TODO: May be able to relax for unordered atomics (see D66309)
15414 if (!OtherLd
->isSimple() ||
15415 OtherLd
->isIndexed())
15417 // Don't mix temporal loads with non-temporal loads.
15418 if (cast
<LoadSDNode
>(Val
)->isNonTemporal() != OtherLd
->isNonTemporal())
15420 if (!(LBasePtr
.equalBaseIndex(LPtr
, DAG
)))
15425 if (IsConstantSrc
) {
15428 if (!(isa
<ConstantSDNode
>(OtherBC
) || isa
<ConstantFPSDNode
>(OtherBC
)))
15431 if (IsExtractVecSrc
) {
15432 // Do not merge truncated stores here.
15433 if (Other
->isTruncatingStore())
15435 if (!MemVT
.bitsEq(OtherBC
.getValueType()))
15437 if (OtherBC
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
&&
15438 OtherBC
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
15441 Ptr
= BaseIndexOffset::match(Other
, DAG
);
15442 return (BasePtr
.equalBaseIndex(Ptr
, DAG
, Offset
));
15445 // Check if the pair of StoreNode and the RootNode already bail out many
15446 // times which is over the limit in dependence check.
15447 auto OverLimitInDependenceCheck
= [&](SDNode
*StoreNode
,
15448 SDNode
*RootNode
) -> bool {
15449 auto RootCount
= StoreRootCountMap
.find(StoreNode
);
15450 if (RootCount
!= StoreRootCountMap
.end() &&
15451 RootCount
->second
.first
== RootNode
&&
15452 RootCount
->second
.second
> StoreMergeDependenceLimit
)
15457 // We looking for a root node which is an ancestor to all mergable
15458 // stores. We search up through a load, to our root and then down
15459 // through all children. For instance we will find Store{1,2,3} if
15460 // St is Store1, Store2. or Store3 where the root is not a load
15461 // which always true for nonvolatile ops. TODO: Expand
15462 // the search to find all valid candidates through multiple layers of loads.
15465 // |-------|-------|
15466 // Load Load Store3
15470 // FIXME: We should be able to climb and
15471 // descend TokenFactors to find candidates as well.
15473 RootNode
= St
->getChain().getNode();
15475 unsigned NumNodesExplored
= 0;
15476 if (LoadSDNode
*Ldn
= dyn_cast
<LoadSDNode
>(RootNode
)) {
15477 RootNode
= Ldn
->getChain().getNode();
15478 for (auto I
= RootNode
->use_begin(), E
= RootNode
->use_end();
15479 I
!= E
&& NumNodesExplored
< 1024; ++I
, ++NumNodesExplored
)
15480 if (I
.getOperandNo() == 0 && isa
<LoadSDNode
>(*I
)) // walk down chain
15481 for (auto I2
= (*I
)->use_begin(), E2
= (*I
)->use_end(); I2
!= E2
; ++I2
)
15482 if (I2
.getOperandNo() == 0)
15483 if (StoreSDNode
*OtherST
= dyn_cast
<StoreSDNode
>(*I2
)) {
15484 BaseIndexOffset Ptr
;
15486 if (CandidateMatch(OtherST
, Ptr
, PtrDiff
) &&
15487 !OverLimitInDependenceCheck(OtherST
, RootNode
))
15488 StoreNodes
.push_back(MemOpLink(OtherST
, PtrDiff
));
15491 for (auto I
= RootNode
->use_begin(), E
= RootNode
->use_end();
15492 I
!= E
&& NumNodesExplored
< 1024; ++I
, ++NumNodesExplored
)
15493 if (I
.getOperandNo() == 0)
15494 if (StoreSDNode
*OtherST
= dyn_cast
<StoreSDNode
>(*I
)) {
15495 BaseIndexOffset Ptr
;
15497 if (CandidateMatch(OtherST
, Ptr
, PtrDiff
) &&
15498 !OverLimitInDependenceCheck(OtherST
, RootNode
))
15499 StoreNodes
.push_back(MemOpLink(OtherST
, PtrDiff
));
15503 // We need to check that merging these stores does not cause a loop in
15504 // the DAG. Any store candidate may depend on another candidate
15505 // indirectly through its operand (we already consider dependencies
15506 // through the chain). Check in parallel by searching up from
15507 // non-chain operands of candidates.
15508 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
15509 SmallVectorImpl
<MemOpLink
> &StoreNodes
, unsigned NumStores
,
15510 SDNode
*RootNode
) {
15511 // FIXME: We should be able to truncate a full search of
15512 // predecessors by doing a BFS and keeping tabs the originating
15513 // stores from which worklist nodes come from in a similar way to
15514 // TokenFactor simplfication.
15516 SmallPtrSet
<const SDNode
*, 32> Visited
;
15517 SmallVector
<const SDNode
*, 8> Worklist
;
15519 // RootNode is a predecessor to all candidates so we need not search
15520 // past it. Add RootNode (peeking through TokenFactors). Do not count
15521 // these towards size check.
15523 Worklist
.push_back(RootNode
);
15524 while (!Worklist
.empty()) {
15525 auto N
= Worklist
.pop_back_val();
15526 if (!Visited
.insert(N
).second
)
15527 continue; // Already present in Visited.
15528 if (N
->getOpcode() == ISD::TokenFactor
) {
15529 for (SDValue Op
: N
->ops())
15530 Worklist
.push_back(Op
.getNode());
15534 // Don't count pruning nodes towards max.
15535 unsigned int Max
= 1024 + Visited
.size();
15536 // Search Ops of store candidates.
15537 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15538 SDNode
*N
= StoreNodes
[i
].MemNode
;
15539 // Of the 4 Store Operands:
15540 // * Chain (Op 0) -> We have already considered these
15541 // in candidate selection and can be
15543 // * Value (Op 1) -> Cycles may happen (e.g. through load chains)
15544 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
15545 // but aren't necessarily fromt the same base node, so
15546 // cycles possible (e.g. via indexed store).
15547 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for
15548 // non-indexed stores). Not constant on all targets (e.g. ARM)
15549 // and so can participate in a cycle.
15550 for (unsigned j
= 1; j
< N
->getNumOperands(); ++j
)
15551 Worklist
.push_back(N
->getOperand(j
).getNode());
15553 // Search through DAG. We can stop early if we find a store node.
15554 for (unsigned i
= 0; i
< NumStores
; ++i
)
15555 if (SDNode::hasPredecessorHelper(StoreNodes
[i
].MemNode
, Visited
, Worklist
,
15557 // If the searching bail out, record the StoreNode and RootNode in the
15558 // StoreRootCountMap. If we have seen the pair many times over a limit,
15559 // we won't add the StoreNode into StoreNodes set again.
15560 if (Visited
.size() >= Max
) {
15561 auto &RootCount
= StoreRootCountMap
[StoreNodes
[i
].MemNode
];
15562 if (RootCount
.first
== RootNode
)
15563 RootCount
.second
++;
15565 RootCount
= {RootNode
, 1};
15572 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode
*St
) {
15573 if (OptLevel
== CodeGenOpt::None
|| !EnableStoreMerging
)
15576 EVT MemVT
= St
->getMemoryVT();
15577 int64_t ElementSizeBytes
= MemVT
.getStoreSize();
15578 unsigned NumMemElts
= MemVT
.isVector() ? MemVT
.getVectorNumElements() : 1;
15580 if (MemVT
.getSizeInBits() * 2 > MaximumLegalStoreInBits
)
15583 bool NoVectors
= DAG
.getMachineFunction().getFunction().hasFnAttribute(
15584 Attribute::NoImplicitFloat
);
15586 // This function cannot currently deal with non-byte-sized memory sizes.
15587 if (ElementSizeBytes
* 8 != MemVT
.getSizeInBits())
15590 if (!MemVT
.isSimple())
15593 // Perform an early exit check. Do not bother looking at stored values that
15594 // are not constants, loads, or extracted vector elements.
15595 SDValue StoredVal
= peekThroughBitcasts(St
->getValue());
15596 bool IsLoadSrc
= isa
<LoadSDNode
>(StoredVal
);
15597 bool IsConstantSrc
= isa
<ConstantSDNode
>(StoredVal
) ||
15598 isa
<ConstantFPSDNode
>(StoredVal
);
15599 bool IsExtractVecSrc
= (StoredVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15600 StoredVal
.getOpcode() == ISD::EXTRACT_SUBVECTOR
);
15601 bool IsNonTemporalStore
= St
->isNonTemporal();
15602 bool IsNonTemporalLoad
=
15603 IsLoadSrc
&& cast
<LoadSDNode
>(StoredVal
)->isNonTemporal();
15605 if (!IsConstantSrc
&& !IsLoadSrc
&& !IsExtractVecSrc
)
15608 SmallVector
<MemOpLink
, 8> StoreNodes
;
15610 // Find potential store merge candidates by searching through chain sub-DAG
15611 getStoreMergeCandidates(St
, StoreNodes
, RootNode
);
15613 // Check if there is anything to merge.
15614 if (StoreNodes
.size() < 2)
15617 // Sort the memory operands according to their distance from the
15619 llvm::sort(StoreNodes
, [](MemOpLink LHS
, MemOpLink RHS
) {
15620 return LHS
.OffsetFromBase
< RHS
.OffsetFromBase
;
15623 // Store Merge attempts to merge the lowest stores. This generally
15624 // works out as if successful, as the remaining stores are checked
15625 // after the first collection of stores is merged. However, in the
15626 // case that a non-mergeable store is found first, e.g., {p[-2],
15627 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
15628 // mergeable cases. To prevent this, we prune such stores from the
15629 // front of StoreNodes here.
15632 while (StoreNodes
.size() > 1) {
15633 size_t StartIdx
= 0;
15634 while ((StartIdx
+ 1 < StoreNodes
.size()) &&
15635 StoreNodes
[StartIdx
].OffsetFromBase
+ ElementSizeBytes
!=
15636 StoreNodes
[StartIdx
+ 1].OffsetFromBase
)
15639 // Bail if we don't have enough candidates to merge.
15640 if (StartIdx
+ 1 >= StoreNodes
.size())
15644 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + StartIdx
);
15646 // Scan the memory operations on the chain and find the first
15647 // non-consecutive store memory address.
15648 unsigned NumConsecutiveStores
= 1;
15649 int64_t StartAddress
= StoreNodes
[0].OffsetFromBase
;
15650 // Check that the addresses are consecutive starting from the second
15651 // element in the list of stores.
15652 for (unsigned i
= 1, e
= StoreNodes
.size(); i
< e
; ++i
) {
15653 int64_t CurrAddress
= StoreNodes
[i
].OffsetFromBase
;
15654 if (CurrAddress
- StartAddress
!= (ElementSizeBytes
* i
))
15656 NumConsecutiveStores
= i
+ 1;
15659 if (NumConsecutiveStores
< 2) {
15660 StoreNodes
.erase(StoreNodes
.begin(),
15661 StoreNodes
.begin() + NumConsecutiveStores
);
15665 // The node with the lowest store address.
15666 LLVMContext
&Context
= *DAG
.getContext();
15667 const DataLayout
&DL
= DAG
.getDataLayout();
15669 // Store the constants into memory as one consecutive store.
15670 if (IsConstantSrc
) {
15671 while (NumConsecutiveStores
>= 2) {
15672 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15673 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15674 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15675 unsigned LastLegalType
= 1;
15676 unsigned LastLegalVectorType
= 1;
15677 bool LastIntegerTrunc
= false;
15678 bool NonZero
= false;
15679 unsigned FirstZeroAfterNonZero
= NumConsecutiveStores
;
15680 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15681 StoreSDNode
*ST
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15682 SDValue StoredVal
= ST
->getValue();
15683 bool IsElementZero
= false;
15684 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(StoredVal
))
15685 IsElementZero
= C
->isNullValue();
15686 else if (ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(StoredVal
))
15687 IsElementZero
= C
->getConstantFPValue()->isNullValue();
15688 if (IsElementZero
) {
15689 if (NonZero
&& FirstZeroAfterNonZero
== NumConsecutiveStores
)
15690 FirstZeroAfterNonZero
= i
;
15692 NonZero
|= !IsElementZero
;
15694 // Find a legal type for the constant store.
15695 unsigned SizeInBits
= (i
+ 1) * ElementSizeBytes
* 8;
15696 EVT StoreTy
= EVT::getIntegerVT(Context
, SizeInBits
);
15697 bool IsFast
= false;
15699 // Break early when size is too large to be legal.
15700 if (StoreTy
.getSizeInBits() > MaximumLegalStoreInBits
)
15703 if (TLI
.isTypeLegal(StoreTy
) &&
15704 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15705 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15706 *FirstInChain
->getMemOperand(), &IsFast
) &&
15708 LastIntegerTrunc
= false;
15709 LastLegalType
= i
+ 1;
15710 // Or check whether a truncstore is legal.
15711 } else if (TLI
.getTypeAction(Context
, StoreTy
) ==
15712 TargetLowering::TypePromoteInteger
) {
15713 EVT LegalizedStoredValTy
=
15714 TLI
.getTypeToTransformTo(Context
, StoredVal
.getValueType());
15715 if (TLI
.isTruncStoreLegal(LegalizedStoredValTy
, StoreTy
) &&
15716 TLI
.canMergeStoresTo(FirstStoreAS
, LegalizedStoredValTy
, DAG
) &&
15717 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15718 *FirstInChain
->getMemOperand(),
15721 LastIntegerTrunc
= true;
15722 LastLegalType
= i
+ 1;
15726 // We only use vectors if the constant is known to be zero or the
15727 // target allows it and the function is not marked with the
15728 // noimplicitfloat attribute.
15730 TLI
.storeOfVectorConstantIsCheap(MemVT
, i
+ 1, FirstStoreAS
)) &&
15732 // Find a legal type for the vector store.
15733 unsigned Elts
= (i
+ 1) * NumMemElts
;
15734 EVT Ty
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
15735 if (TLI
.isTypeLegal(Ty
) && TLI
.isTypeLegal(MemVT
) &&
15736 TLI
.canMergeStoresTo(FirstStoreAS
, Ty
, DAG
) &&
15737 TLI
.allowsMemoryAccess(
15738 Context
, DL
, Ty
, *FirstInChain
->getMemOperand(), &IsFast
) &&
15740 LastLegalVectorType
= i
+ 1;
15744 bool UseVector
= (LastLegalVectorType
> LastLegalType
) && !NoVectors
;
15745 unsigned NumElem
= (UseVector
) ? LastLegalVectorType
: LastLegalType
;
15747 // Check if we found a legal integer type that creates a meaningful
15750 // We know that candidate stores are in order and of correct
15751 // shape. While there is no mergeable sequence from the
15752 // beginning one may start later in the sequence. The only
15753 // reason a merge of size N could have failed where another of
15754 // the same size would not have, is if the alignment has
15755 // improved or we've dropped a non-zero value. Drop as many
15756 // candidates as we can here.
15757 unsigned NumSkip
= 1;
15759 (NumSkip
< NumConsecutiveStores
) &&
15760 (NumSkip
< FirstZeroAfterNonZero
) &&
15761 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
15764 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
15765 NumConsecutiveStores
-= NumSkip
;
15769 // Check that we can merge these candidates without causing a cycle.
15770 if (!checkMergeStoreCandidatesForDependencies(StoreNodes
, NumElem
,
15772 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15773 NumConsecutiveStores
-= NumElem
;
15777 RV
|= MergeStoresOfConstantsOrVecElts(StoreNodes
, MemVT
, NumElem
, true,
15778 UseVector
, LastIntegerTrunc
);
15780 // Remove merged stores for next iteration.
15781 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15782 NumConsecutiveStores
-= NumElem
;
15787 // When extracting multiple vector elements, try to store them
15788 // in one vector store rather than a sequence of scalar stores.
15789 if (IsExtractVecSrc
) {
15790 // Loop on Consecutive Stores on success.
15791 while (NumConsecutiveStores
>= 2) {
15792 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15793 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15794 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15795 unsigned NumStoresToMerge
= 1;
15796 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15797 // Find a legal type for the vector store.
15798 unsigned Elts
= (i
+ 1) * NumMemElts
;
15800 EVT::getVectorVT(*DAG
.getContext(), MemVT
.getScalarType(), Elts
);
15803 // Break early when size is too large to be legal.
15804 if (Ty
.getSizeInBits() > MaximumLegalStoreInBits
)
15807 if (TLI
.isTypeLegal(Ty
) &&
15808 TLI
.canMergeStoresTo(FirstStoreAS
, Ty
, DAG
) &&
15809 TLI
.allowsMemoryAccess(Context
, DL
, Ty
,
15810 *FirstInChain
->getMemOperand(), &IsFast
) &&
15812 NumStoresToMerge
= i
+ 1;
15815 // Check if we found a legal integer type creating a meaningful
15817 if (NumStoresToMerge
< 2) {
15818 // We know that candidate stores are in order and of correct
15819 // shape. While there is no mergeable sequence from the
15820 // beginning one may start later in the sequence. The only
15821 // reason a merge of size N could have failed where another of
15822 // the same size would not have, is if the alignment has
15823 // improved. Drop as many candidates as we can here.
15824 unsigned NumSkip
= 1;
15826 (NumSkip
< NumConsecutiveStores
) &&
15827 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
15830 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
15831 NumConsecutiveStores
-= NumSkip
;
15835 // Check that we can merge these candidates without causing a cycle.
15836 if (!checkMergeStoreCandidatesForDependencies(
15837 StoreNodes
, NumStoresToMerge
, RootNode
)) {
15838 StoreNodes
.erase(StoreNodes
.begin(),
15839 StoreNodes
.begin() + NumStoresToMerge
);
15840 NumConsecutiveStores
-= NumStoresToMerge
;
15844 RV
|= MergeStoresOfConstantsOrVecElts(
15845 StoreNodes
, MemVT
, NumStoresToMerge
, false, true, false);
15847 StoreNodes
.erase(StoreNodes
.begin(),
15848 StoreNodes
.begin() + NumStoresToMerge
);
15849 NumConsecutiveStores
-= NumStoresToMerge
;
15854 // Below we handle the case of multiple consecutive stores that
15855 // come from multiple consecutive loads. We merge them into a single
15856 // wide load and a single wide store.
15858 // Look for load nodes which are used by the stored values.
15859 SmallVector
<MemOpLink
, 8> LoadNodes
;
15861 // Find acceptable loads. Loads need to have the same chain (token factor),
15862 // must not be zext, volatile, indexed, and they must be consecutive.
15863 BaseIndexOffset LdBasePtr
;
15865 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15866 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15867 SDValue Val
= peekThroughBitcasts(St
->getValue());
15868 LoadSDNode
*Ld
= cast
<LoadSDNode
>(Val
);
15870 BaseIndexOffset LdPtr
= BaseIndexOffset::match(Ld
, DAG
);
15871 // If this is not the first ptr that we check.
15872 int64_t LdOffset
= 0;
15873 if (LdBasePtr
.getBase().getNode()) {
15874 // The base ptr must be the same.
15875 if (!LdBasePtr
.equalBaseIndex(LdPtr
, DAG
, LdOffset
))
15878 // Check that all other base pointers are the same as this one.
15882 // We found a potential memory operand to merge.
15883 LoadNodes
.push_back(MemOpLink(Ld
, LdOffset
));
15886 while (NumConsecutiveStores
>= 2 && LoadNodes
.size() >= 2) {
15887 // If we have load/store pair instructions and we only have two values,
15888 // don't bother merging.
15889 unsigned RequiredAlignment
;
15890 if (LoadNodes
.size() == 2 &&
15891 TLI
.hasPairedLoad(MemVT
, RequiredAlignment
) &&
15892 StoreNodes
[0].MemNode
->getAlignment() >= RequiredAlignment
) {
15893 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + 2);
15894 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + 2);
15897 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15898 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15899 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15900 LoadSDNode
*FirstLoad
= cast
<LoadSDNode
>(LoadNodes
[0].MemNode
);
15901 unsigned FirstLoadAlign
= FirstLoad
->getAlignment();
15903 // Scan the memory operations on the chain and find the first
15904 // non-consecutive load memory address. These variables hold the index in
15905 // the store node array.
15907 unsigned LastConsecutiveLoad
= 1;
15909 // This variable refers to the size and not index in the array.
15910 unsigned LastLegalVectorType
= 1;
15911 unsigned LastLegalIntegerType
= 1;
15912 bool isDereferenceable
= true;
15913 bool DoIntegerTruncate
= false;
15914 StartAddress
= LoadNodes
[0].OffsetFromBase
;
15915 SDValue FirstChain
= FirstLoad
->getChain();
15916 for (unsigned i
= 1; i
< LoadNodes
.size(); ++i
) {
15917 // All loads must share the same chain.
15918 if (LoadNodes
[i
].MemNode
->getChain() != FirstChain
)
15921 int64_t CurrAddress
= LoadNodes
[i
].OffsetFromBase
;
15922 if (CurrAddress
- StartAddress
!= (ElementSizeBytes
* i
))
15924 LastConsecutiveLoad
= i
;
15926 if (isDereferenceable
&& !LoadNodes
[i
].MemNode
->isDereferenceable())
15927 isDereferenceable
= false;
15929 // Find a legal type for the vector store.
15930 unsigned Elts
= (i
+ 1) * NumMemElts
;
15931 EVT StoreTy
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
15933 // Break early when size is too large to be legal.
15934 if (StoreTy
.getSizeInBits() > MaximumLegalStoreInBits
)
15937 bool IsFastSt
, IsFastLd
;
15938 if (TLI
.isTypeLegal(StoreTy
) &&
15939 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15940 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15941 *FirstInChain
->getMemOperand(), &IsFastSt
) &&
15943 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15944 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15946 LastLegalVectorType
= i
+ 1;
15949 // Find a legal type for the integer store.
15950 unsigned SizeInBits
= (i
+ 1) * ElementSizeBytes
* 8;
15951 StoreTy
= EVT::getIntegerVT(Context
, SizeInBits
);
15952 if (TLI
.isTypeLegal(StoreTy
) &&
15953 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15954 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15955 *FirstInChain
->getMemOperand(), &IsFastSt
) &&
15957 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15958 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15960 LastLegalIntegerType
= i
+ 1;
15961 DoIntegerTruncate
= false;
15962 // Or check whether a truncstore and extload is legal.
15963 } else if (TLI
.getTypeAction(Context
, StoreTy
) ==
15964 TargetLowering::TypePromoteInteger
) {
15965 EVT LegalizedStoredValTy
= TLI
.getTypeToTransformTo(Context
, StoreTy
);
15966 if (TLI
.isTruncStoreLegal(LegalizedStoredValTy
, StoreTy
) &&
15967 TLI
.canMergeStoresTo(FirstStoreAS
, LegalizedStoredValTy
, DAG
) &&
15968 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LegalizedStoredValTy
,
15970 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, LegalizedStoredValTy
,
15972 TLI
.isLoadExtLegal(ISD::EXTLOAD
, LegalizedStoredValTy
, StoreTy
) &&
15973 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15974 *FirstInChain
->getMemOperand(),
15977 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15978 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15980 LastLegalIntegerType
= i
+ 1;
15981 DoIntegerTruncate
= true;
15986 // Only use vector types if the vector type is larger than the integer
15987 // type. If they are the same, use integers.
15989 LastLegalVectorType
> LastLegalIntegerType
&& !NoVectors
;
15990 unsigned LastLegalType
=
15991 std::max(LastLegalVectorType
, LastLegalIntegerType
);
15993 // We add +1 here because the LastXXX variables refer to location while
15994 // the NumElem refers to array/index size.
15996 std::min(NumConsecutiveStores
, LastConsecutiveLoad
+ 1);
15997 NumElem
= std::min(LastLegalType
, NumElem
);
16000 // We know that candidate stores are in order and of correct
16001 // shape. While there is no mergeable sequence from the
16002 // beginning one may start later in the sequence. The only
16003 // reason a merge of size N could have failed where another of
16004 // the same size would not have is if the alignment or either
16005 // the load or store has improved. Drop as many candidates as we
16007 unsigned NumSkip
= 1;
16008 while ((NumSkip
< LoadNodes
.size()) &&
16009 (LoadNodes
[NumSkip
].MemNode
->getAlignment() <= FirstLoadAlign
) &&
16010 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
16012 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
16013 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumSkip
);
16014 NumConsecutiveStores
-= NumSkip
;
16018 // Check that we can merge these candidates without causing a cycle.
16019 if (!checkMergeStoreCandidatesForDependencies(StoreNodes
, NumElem
,
16021 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
16022 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumElem
);
16023 NumConsecutiveStores
-= NumElem
;
16027 // Find if it is better to use vectors or integers to load and store
16031 // Find a legal type for the vector store.
16032 unsigned Elts
= NumElem
* NumMemElts
;
16033 JointMemOpVT
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
16035 unsigned SizeInBits
= NumElem
* ElementSizeBytes
* 8;
16036 JointMemOpVT
= EVT::getIntegerVT(Context
, SizeInBits
);
16039 SDLoc
LoadDL(LoadNodes
[0].MemNode
);
16040 SDLoc
StoreDL(StoreNodes
[0].MemNode
);
16042 // The merged loads are required to have the same incoming chain, so
16043 // using the first's chain is acceptable.
16045 SDValue NewStoreChain
= getMergeStoreChains(StoreNodes
, NumElem
);
16046 AddToWorklist(NewStoreChain
.getNode());
16048 MachineMemOperand::Flags LdMMOFlags
=
16049 isDereferenceable
? MachineMemOperand::MODereferenceable
16050 : MachineMemOperand::MONone
;
16051 if (IsNonTemporalLoad
)
16052 LdMMOFlags
|= MachineMemOperand::MONonTemporal
;
16054 MachineMemOperand::Flags StMMOFlags
=
16055 IsNonTemporalStore
? MachineMemOperand::MONonTemporal
16056 : MachineMemOperand::MONone
;
16058 SDValue NewLoad
, NewStore
;
16059 if (UseVectorTy
|| !DoIntegerTruncate
) {
16061 DAG
.getLoad(JointMemOpVT
, LoadDL
, FirstLoad
->getChain(),
16062 FirstLoad
->getBasePtr(), FirstLoad
->getPointerInfo(),
16063 FirstLoadAlign
, LdMMOFlags
);
16064 NewStore
= DAG
.getStore(
16065 NewStoreChain
, StoreDL
, NewLoad
, FirstInChain
->getBasePtr(),
16066 FirstInChain
->getPointerInfo(), FirstStoreAlign
, StMMOFlags
);
16067 } else { // This must be the truncstore/extload case
16069 TLI
.getTypeToTransformTo(*DAG
.getContext(), JointMemOpVT
);
16070 NewLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, LoadDL
, ExtendedTy
,
16071 FirstLoad
->getChain(), FirstLoad
->getBasePtr(),
16072 FirstLoad
->getPointerInfo(), JointMemOpVT
,
16073 FirstLoadAlign
, LdMMOFlags
);
16074 NewStore
= DAG
.getTruncStore(NewStoreChain
, StoreDL
, NewLoad
,
16075 FirstInChain
->getBasePtr(),
16076 FirstInChain
->getPointerInfo(),
16077 JointMemOpVT
, FirstInChain
->getAlignment(),
16078 FirstInChain
->getMemOperand()->getFlags());
16081 // Transfer chain users from old loads to the new load.
16082 for (unsigned i
= 0; i
< NumElem
; ++i
) {
16083 LoadSDNode
*Ld
= cast
<LoadSDNode
>(LoadNodes
[i
].MemNode
);
16084 DAG
.ReplaceAllUsesOfValueWith(SDValue(Ld
, 1),
16085 SDValue(NewLoad
.getNode(), 1));
16088 // Replace the all stores with the new store. Recursively remove
16089 // corresponding value if its no longer used.
16090 for (unsigned i
= 0; i
< NumElem
; ++i
) {
16091 SDValue Val
= StoreNodes
[i
].MemNode
->getOperand(1);
16092 CombineTo(StoreNodes
[i
].MemNode
, NewStore
);
16093 if (Val
.getNode()->use_empty())
16094 recursivelyDeleteUnusedNodes(Val
.getNode());
16098 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
16099 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumElem
);
16100 NumConsecutiveStores
-= NumElem
;
16106 SDValue
DAGCombiner::replaceStoreChain(StoreSDNode
*ST
, SDValue BetterChain
) {
16110 // Replace the chain to avoid dependency.
16111 if (ST
->isTruncatingStore()) {
16112 ReplStore
= DAG
.getTruncStore(BetterChain
, SL
, ST
->getValue(),
16113 ST
->getBasePtr(), ST
->getMemoryVT(),
16114 ST
->getMemOperand());
16116 ReplStore
= DAG
.getStore(BetterChain
, SL
, ST
->getValue(), ST
->getBasePtr(),
16117 ST
->getMemOperand());
16120 // Create token to keep both nodes around.
16121 SDValue Token
= DAG
.getNode(ISD::TokenFactor
, SL
,
16122 MVT::Other
, ST
->getChain(), ReplStore
);
16124 // Make sure the new and old chains are cleaned up.
16125 AddToWorklist(Token
.getNode());
16127 // Don't add users to work list.
16128 return CombineTo(ST
, Token
, false);
16131 SDValue
DAGCombiner::replaceStoreOfFPConstant(StoreSDNode
*ST
) {
16132 SDValue Value
= ST
->getValue();
16133 if (Value
.getOpcode() == ISD::TargetConstantFP
)
16138 SDValue Chain
= ST
->getChain();
16139 SDValue Ptr
= ST
->getBasePtr();
16141 const ConstantFPSDNode
*CFP
= cast
<ConstantFPSDNode
>(Value
);
16143 // NOTE: If the original store is volatile, this transform must not increase
16144 // the number of stores. For example, on x86-32 an f64 can be stored in one
16145 // processor operation but an i64 (which is not legal) requires two. So the
16146 // transform should not be done in this case.
16149 switch (CFP
->getSimpleValueType(0).SimpleTy
) {
16151 llvm_unreachable("Unknown FP type");
16152 case MVT::f16
: // We don't do this for these yet.
16158 if ((isTypeLegal(MVT::i32
) && !LegalOperations
&& ST
->isSimple()) ||
16159 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i32
)) {
16161 Tmp
= DAG
.getConstant((uint32_t)CFP
->getValueAPF().
16162 bitcastToAPInt().getZExtValue(), SDLoc(CFP
),
16164 return DAG
.getStore(Chain
, DL
, Tmp
, Ptr
, ST
->getMemOperand());
16169 if ((TLI
.isTypeLegal(MVT::i64
) && !LegalOperations
&&
16171 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i64
)) {
16173 Tmp
= DAG
.getConstant(CFP
->getValueAPF().bitcastToAPInt().
16174 getZExtValue(), SDLoc(CFP
), MVT::i64
);
16175 return DAG
.getStore(Chain
, DL
, Tmp
,
16176 Ptr
, ST
->getMemOperand());
16179 if (ST
->isSimple() &&
16180 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i32
)) {
16181 // Many FP stores are not made apparent until after legalize, e.g. for
16182 // argument passing. Since this is so common, custom legalize the
16183 // 64-bit integer store into two 32-bit stores.
16184 uint64_t Val
= CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
16185 SDValue Lo
= DAG
.getConstant(Val
& 0xFFFFFFFF, SDLoc(CFP
), MVT::i32
);
16186 SDValue Hi
= DAG
.getConstant(Val
>> 32, SDLoc(CFP
), MVT::i32
);
16187 if (DAG
.getDataLayout().isBigEndian())
16190 unsigned Alignment
= ST
->getAlignment();
16191 MachineMemOperand::Flags MMOFlags
= ST
->getMemOperand()->getFlags();
16192 AAMDNodes AAInfo
= ST
->getAAInfo();
16194 SDValue St0
= DAG
.getStore(Chain
, DL
, Lo
, Ptr
, ST
->getPointerInfo(),
16195 ST
->getAlignment(), MMOFlags
, AAInfo
);
16196 Ptr
= DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(), Ptr
,
16197 DAG
.getConstant(4, DL
, Ptr
.getValueType()));
16198 Alignment
= MinAlign(Alignment
, 4U);
16199 SDValue St1
= DAG
.getStore(Chain
, DL
, Hi
, Ptr
,
16200 ST
->getPointerInfo().getWithOffset(4),
16201 Alignment
, MMOFlags
, AAInfo
);
16202 return DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
,
16210 SDValue
DAGCombiner::visitSTORE(SDNode
*N
) {
16211 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
16212 SDValue Chain
= ST
->getChain();
16213 SDValue Value
= ST
->getValue();
16214 SDValue Ptr
= ST
->getBasePtr();
16216 // If this is a store of a bit convert, store the input value if the
16217 // resultant store does not need a higher alignment than the original.
16218 if (Value
.getOpcode() == ISD::BITCAST
&& !ST
->isTruncatingStore() &&
16219 ST
->isUnindexed()) {
16220 EVT SVT
= Value
.getOperand(0).getValueType();
16221 // If the store is volatile, we only want to change the store type if the
16222 // resulting store is legal. Otherwise we might increase the number of
16223 // memory accesses. We don't care if the original type was legal or not
16224 // as we assume software couldn't rely on the number of accesses of an
16226 // TODO: May be able to relax for unordered atomics (see D66309)
16227 if (((!LegalOperations
&& ST
->isSimple()) ||
16228 TLI
.isOperationLegal(ISD::STORE
, SVT
)) &&
16229 TLI
.isStoreBitCastBeneficial(Value
.getValueType(), SVT
,
16230 DAG
, *ST
->getMemOperand())) {
16231 return DAG
.getStore(Chain
, SDLoc(N
), Value
.getOperand(0), Ptr
,
16232 ST
->getPointerInfo(), ST
->getAlignment(),
16233 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
16237 // Turn 'store undef, Ptr' -> nothing.
16238 if (Value
.isUndef() && ST
->isUnindexed())
16241 // Try to infer better alignment information than the store already has.
16242 if (OptLevel
!= CodeGenOpt::None
&& ST
->isUnindexed()) {
16243 if (unsigned Align
= DAG
.InferPtrAlignment(Ptr
)) {
16244 if (Align
> ST
->getAlignment() && ST
->getSrcValueOffset() % Align
== 0) {
16246 DAG
.getTruncStore(Chain
, SDLoc(N
), Value
, Ptr
, ST
->getPointerInfo(),
16247 ST
->getMemoryVT(), Align
,
16248 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
16249 // NewStore will always be N as we are only refining the alignment
16250 assert(NewStore
.getNode() == N
);
16256 // Try transforming a pair floating point load / store ops to integer
16257 // load / store ops.
16258 if (SDValue NewST
= TransformFPLoadStorePair(N
))
16261 // Try transforming several stores into STORE (BSWAP).
16262 if (SDValue Store
= MatchStoreCombine(ST
))
16265 if (ST
->isUnindexed()) {
16266 // Walk up chain skipping non-aliasing memory nodes, on this store and any
16267 // adjacent stores.
16268 if (findBetterNeighborChains(ST
)) {
16269 // replaceStoreChain uses CombineTo, which handled all of the worklist
16270 // manipulation. Return the original node to not do anything else.
16271 return SDValue(ST
, 0);
16273 Chain
= ST
->getChain();
16276 // FIXME: is there such a thing as a truncating indexed store?
16277 if (ST
->isTruncatingStore() && ST
->isUnindexed() &&
16278 Value
.getValueType().isInteger() &&
16279 (!isa
<ConstantSDNode
>(Value
) ||
16280 !cast
<ConstantSDNode
>(Value
)->isOpaque())) {
16281 APInt TruncDemandedBits
=
16282 APInt::getLowBitsSet(Value
.getScalarValueSizeInBits(),
16283 ST
->getMemoryVT().getScalarSizeInBits());
16285 // See if we can simplify the input to this truncstore with knowledge that
16286 // only the low bits are being used. For example:
16287 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
16288 AddToWorklist(Value
.getNode());
16289 if (SDValue Shorter
= DAG
.GetDemandedBits(Value
, TruncDemandedBits
))
16290 return DAG
.getTruncStore(Chain
, SDLoc(N
), Shorter
, Ptr
, ST
->getMemoryVT(),
16291 ST
->getMemOperand());
16293 // Otherwise, see if we can simplify the operation with
16294 // SimplifyDemandedBits, which only works if the value has a single use.
16295 if (SimplifyDemandedBits(Value
, TruncDemandedBits
)) {
16296 // Re-visit the store if anything changed and the store hasn't been merged
16297 // with another node (N is deleted) SimplifyDemandedBits will add Value's
16298 // node back to the worklist if necessary, but we also need to re-visit
16299 // the Store node itself.
16300 if (N
->getOpcode() != ISD::DELETED_NODE
)
16302 return SDValue(N
, 0);
16306 // If this is a load followed by a store to the same location, then the store
16308 // TODO: Can relax for unordered atomics (see D66309)
16309 if (LoadSDNode
*Ld
= dyn_cast
<LoadSDNode
>(Value
)) {
16310 if (Ld
->getBasePtr() == Ptr
&& ST
->getMemoryVT() == Ld
->getMemoryVT() &&
16311 ST
->isUnindexed() && ST
->isSimple() &&
16312 // There can't be any side effects between the load and store, such as
16313 // a call or store.
16314 Chain
.reachesChainWithoutSideEffects(SDValue(Ld
, 1))) {
16315 // The store is dead, remove it.
16320 // TODO: Can relax for unordered atomics (see D66309)
16321 if (StoreSDNode
*ST1
= dyn_cast
<StoreSDNode
>(Chain
)) {
16322 if (ST
->isUnindexed() && ST
->isSimple() &&
16323 ST1
->isUnindexed() && ST1
->isSimple()) {
16324 if (ST1
->getBasePtr() == Ptr
&& ST1
->getValue() == Value
&&
16325 ST
->getMemoryVT() == ST1
->getMemoryVT()) {
16326 // If this is a store followed by a store with the same value to the
16327 // same location, then the store is dead/noop.
16331 if (OptLevel
!= CodeGenOpt::None
&& ST1
->hasOneUse() &&
16332 !ST1
->getBasePtr().isUndef()) {
16333 const BaseIndexOffset STBase
= BaseIndexOffset::match(ST
, DAG
);
16334 const BaseIndexOffset ChainBase
= BaseIndexOffset::match(ST1
, DAG
);
16335 unsigned STBitSize
= ST
->getMemoryVT().getSizeInBits();
16336 unsigned ChainBitSize
= ST1
->getMemoryVT().getSizeInBits();
16337 // If this is a store who's preceding store to a subset of the current
16338 // location and no one other node is chained to that store we can
16339 // effectively drop the store. Do not remove stores to undef as they may
16340 // be used as data sinks.
16341 if (STBase
.contains(DAG
, STBitSize
, ChainBase
, ChainBitSize
)) {
16342 CombineTo(ST1
, ST1
->getChain());
16346 // If ST stores to a subset of preceding store's write set, we may be
16347 // able to fold ST's value into the preceding stored value. As we know
16348 // the other uses of ST1's chain are unconcerned with ST, this folding
16349 // will not affect those nodes.
16351 if (ChainBase
.contains(DAG
, ChainBitSize
, STBase
, STBitSize
,
16353 SDValue ChainValue
= ST1
->getValue();
16354 if (auto *C1
= dyn_cast
<ConstantSDNode
>(ChainValue
)) {
16355 if (auto *C
= dyn_cast
<ConstantSDNode
>(Value
)) {
16356 APInt Val
= C1
->getAPIntValue();
16357 APInt InsertVal
= C
->getAPIntValue().zextOrTrunc(STBitSize
);
16358 // FIXME: Handle Big-endian mode.
16359 if (!DAG
.getDataLayout().isBigEndian()) {
16360 Val
.insertBits(InsertVal
, BitOffset
);
16362 DAG
.getConstant(Val
, SDLoc(C
), ChainValue
.getValueType(),
16363 C1
->isTargetOpcode(), C1
->isOpaque());
16364 SDNode
*NewST1
= DAG
.UpdateNodeOperands(
16365 ST1
, ST1
->getChain(), NewSDVal
, ST1
->getOperand(2),
16366 ST1
->getOperand(3));
16367 return CombineTo(ST
, SDValue(NewST1
, 0));
16371 } // End ST subset of ST1 case.
16376 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
16377 // truncating store. We can do this even if this is already a truncstore.
16378 if ((Value
.getOpcode() == ISD::FP_ROUND
|| Value
.getOpcode() == ISD::TRUNCATE
)
16379 && Value
.getNode()->hasOneUse() && ST
->isUnindexed() &&
16380 TLI
.isTruncStoreLegal(Value
.getOperand(0).getValueType(),
16381 ST
->getMemoryVT())) {
16382 return DAG
.getTruncStore(Chain
, SDLoc(N
), Value
.getOperand(0),
16383 Ptr
, ST
->getMemoryVT(), ST
->getMemOperand());
16386 // Always perform this optimization before types are legal. If the target
16387 // prefers, also try this after legalization to catch stores that were created
16388 // by intrinsics or other nodes.
16389 if (!LegalTypes
|| (TLI
.mergeStoresAfterLegalization(ST
->getMemoryVT()))) {
16391 // There can be multiple store sequences on the same chain.
16392 // Keep trying to merge store sequences until we are unable to do so
16393 // or until we merge the last store on the chain.
16394 bool Changed
= MergeConsecutiveStores(ST
);
16395 if (!Changed
) break;
16396 // Return N as merge only uses CombineTo and no worklist clean
16397 // up is necessary.
16398 if (N
->getOpcode() == ISD::DELETED_NODE
|| !isa
<StoreSDNode
>(N
))
16399 return SDValue(N
, 0);
16403 // Try transforming N to an indexed store.
16404 if (CombineToPreIndexedLoadStore(N
) || CombineToPostIndexedLoadStore(N
))
16405 return SDValue(N
, 0);
16407 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
16409 // Make sure to do this only after attempting to merge stores in order to
16410 // avoid changing the types of some subset of stores due to visit order,
16411 // preventing their merging.
16412 if (isa
<ConstantFPSDNode
>(ST
->getValue())) {
16413 if (SDValue NewSt
= replaceStoreOfFPConstant(ST
))
16417 if (SDValue NewSt
= splitMergedValStore(ST
))
16420 return ReduceLoadOpStoreWidth(N
);
16423 SDValue
DAGCombiner::visitLIFETIME_END(SDNode
*N
) {
16424 const auto *LifetimeEnd
= cast
<LifetimeSDNode
>(N
);
16425 if (!LifetimeEnd
->hasOffset())
16428 const BaseIndexOffset
LifetimeEndBase(N
->getOperand(1), SDValue(),
16429 LifetimeEnd
->getOffset(), false);
16431 // We walk up the chains to find stores.
16432 SmallVector
<SDValue
, 8> Chains
= {N
->getOperand(0)};
16433 while (!Chains
.empty()) {
16434 SDValue Chain
= Chains
.back();
16436 if (!Chain
.hasOneUse())
16438 switch (Chain
.getOpcode()) {
16439 case ISD::TokenFactor
:
16440 for (unsigned Nops
= Chain
.getNumOperands(); Nops
;)
16441 Chains
.push_back(Chain
.getOperand(--Nops
));
16443 case ISD::LIFETIME_START
:
16444 case ISD::LIFETIME_END
:
16445 // We can forward past any lifetime start/end that can be proven not to
16447 if (!isAlias(Chain
.getNode(), N
))
16448 Chains
.push_back(Chain
.getOperand(0));
16451 StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Chain
);
16452 // TODO: Can relax for unordered atomics (see D66309)
16453 if (!ST
->isSimple() || ST
->isIndexed())
16455 const BaseIndexOffset StoreBase
= BaseIndexOffset::match(ST
, DAG
);
16456 // If we store purely within object bounds just before its lifetime ends,
16457 // we can remove the store.
16458 if (LifetimeEndBase
.contains(DAG
, LifetimeEnd
->getSize() * 8, StoreBase
,
16459 ST
->getMemoryVT().getStoreSizeInBits())) {
16460 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase
.dump();
16461 dbgs() << "\nwithin LIFETIME_END of : ";
16462 LifetimeEndBase
.dump(); dbgs() << "\n");
16463 CombineTo(ST
, ST
->getChain());
16464 return SDValue(N
, 0);
16472 /// For the instruction sequence of store below, F and I values
16473 /// are bundled together as an i64 value before being stored into memory.
16474 /// Sometimes it is more efficent to generate separate stores for F and I,
16475 /// which can remove the bitwise instructions or sink them to colder places.
16477 /// (store (or (zext (bitcast F to i32) to i64),
16478 /// (shl (zext I to i64), 32)), addr) -->
16479 /// (store F, addr) and (store I, addr+4)
16481 /// Similarly, splitting for other merged store can also be beneficial, like:
16482 /// For pair of {i32, i32}, i64 store --> two i32 stores.
16483 /// For pair of {i32, i16}, i64 store --> two i32 stores.
16484 /// For pair of {i16, i16}, i32 store --> two i16 stores.
16485 /// For pair of {i16, i8}, i32 store --> two i16 stores.
16486 /// For pair of {i8, i8}, i16 store --> two i8 stores.
16488 /// We allow each target to determine specifically which kind of splitting is
16491 /// The store patterns are commonly seen from the simple code snippet below
16492 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
16493 /// void goo(const std::pair<int, float> &);
16496 /// goo(std::make_pair(tmp, ftmp));
16500 SDValue
DAGCombiner::splitMergedValStore(StoreSDNode
*ST
) {
16501 if (OptLevel
== CodeGenOpt::None
)
16504 SDValue Val
= ST
->getValue();
16507 // Match OR operand.
16508 if (!Val
.getValueType().isScalarInteger() || Val
.getOpcode() != ISD::OR
)
16511 // Match SHL operand and get Lower and Higher parts of Val.
16512 SDValue Op1
= Val
.getOperand(0);
16513 SDValue Op2
= Val
.getOperand(1);
16515 if (Op1
.getOpcode() != ISD::SHL
) {
16516 std::swap(Op1
, Op2
);
16517 if (Op1
.getOpcode() != ISD::SHL
)
16521 Hi
= Op1
.getOperand(0);
16522 if (!Op1
.hasOneUse())
16525 // Match shift amount to HalfValBitSize.
16526 unsigned HalfValBitSize
= Val
.getValueSizeInBits() / 2;
16527 ConstantSDNode
*ShAmt
= dyn_cast
<ConstantSDNode
>(Op1
.getOperand(1));
16528 if (!ShAmt
|| ShAmt
->getAPIntValue() != HalfValBitSize
)
16531 // Lo and Hi are zero-extended from int with size less equal than 32
16533 if (Lo
.getOpcode() != ISD::ZERO_EXTEND
|| !Lo
.hasOneUse() ||
16534 !Lo
.getOperand(0).getValueType().isScalarInteger() ||
16535 Lo
.getOperand(0).getValueSizeInBits() > HalfValBitSize
||
16536 Hi
.getOpcode() != ISD::ZERO_EXTEND
|| !Hi
.hasOneUse() ||
16537 !Hi
.getOperand(0).getValueType().isScalarInteger() ||
16538 Hi
.getOperand(0).getValueSizeInBits() > HalfValBitSize
)
16541 // Use the EVT of low and high parts before bitcast as the input
16542 // of target query.
16543 EVT LowTy
= (Lo
.getOperand(0).getOpcode() == ISD::BITCAST
)
16544 ? Lo
.getOperand(0).getValueType()
16545 : Lo
.getValueType();
16546 EVT HighTy
= (Hi
.getOperand(0).getOpcode() == ISD::BITCAST
)
16547 ? Hi
.getOperand(0).getValueType()
16548 : Hi
.getValueType();
16549 if (!TLI
.isMultiStoresCheaperThanBitsMerge(LowTy
, HighTy
))
16552 // Start to split store.
16553 unsigned Alignment
= ST
->getAlignment();
16554 MachineMemOperand::Flags MMOFlags
= ST
->getMemOperand()->getFlags();
16555 AAMDNodes AAInfo
= ST
->getAAInfo();
16557 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
16558 EVT VT
= EVT::getIntegerVT(*DAG
.getContext(), HalfValBitSize
);
16559 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Lo
.getOperand(0));
16560 Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Hi
.getOperand(0));
16562 SDValue Chain
= ST
->getChain();
16563 SDValue Ptr
= ST
->getBasePtr();
16564 // Lower value store.
16565 SDValue St0
= DAG
.getStore(Chain
, DL
, Lo
, Ptr
, ST
->getPointerInfo(),
16566 ST
->getAlignment(), MMOFlags
, AAInfo
);
16568 DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(), Ptr
,
16569 DAG
.getConstant(HalfValBitSize
/ 8, DL
, Ptr
.getValueType()));
16570 // Higher value store.
16572 DAG
.getStore(St0
, DL
, Hi
, Ptr
,
16573 ST
->getPointerInfo().getWithOffset(HalfValBitSize
/ 8),
16574 Alignment
/ 2, MMOFlags
, AAInfo
);
16578 /// Convert a disguised subvector insertion into a shuffle:
16579 SDValue
DAGCombiner::combineInsertEltToShuffle(SDNode
*N
, unsigned InsIndex
) {
16580 SDValue InsertVal
= N
->getOperand(1);
16581 SDValue Vec
= N
->getOperand(0);
16583 // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N), InsIndex)
16584 // --> (vector_shuffle X, Y)
16585 if (Vec
.getOpcode() == ISD::VECTOR_SHUFFLE
&& Vec
.hasOneUse() &&
16586 InsertVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
16587 isa
<ConstantSDNode
>(InsertVal
.getOperand(1))) {
16588 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Vec
.getNode());
16589 ArrayRef
<int> Mask
= SVN
->getMask();
16591 SDValue X
= Vec
.getOperand(0);
16592 SDValue Y
= Vec
.getOperand(1);
16594 // Vec's operand 0 is using indices from 0 to N-1 and
16595 // operand 1 from N to 2N - 1, where N is the number of
16596 // elements in the vectors.
16598 if (InsertVal
.getOperand(0) == X
) {
16600 } else if (InsertVal
.getOperand(0) == Y
) {
16601 XOffset
= X
.getValueType().getVectorNumElements();
16604 if (XOffset
!= -1) {
16605 SmallVector
<int, 16> NewMask(Mask
.begin(), Mask
.end());
16607 auto *ExtrIndex
= cast
<ConstantSDNode
>(InsertVal
.getOperand(1));
16608 NewMask
[InsIndex
] = XOffset
+ ExtrIndex
->getZExtValue();
16609 assert(NewMask
[InsIndex
] <
16610 (int)(2 * Vec
.getValueType().getVectorNumElements()) &&
16611 NewMask
[InsIndex
] >= 0 && "NewMask[InsIndex] is out of bound");
16613 SDValue LegalShuffle
=
16614 TLI
.buildLegalVectorShuffle(Vec
.getValueType(), SDLoc(N
), X
,
16617 return LegalShuffle
;
16621 // insert_vector_elt V, (bitcast X from vector type), IdxC -->
16622 // bitcast(shuffle (bitcast V), (extended X), Mask)
16623 // Note: We do not use an insert_subvector node because that requires a
16624 // legal subvector type.
16625 if (InsertVal
.getOpcode() != ISD::BITCAST
|| !InsertVal
.hasOneUse() ||
16626 !InsertVal
.getOperand(0).getValueType().isVector())
16629 SDValue SubVec
= InsertVal
.getOperand(0);
16630 SDValue DestVec
= N
->getOperand(0);
16631 EVT SubVecVT
= SubVec
.getValueType();
16632 EVT VT
= DestVec
.getValueType();
16633 unsigned NumSrcElts
= SubVecVT
.getVectorNumElements();
16634 unsigned ExtendRatio
= VT
.getSizeInBits() / SubVecVT
.getSizeInBits();
16635 unsigned NumMaskVals
= ExtendRatio
* NumSrcElts
;
16637 // Step 1: Create a shuffle mask that implements this insert operation. The
16638 // vector that we are inserting into will be operand 0 of the shuffle, so
16639 // those elements are just 'i'. The inserted subvector is in the first
16640 // positions of operand 1 of the shuffle. Example:
16641 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
16642 SmallVector
<int, 16> Mask(NumMaskVals
);
16643 for (unsigned i
= 0; i
!= NumMaskVals
; ++i
) {
16644 if (i
/ NumSrcElts
== InsIndex
)
16645 Mask
[i
] = (i
% NumSrcElts
) + NumMaskVals
;
16650 // Bail out if the target can not handle the shuffle we want to create.
16651 EVT SubVecEltVT
= SubVecVT
.getVectorElementType();
16652 EVT ShufVT
= EVT::getVectorVT(*DAG
.getContext(), SubVecEltVT
, NumMaskVals
);
16653 if (!TLI
.isShuffleMaskLegal(Mask
, ShufVT
))
16656 // Step 2: Create a wide vector from the inserted source vector by appending
16657 // undefined elements. This is the same size as our destination vector.
16659 SmallVector
<SDValue
, 8> ConcatOps(ExtendRatio
, DAG
.getUNDEF(SubVecVT
));
16660 ConcatOps
[0] = SubVec
;
16661 SDValue PaddedSubV
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, ShufVT
, ConcatOps
);
16663 // Step 3: Shuffle in the padded subvector.
16664 SDValue DestVecBC
= DAG
.getBitcast(ShufVT
, DestVec
);
16665 SDValue Shuf
= DAG
.getVectorShuffle(ShufVT
, DL
, DestVecBC
, PaddedSubV
, Mask
);
16666 AddToWorklist(PaddedSubV
.getNode());
16667 AddToWorklist(DestVecBC
.getNode());
16668 AddToWorklist(Shuf
.getNode());
16669 return DAG
.getBitcast(VT
, Shuf
);
16672 SDValue
DAGCombiner::visitINSERT_VECTOR_ELT(SDNode
*N
) {
16673 SDValue InVec
= N
->getOperand(0);
16674 SDValue InVal
= N
->getOperand(1);
16675 SDValue EltNo
= N
->getOperand(2);
16678 // If the inserted element is an UNDEF, just use the input vector.
16679 if (InVal
.isUndef())
16682 EVT VT
= InVec
.getValueType();
16683 unsigned NumElts
= VT
.getVectorNumElements();
16685 // Remove redundant insertions:
16686 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
16687 if (InVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
16688 InVec
== InVal
.getOperand(0) && EltNo
== InVal
.getOperand(1))
16691 auto *IndexC
= dyn_cast
<ConstantSDNode
>(EltNo
);
16693 // If this is variable insert to undef vector, it might be better to splat:
16694 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
16695 if (InVec
.isUndef() && TLI
.shouldSplatInsEltVarIndex(VT
)) {
16696 SmallVector
<SDValue
, 8> Ops(NumElts
, InVal
);
16697 return DAG
.getBuildVector(VT
, DL
, Ops
);
16702 // We must know which element is being inserted for folds below here.
16703 unsigned Elt
= IndexC
->getZExtValue();
16704 if (SDValue Shuf
= combineInsertEltToShuffle(N
, Elt
))
16707 // Canonicalize insert_vector_elt dag nodes.
16709 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
16710 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
16712 // Do this only if the child insert_vector node has one use; also
16713 // do this only if indices are both constants and Idx1 < Idx0.
16714 if (InVec
.getOpcode() == ISD::INSERT_VECTOR_ELT
&& InVec
.hasOneUse()
16715 && isa
<ConstantSDNode
>(InVec
.getOperand(2))) {
16716 unsigned OtherElt
= InVec
.getConstantOperandVal(2);
16717 if (Elt
< OtherElt
) {
16719 SDValue NewOp
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, DL
, VT
,
16720 InVec
.getOperand(0), InVal
, EltNo
);
16721 AddToWorklist(NewOp
.getNode());
16722 return DAG
.getNode(ISD::INSERT_VECTOR_ELT
, SDLoc(InVec
.getNode()),
16723 VT
, NewOp
, InVec
.getOperand(1), InVec
.getOperand(2));
16727 // If we can't generate a legal BUILD_VECTOR, exit
16728 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
16731 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
16732 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
16733 // vector elements.
16734 SmallVector
<SDValue
, 8> Ops
;
16735 // Do not combine these two vectors if the output vector will not replace
16736 // the input vector.
16737 if (InVec
.getOpcode() == ISD::BUILD_VECTOR
&& InVec
.hasOneUse()) {
16738 Ops
.append(InVec
.getNode()->op_begin(),
16739 InVec
.getNode()->op_end());
16740 } else if (InVec
.isUndef()) {
16741 Ops
.append(NumElts
, DAG
.getUNDEF(InVal
.getValueType()));
16745 assert(Ops
.size() == NumElts
&& "Unexpected vector size");
16747 // Insert the element
16748 if (Elt
< Ops
.size()) {
16749 // All the operands of BUILD_VECTOR must have the same type;
16750 // we enforce that here.
16751 EVT OpVT
= Ops
[0].getValueType();
16752 Ops
[Elt
] = OpVT
.isInteger() ? DAG
.getAnyExtOrTrunc(InVal
, DL
, OpVT
) : InVal
;
16755 // Return the new vector
16756 return DAG
.getBuildVector(VT
, DL
, Ops
);
16759 SDValue
DAGCombiner::scalarizeExtractedVectorLoad(SDNode
*EVE
, EVT InVecVT
,
16761 LoadSDNode
*OriginalLoad
) {
16762 assert(OriginalLoad
->isSimple());
16764 EVT ResultVT
= EVE
->getValueType(0);
16765 EVT VecEltVT
= InVecVT
.getVectorElementType();
16766 unsigned Align
= OriginalLoad
->getAlignment();
16767 unsigned NewAlign
= DAG
.getDataLayout().getABITypeAlignment(
16768 VecEltVT
.getTypeForEVT(*DAG
.getContext()));
16770 if (NewAlign
> Align
|| !TLI
.isOperationLegalOrCustom(ISD::LOAD
, VecEltVT
))
16773 ISD::LoadExtType ExtTy
= ResultVT
.bitsGT(VecEltVT
) ?
16774 ISD::NON_EXTLOAD
: ISD::EXTLOAD
;
16775 if (!TLI
.shouldReduceLoadWidth(OriginalLoad
, ExtTy
, VecEltVT
))
16780 SDValue NewPtr
= OriginalLoad
->getBasePtr();
16782 EVT PtrType
= NewPtr
.getValueType();
16783 MachinePointerInfo MPI
;
16785 if (auto *ConstEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
)) {
16786 int Elt
= ConstEltNo
->getZExtValue();
16787 unsigned PtrOff
= VecEltVT
.getSizeInBits() * Elt
/ 8;
16788 Offset
= DAG
.getConstant(PtrOff
, DL
, PtrType
);
16789 MPI
= OriginalLoad
->getPointerInfo().getWithOffset(PtrOff
);
16791 Offset
= DAG
.getZExtOrTrunc(EltNo
, DL
, PtrType
);
16792 Offset
= DAG
.getNode(
16793 ISD::MUL
, DL
, PtrType
, Offset
,
16794 DAG
.getConstant(VecEltVT
.getStoreSize(), DL
, PtrType
));
16795 // Discard the pointer info except the address space because the memory
16796 // operand can't represent this new access since the offset is variable.
16797 MPI
= MachinePointerInfo(OriginalLoad
->getPointerInfo().getAddrSpace());
16799 NewPtr
= DAG
.getNode(ISD::ADD
, DL
, PtrType
, NewPtr
, Offset
);
16801 // The replacement we need to do here is a little tricky: we need to
16802 // replace an extractelement of a load with a load.
16803 // Use ReplaceAllUsesOfValuesWith to do the replacement.
16804 // Note that this replacement assumes that the extractvalue is the only
16805 // use of the load; that's okay because we don't want to perform this
16806 // transformation in other cases anyway.
16809 if (ResultVT
.bitsGT(VecEltVT
)) {
16810 // If the result type of vextract is wider than the load, then issue an
16811 // extending load instead.
16812 ISD::LoadExtType ExtType
= TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, ResultVT
,
16816 Load
= DAG
.getExtLoad(ExtType
, SDLoc(EVE
), ResultVT
,
16817 OriginalLoad
->getChain(), NewPtr
, MPI
, VecEltVT
,
16818 Align
, OriginalLoad
->getMemOperand()->getFlags(),
16819 OriginalLoad
->getAAInfo());
16820 Chain
= Load
.getValue(1);
16822 Load
= DAG
.getLoad(VecEltVT
, SDLoc(EVE
), OriginalLoad
->getChain(), NewPtr
,
16823 MPI
, Align
, OriginalLoad
->getMemOperand()->getFlags(),
16824 OriginalLoad
->getAAInfo());
16825 Chain
= Load
.getValue(1);
16826 if (ResultVT
.bitsLT(VecEltVT
))
16827 Load
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(EVE
), ResultVT
, Load
);
16829 Load
= DAG
.getBitcast(ResultVT
, Load
);
16831 WorklistRemover
DeadNodes(*this);
16832 SDValue From
[] = { SDValue(EVE
, 0), SDValue(OriginalLoad
, 1) };
16833 SDValue To
[] = { Load
, Chain
};
16834 DAG
.ReplaceAllUsesOfValuesWith(From
, To
, 2);
16835 // Since we're explicitly calling ReplaceAllUses, add the new node to the
16836 // worklist explicitly as well.
16837 AddToWorklist(Load
.getNode());
16838 AddUsersToWorklist(Load
.getNode()); // Add users too
16839 // Make sure to revisit this node to clean it up; it will usually be dead.
16840 AddToWorklist(EVE
);
16842 return SDValue(EVE
, 0);
16845 /// Transform a vector binary operation into a scalar binary operation by moving
16846 /// the math/logic after an extract element of a vector.
16847 static SDValue
scalarizeExtractedBinop(SDNode
*ExtElt
, SelectionDAG
&DAG
,
16848 bool LegalOperations
) {
16849 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
16850 SDValue Vec
= ExtElt
->getOperand(0);
16851 SDValue Index
= ExtElt
->getOperand(1);
16852 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
16853 if (!IndexC
|| !TLI
.isBinOp(Vec
.getOpcode()) || !Vec
.hasOneUse() ||
16854 Vec
.getNode()->getNumValues() != 1)
16857 // Targets may want to avoid this to prevent an expensive register transfer.
16858 if (!TLI
.shouldScalarizeBinop(Vec
))
16861 // Extracting an element of a vector constant is constant-folded, so this
16862 // transform is just replacing a vector op with a scalar op while moving the
16864 SDValue Op0
= Vec
.getOperand(0);
16865 SDValue Op1
= Vec
.getOperand(1);
16866 if (isAnyConstantBuildVector(Op0
, true) ||
16867 isAnyConstantBuildVector(Op1
, true)) {
16868 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
16869 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
16871 EVT VT
= ExtElt
->getValueType(0);
16872 SDValue Ext0
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, Op0
, Index
);
16873 SDValue Ext1
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, Op1
, Index
);
16874 return DAG
.getNode(Vec
.getOpcode(), DL
, VT
, Ext0
, Ext1
);
16880 SDValue
DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode
*N
) {
16881 SDValue VecOp
= N
->getOperand(0);
16882 SDValue Index
= N
->getOperand(1);
16883 EVT ScalarVT
= N
->getValueType(0);
16884 EVT VecVT
= VecOp
.getValueType();
16885 if (VecOp
.isUndef())
16886 return DAG
.getUNDEF(ScalarVT
);
16888 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
16890 // This only really matters if the index is non-constant since other combines
16891 // on the constant elements already work.
16893 if (VecOp
.getOpcode() == ISD::INSERT_VECTOR_ELT
&&
16894 Index
== VecOp
.getOperand(2)) {
16895 SDValue Elt
= VecOp
.getOperand(1);
16896 return VecVT
.isInteger() ? DAG
.getAnyExtOrTrunc(Elt
, DL
, ScalarVT
) : Elt
;
16899 // (vextract (scalar_to_vector val, 0) -> val
16900 if (VecOp
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
16901 // Check if the result type doesn't match the inserted element type. A
16902 // SCALAR_TO_VECTOR may truncate the inserted element and the
16903 // EXTRACT_VECTOR_ELT may widen the extracted vector.
16904 SDValue InOp
= VecOp
.getOperand(0);
16905 if (InOp
.getValueType() != ScalarVT
) {
16906 assert(InOp
.getValueType().isInteger() && ScalarVT
.isInteger());
16907 return DAG
.getSExtOrTrunc(InOp
, DL
, ScalarVT
);
16912 // extract_vector_elt of out-of-bounds element -> UNDEF
16913 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
16914 unsigned NumElts
= VecVT
.getVectorNumElements();
16915 if (IndexC
&& IndexC
->getAPIntValue().uge(NumElts
))
16916 return DAG
.getUNDEF(ScalarVT
);
16918 // extract_vector_elt (build_vector x, y), 1 -> y
16919 if (IndexC
&& VecOp
.getOpcode() == ISD::BUILD_VECTOR
&&
16920 TLI
.isTypeLegal(VecVT
) &&
16921 (VecOp
.hasOneUse() || TLI
.aggressivelyPreferBuildVectorSources(VecVT
))) {
16922 SDValue Elt
= VecOp
.getOperand(IndexC
->getZExtValue());
16923 EVT InEltVT
= Elt
.getValueType();
16925 // Sometimes build_vector's scalar input types do not match result type.
16926 if (ScalarVT
== InEltVT
)
16929 // TODO: It may be useful to truncate if free if the build_vector implicitly
16933 // TODO: These transforms should not require the 'hasOneUse' restriction, but
16934 // there are regressions on multiple targets without it. We can end up with a
16935 // mess of scalar and vector code if we reduce only part of the DAG to scalar.
16936 if (IndexC
&& VecOp
.getOpcode() == ISD::BITCAST
&& VecVT
.isInteger() &&
16937 VecOp
.hasOneUse()) {
16938 // The vector index of the LSBs of the source depend on the endian-ness.
16939 bool IsLE
= DAG
.getDataLayout().isLittleEndian();
16940 unsigned ExtractIndex
= IndexC
->getZExtValue();
16941 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
16942 unsigned BCTruncElt
= IsLE
? 0 : NumElts
- 1;
16943 SDValue BCSrc
= VecOp
.getOperand(0);
16944 if (ExtractIndex
== BCTruncElt
&& BCSrc
.getValueType().isScalarInteger())
16945 return DAG
.getNode(ISD::TRUNCATE
, DL
, ScalarVT
, BCSrc
);
16947 if (LegalTypes
&& BCSrc
.getValueType().isInteger() &&
16948 BCSrc
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
16949 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
16950 // trunc i64 X to i32
16951 SDValue X
= BCSrc
.getOperand(0);
16952 assert(X
.getValueType().isScalarInteger() && ScalarVT
.isScalarInteger() &&
16953 "Extract element and scalar to vector can't change element type "
16954 "from FP to integer.");
16955 unsigned XBitWidth
= X
.getValueSizeInBits();
16956 unsigned VecEltBitWidth
= VecVT
.getScalarSizeInBits();
16957 BCTruncElt
= IsLE
? 0 : XBitWidth
/ VecEltBitWidth
- 1;
16959 // An extract element return value type can be wider than its vector
16960 // operand element type. In that case, the high bits are undefined, so
16961 // it's possible that we may need to extend rather than truncate.
16962 if (ExtractIndex
== BCTruncElt
&& XBitWidth
> VecEltBitWidth
) {
16963 assert(XBitWidth
% VecEltBitWidth
== 0 &&
16964 "Scalar bitwidth must be a multiple of vector element bitwidth");
16965 return DAG
.getAnyExtOrTrunc(X
, DL
, ScalarVT
);
16970 if (SDValue BO
= scalarizeExtractedBinop(N
, DAG
, LegalOperations
))
16973 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
16974 // We only perform this optimization before the op legalization phase because
16975 // we may introduce new vector instructions which are not backed by TD
16976 // patterns. For example on AVX, extracting elements from a wide vector
16977 // without using extract_subvector. However, if we can find an underlying
16978 // scalar value, then we can always use that.
16979 if (IndexC
&& VecOp
.getOpcode() == ISD::VECTOR_SHUFFLE
) {
16980 auto *Shuf
= cast
<ShuffleVectorSDNode
>(VecOp
);
16981 // Find the new index to extract from.
16982 int OrigElt
= Shuf
->getMaskElt(IndexC
->getZExtValue());
16984 // Extracting an undef index is undef.
16986 return DAG
.getUNDEF(ScalarVT
);
16988 // Select the right vector half to extract from.
16990 if (OrigElt
< (int)NumElts
) {
16991 SVInVec
= VecOp
.getOperand(0);
16993 SVInVec
= VecOp
.getOperand(1);
16994 OrigElt
-= NumElts
;
16997 if (SVInVec
.getOpcode() == ISD::BUILD_VECTOR
) {
16998 SDValue InOp
= SVInVec
.getOperand(OrigElt
);
16999 if (InOp
.getValueType() != ScalarVT
) {
17000 assert(InOp
.getValueType().isInteger() && ScalarVT
.isInteger());
17001 InOp
= DAG
.getSExtOrTrunc(InOp
, DL
, ScalarVT
);
17007 // FIXME: We should handle recursing on other vector shuffles and
17008 // scalar_to_vector here as well.
17010 if (!LegalOperations
||
17011 // FIXME: Should really be just isOperationLegalOrCustom.
17012 TLI
.isOperationLegal(ISD::EXTRACT_VECTOR_ELT
, VecVT
) ||
17013 TLI
.isOperationExpand(ISD::VECTOR_SHUFFLE
, VecVT
)) {
17014 EVT IndexTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
17015 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ScalarVT
, SVInVec
,
17016 DAG
.getConstant(OrigElt
, DL
, IndexTy
));
17020 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
17021 // simplify it based on the (valid) extraction indices.
17022 if (llvm::all_of(VecOp
->uses(), [&](SDNode
*Use
) {
17023 return Use
->getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
17024 Use
->getOperand(0) == VecOp
&&
17025 isa
<ConstantSDNode
>(Use
->getOperand(1));
17027 APInt DemandedElts
= APInt::getNullValue(NumElts
);
17028 for (SDNode
*Use
: VecOp
->uses()) {
17029 auto *CstElt
= cast
<ConstantSDNode
>(Use
->getOperand(1));
17030 if (CstElt
->getAPIntValue().ult(NumElts
))
17031 DemandedElts
.setBit(CstElt
->getZExtValue());
17033 if (SimplifyDemandedVectorElts(VecOp
, DemandedElts
, true)) {
17034 // We simplified the vector operand of this extract element. If this
17035 // extract is not dead, visit it again so it is folded properly.
17036 if (N
->getOpcode() != ISD::DELETED_NODE
)
17038 return SDValue(N
, 0);
17042 // Everything under here is trying to match an extract of a loaded value.
17043 // If the result of load has to be truncated, then it's not necessarily
17045 bool BCNumEltsChanged
= false;
17046 EVT ExtVT
= VecVT
.getVectorElementType();
17048 if (ScalarVT
.bitsLT(LVT
) && !TLI
.isTruncateFree(LVT
, ScalarVT
))
17051 if (VecOp
.getOpcode() == ISD::BITCAST
) {
17052 // Don't duplicate a load with other uses.
17053 if (!VecOp
.hasOneUse())
17056 EVT BCVT
= VecOp
.getOperand(0).getValueType();
17057 if (!BCVT
.isVector() || ExtVT
.bitsGT(BCVT
.getVectorElementType()))
17059 if (NumElts
!= BCVT
.getVectorNumElements())
17060 BCNumEltsChanged
= true;
17061 VecOp
= VecOp
.getOperand(0);
17062 ExtVT
= BCVT
.getVectorElementType();
17065 // extract (vector load $addr), i --> load $addr + i * size
17066 if (!LegalOperations
&& !IndexC
&& VecOp
.hasOneUse() &&
17067 ISD::isNormalLoad(VecOp
.getNode()) &&
17068 !Index
->hasPredecessor(VecOp
.getNode())) {
17069 auto *VecLoad
= dyn_cast
<LoadSDNode
>(VecOp
);
17070 if (VecLoad
&& VecLoad
->isSimple())
17071 return scalarizeExtractedVectorLoad(N
, VecVT
, Index
, VecLoad
);
17074 // Perform only after legalization to ensure build_vector / vector_shuffle
17075 // optimizations have already been done.
17076 if (!LegalOperations
|| !IndexC
)
17079 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
17080 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
17081 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
17082 int Elt
= IndexC
->getZExtValue();
17083 LoadSDNode
*LN0
= nullptr;
17084 if (ISD::isNormalLoad(VecOp
.getNode())) {
17085 LN0
= cast
<LoadSDNode
>(VecOp
);
17086 } else if (VecOp
.getOpcode() == ISD::SCALAR_TO_VECTOR
&&
17087 VecOp
.getOperand(0).getValueType() == ExtVT
&&
17088 ISD::isNormalLoad(VecOp
.getOperand(0).getNode())) {
17089 // Don't duplicate a load with other uses.
17090 if (!VecOp
.hasOneUse())
17093 LN0
= cast
<LoadSDNode
>(VecOp
.getOperand(0));
17095 if (auto *Shuf
= dyn_cast
<ShuffleVectorSDNode
>(VecOp
)) {
17096 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
17098 // (load $addr+1*size)
17100 // Don't duplicate a load with other uses.
17101 if (!VecOp
.hasOneUse())
17104 // If the bit convert changed the number of elements, it is unsafe
17105 // to examine the mask.
17106 if (BCNumEltsChanged
)
17109 // Select the input vector, guarding against out of range extract vector.
17110 int Idx
= (Elt
> (int)NumElts
) ? -1 : Shuf
->getMaskElt(Elt
);
17111 VecOp
= (Idx
< (int)NumElts
) ? VecOp
.getOperand(0) : VecOp
.getOperand(1);
17113 if (VecOp
.getOpcode() == ISD::BITCAST
) {
17114 // Don't duplicate a load with other uses.
17115 if (!VecOp
.hasOneUse())
17118 VecOp
= VecOp
.getOperand(0);
17120 if (ISD::isNormalLoad(VecOp
.getNode())) {
17121 LN0
= cast
<LoadSDNode
>(VecOp
);
17122 Elt
= (Idx
< (int)NumElts
) ? Idx
: Idx
- (int)NumElts
;
17123 Index
= DAG
.getConstant(Elt
, DL
, Index
.getValueType());
17127 // Make sure we found a non-volatile load and the extractelement is
17129 if (!LN0
|| !LN0
->hasNUsesOfValue(1,0) || !LN0
->isSimple())
17132 // If Idx was -1 above, Elt is going to be -1, so just return undef.
17134 return DAG
.getUNDEF(LVT
);
17136 return scalarizeExtractedVectorLoad(N
, VecVT
, Index
, LN0
);
17139 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
17140 SDValue
DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode
*N
) {
17141 // We perform this optimization post type-legalization because
17142 // the type-legalizer often scalarizes integer-promoted vectors.
17143 // Performing this optimization before may create bit-casts which
17144 // will be type-legalized to complex code sequences.
17145 // We perform this optimization only before the operation legalizer because we
17146 // may introduce illegal operations.
17147 if (Level
!= AfterLegalizeVectorOps
&& Level
!= AfterLegalizeTypes
)
17150 unsigned NumInScalars
= N
->getNumOperands();
17152 EVT VT
= N
->getValueType(0);
17154 // Check to see if this is a BUILD_VECTOR of a bunch of values
17155 // which come from any_extend or zero_extend nodes. If so, we can create
17156 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
17157 // optimizations. We do not handle sign-extend because we can't fill the sign
17159 EVT SourceType
= MVT::Other
;
17160 bool AllAnyExt
= true;
17162 for (unsigned i
= 0; i
!= NumInScalars
; ++i
) {
17163 SDValue In
= N
->getOperand(i
);
17164 // Ignore undef inputs.
17165 if (In
.isUndef()) continue;
17167 bool AnyExt
= In
.getOpcode() == ISD::ANY_EXTEND
;
17168 bool ZeroExt
= In
.getOpcode() == ISD::ZERO_EXTEND
;
17170 // Abort if the element is not an extension.
17171 if (!ZeroExt
&& !AnyExt
) {
17172 SourceType
= MVT::Other
;
17176 // The input is a ZeroExt or AnyExt. Check the original type.
17177 EVT InTy
= In
.getOperand(0).getValueType();
17179 // Check that all of the widened source types are the same.
17180 if (SourceType
== MVT::Other
)
17183 else if (InTy
!= SourceType
) {
17184 // Multiple income types. Abort.
17185 SourceType
= MVT::Other
;
17189 // Check if all of the extends are ANY_EXTENDs.
17190 AllAnyExt
&= AnyExt
;
17193 // In order to have valid types, all of the inputs must be extended from the
17194 // same source type and all of the inputs must be any or zero extend.
17195 // Scalar sizes must be a power of two.
17196 EVT OutScalarTy
= VT
.getScalarType();
17197 bool ValidTypes
= SourceType
!= MVT::Other
&&
17198 isPowerOf2_32(OutScalarTy
.getSizeInBits()) &&
17199 isPowerOf2_32(SourceType
.getSizeInBits());
17201 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
17202 // turn into a single shuffle instruction.
17206 bool isLE
= DAG
.getDataLayout().isLittleEndian();
17207 unsigned ElemRatio
= OutScalarTy
.getSizeInBits()/SourceType
.getSizeInBits();
17208 assert(ElemRatio
> 1 && "Invalid element size ratio");
17209 SDValue Filler
= AllAnyExt
? DAG
.getUNDEF(SourceType
):
17210 DAG
.getConstant(0, DL
, SourceType
);
17212 unsigned NewBVElems
= ElemRatio
* VT
.getVectorNumElements();
17213 SmallVector
<SDValue
, 8> Ops(NewBVElems
, Filler
);
17215 // Populate the new build_vector
17216 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
17217 SDValue Cast
= N
->getOperand(i
);
17218 assert((Cast
.getOpcode() == ISD::ANY_EXTEND
||
17219 Cast
.getOpcode() == ISD::ZERO_EXTEND
||
17220 Cast
.isUndef()) && "Invalid cast opcode");
17222 if (Cast
.isUndef())
17223 In
= DAG
.getUNDEF(SourceType
);
17225 In
= Cast
->getOperand(0);
17226 unsigned Index
= isLE
? (i
* ElemRatio
) :
17227 (i
* ElemRatio
+ (ElemRatio
- 1));
17229 assert(Index
< Ops
.size() && "Invalid index");
17233 // The type of the new BUILD_VECTOR node.
17234 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), SourceType
, NewBVElems
);
17235 assert(VecVT
.getSizeInBits() == VT
.getSizeInBits() &&
17236 "Invalid vector size");
17237 // Check if the new vector type is legal.
17238 if (!isTypeLegal(VecVT
) ||
17239 (!TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VecVT
) &&
17240 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
)))
17243 // Make the new BUILD_VECTOR.
17244 SDValue BV
= DAG
.getBuildVector(VecVT
, DL
, Ops
);
17246 // The new BUILD_VECTOR node has the potential to be further optimized.
17247 AddToWorklist(BV
.getNode());
17248 // Bitcast to the desired type.
17249 return DAG
.getBitcast(VT
, BV
);
17252 SDValue
DAGCombiner::createBuildVecShuffle(const SDLoc
&DL
, SDNode
*N
,
17253 ArrayRef
<int> VectorMask
,
17254 SDValue VecIn1
, SDValue VecIn2
,
17255 unsigned LeftIdx
, bool DidSplitVec
) {
17256 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
17257 SDValue ZeroIdx
= DAG
.getConstant(0, DL
, IdxTy
);
17259 EVT VT
= N
->getValueType(0);
17260 EVT InVT1
= VecIn1
.getValueType();
17261 EVT InVT2
= VecIn2
.getNode() ? VecIn2
.getValueType() : InVT1
;
17263 unsigned NumElems
= VT
.getVectorNumElements();
17264 unsigned ShuffleNumElems
= NumElems
;
17266 // If we artificially split a vector in two already, then the offsets in the
17267 // operands will all be based off of VecIn1, even those in VecIn2.
17268 unsigned Vec2Offset
= DidSplitVec
? 0 : InVT1
.getVectorNumElements();
17270 // We can't generate a shuffle node with mismatched input and output types.
17271 // Try to make the types match the type of the output.
17272 if (InVT1
!= VT
|| InVT2
!= VT
) {
17273 if ((VT
.getSizeInBits() % InVT1
.getSizeInBits() == 0) && InVT1
== InVT2
) {
17274 // If the output vector length is a multiple of both input lengths,
17275 // we can concatenate them and pad the rest with undefs.
17276 unsigned NumConcats
= VT
.getSizeInBits() / InVT1
.getSizeInBits();
17277 assert(NumConcats
>= 2 && "Concat needs at least two inputs!");
17278 SmallVector
<SDValue
, 2> ConcatOps(NumConcats
, DAG
.getUNDEF(InVT1
));
17279 ConcatOps
[0] = VecIn1
;
17280 ConcatOps
[1] = VecIn2
? VecIn2
: DAG
.getUNDEF(InVT1
);
17281 VecIn1
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
);
17282 VecIn2
= SDValue();
17283 } else if (InVT1
.getSizeInBits() == VT
.getSizeInBits() * 2) {
17284 if (!TLI
.isExtractSubvectorCheap(VT
, InVT1
, NumElems
))
17287 if (!VecIn2
.getNode()) {
17288 // If we only have one input vector, and it's twice the size of the
17289 // output, split it in two.
17290 VecIn2
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, VecIn1
,
17291 DAG
.getConstant(NumElems
, DL
, IdxTy
));
17292 VecIn1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, VecIn1
, ZeroIdx
);
17293 // Since we now have shorter input vectors, adjust the offset of the
17294 // second vector's start.
17295 Vec2Offset
= NumElems
;
17296 } else if (InVT2
.getSizeInBits() <= InVT1
.getSizeInBits()) {
17297 // VecIn1 is wider than the output, and we have another, possibly
17298 // smaller input. Pad the smaller input with undefs, shuffle at the
17299 // input vector width, and extract the output.
17300 // The shuffle type is different than VT, so check legality again.
17301 if (LegalOperations
&&
17302 !TLI
.isOperationLegal(ISD::VECTOR_SHUFFLE
, InVT1
))
17305 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
17306 // lower it back into a BUILD_VECTOR. So if the inserted type is
17307 // illegal, don't even try.
17308 if (InVT1
!= InVT2
) {
17309 if (!TLI
.isTypeLegal(InVT2
))
17311 VecIn2
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, InVT1
,
17312 DAG
.getUNDEF(InVT1
), VecIn2
, ZeroIdx
);
17314 ShuffleNumElems
= NumElems
* 2;
17316 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
17317 // than VecIn1. We can't handle this for now - this case will disappear
17318 // when we start sorting the vectors by type.
17321 } else if (InVT2
.getSizeInBits() * 2 == VT
.getSizeInBits() &&
17322 InVT1
.getSizeInBits() == VT
.getSizeInBits()) {
17323 SmallVector
<SDValue
, 2> ConcatOps(2, DAG
.getUNDEF(InVT2
));
17324 ConcatOps
[0] = VecIn2
;
17325 VecIn2
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
);
17327 // TODO: Support cases where the length mismatch isn't exactly by a
17329 // TODO: Move this check upwards, so that if we have bad type
17330 // mismatches, we don't create any DAG nodes.
17335 // Initialize mask to undef.
17336 SmallVector
<int, 8> Mask(ShuffleNumElems
, -1);
17338 // Only need to run up to the number of elements actually used, not the
17339 // total number of elements in the shuffle - if we are shuffling a wider
17340 // vector, the high lanes should be set to undef.
17341 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17342 if (VectorMask
[i
] <= 0)
17345 unsigned ExtIndex
= N
->getOperand(i
).getConstantOperandVal(1);
17346 if (VectorMask
[i
] == (int)LeftIdx
) {
17347 Mask
[i
] = ExtIndex
;
17348 } else if (VectorMask
[i
] == (int)LeftIdx
+ 1) {
17349 Mask
[i
] = Vec2Offset
+ ExtIndex
;
17353 // The type the input vectors may have changed above.
17354 InVT1
= VecIn1
.getValueType();
17356 // If we already have a VecIn2, it should have the same type as VecIn1.
17357 // If we don't, get an undef/zero vector of the appropriate type.
17358 VecIn2
= VecIn2
.getNode() ? VecIn2
: DAG
.getUNDEF(InVT1
);
17359 assert(InVT1
== VecIn2
.getValueType() && "Unexpected second input type.");
17361 SDValue Shuffle
= DAG
.getVectorShuffle(InVT1
, DL
, VecIn1
, VecIn2
, Mask
);
17362 if (ShuffleNumElems
> NumElems
)
17363 Shuffle
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, Shuffle
, ZeroIdx
);
17368 static SDValue
reduceBuildVecToShuffleWithZero(SDNode
*BV
, SelectionDAG
&DAG
) {
17369 assert(BV
->getOpcode() == ISD::BUILD_VECTOR
&& "Expected build vector");
17371 // First, determine where the build vector is not undef.
17372 // TODO: We could extend this to handle zero elements as well as undefs.
17373 int NumBVOps
= BV
->getNumOperands();
17375 for (int i
= 0; i
!= NumBVOps
; ++i
) {
17376 SDValue Op
= BV
->getOperand(i
);
17384 // Bail out if there's no non-undef element.
17388 // The build vector contains some number of undef elements and exactly
17389 // one other element. That other element must be a zero-extended scalar
17390 // extracted from a vector at a constant index to turn this into a shuffle.
17391 // Also, require that the build vector does not implicitly truncate/extend
17393 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
17394 EVT VT
= BV
->getValueType(0);
17395 SDValue Zext
= BV
->getOperand(ZextElt
);
17396 if (Zext
.getOpcode() != ISD::ZERO_EXTEND
|| !Zext
.hasOneUse() ||
17397 Zext
.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
17398 !isa
<ConstantSDNode
>(Zext
.getOperand(0).getOperand(1)) ||
17399 Zext
.getValueSizeInBits() != VT
.getScalarSizeInBits())
17402 // The zero-extend must be a multiple of the source size, and we must be
17403 // building a vector of the same size as the source of the extract element.
17404 SDValue Extract
= Zext
.getOperand(0);
17405 unsigned DestSize
= Zext
.getValueSizeInBits();
17406 unsigned SrcSize
= Extract
.getValueSizeInBits();
17407 if (DestSize
% SrcSize
!= 0 ||
17408 Extract
.getOperand(0).getValueSizeInBits() != VT
.getSizeInBits())
17411 // Create a shuffle mask that will combine the extracted element with zeros
17413 int ZextRatio
= DestSize
/ SrcSize
;
17414 int NumMaskElts
= NumBVOps
* ZextRatio
;
17415 SmallVector
<int, 32> ShufMask(NumMaskElts
, -1);
17416 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
17417 if (i
/ ZextRatio
== ZextElt
) {
17418 // The low bits of the (potentially translated) extracted element map to
17419 // the source vector. The high bits map to zero. We will use a zero vector
17420 // as the 2nd source operand of the shuffle, so use the 1st element of
17421 // that vector (mask value is number-of-elements) for the high bits.
17422 if (i
% ZextRatio
== 0)
17423 ShufMask
[i
] = Extract
.getConstantOperandVal(1);
17425 ShufMask
[i
] = NumMaskElts
;
17428 // Undef elements of the build vector remain undef because we initialize
17429 // the shuffle mask with -1.
17432 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
17433 // bitcast (shuffle V, ZeroVec, VectorMask)
17435 EVT VecVT
= Extract
.getOperand(0).getValueType();
17436 SDValue ZeroVec
= DAG
.getConstant(0, DL
, VecVT
);
17437 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17438 SDValue Shuf
= TLI
.buildLegalVectorShuffle(VecVT
, DL
, Extract
.getOperand(0),
17439 ZeroVec
, ShufMask
, DAG
);
17442 return DAG
.getBitcast(VT
, Shuf
);
17445 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
17446 // operations. If the types of the vectors we're extracting from allow it,
17447 // turn this into a vector_shuffle node.
17448 SDValue
DAGCombiner::reduceBuildVecToShuffle(SDNode
*N
) {
17450 EVT VT
= N
->getValueType(0);
17452 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
17453 if (!isTypeLegal(VT
))
17456 if (SDValue V
= reduceBuildVecToShuffleWithZero(N
, DAG
))
17459 // May only combine to shuffle after legalize if shuffle is legal.
17460 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::VECTOR_SHUFFLE
, VT
))
17463 bool UsesZeroVector
= false;
17464 unsigned NumElems
= N
->getNumOperands();
17466 // Record, for each element of the newly built vector, which input vector
17467 // that element comes from. -1 stands for undef, 0 for the zero vector,
17468 // and positive values for the input vectors.
17469 // VectorMask maps each element to its vector number, and VecIn maps vector
17470 // numbers to their initial SDValues.
17472 SmallVector
<int, 8> VectorMask(NumElems
, -1);
17473 SmallVector
<SDValue
, 8> VecIn
;
17474 VecIn
.push_back(SDValue());
17476 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17477 SDValue Op
= N
->getOperand(i
);
17482 // See if we can use a blend with a zero vector.
17483 // TODO: Should we generalize this to a blend with an arbitrary constant
17485 if (isNullConstant(Op
) || isNullFPConstant(Op
)) {
17486 UsesZeroVector
= true;
17491 // Not an undef or zero. If the input is something other than an
17492 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
17493 if (Op
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
17494 !isa
<ConstantSDNode
>(Op
.getOperand(1)))
17496 SDValue ExtractedFromVec
= Op
.getOperand(0);
17498 const APInt
&ExtractIdx
= Op
.getConstantOperandAPInt(1);
17499 if (ExtractIdx
.uge(ExtractedFromVec
.getValueType().getVectorNumElements()))
17502 // All inputs must have the same element type as the output.
17503 if (VT
.getVectorElementType() !=
17504 ExtractedFromVec
.getValueType().getVectorElementType())
17507 // Have we seen this input vector before?
17508 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
17509 // a map back from SDValues to numbers isn't worth it.
17510 unsigned Idx
= std::distance(
17511 VecIn
.begin(), std::find(VecIn
.begin(), VecIn
.end(), ExtractedFromVec
));
17512 if (Idx
== VecIn
.size())
17513 VecIn
.push_back(ExtractedFromVec
);
17515 VectorMask
[i
] = Idx
;
17518 // If we didn't find at least one input vector, bail out.
17519 if (VecIn
.size() < 2)
17522 // If all the Operands of BUILD_VECTOR extract from same
17523 // vector, then split the vector efficiently based on the maximum
17524 // vector access index and adjust the VectorMask and
17525 // VecIn accordingly.
17526 bool DidSplitVec
= false;
17527 if (VecIn
.size() == 2) {
17528 unsigned MaxIndex
= 0;
17529 unsigned NearestPow2
= 0;
17530 SDValue Vec
= VecIn
.back();
17531 EVT InVT
= Vec
.getValueType();
17532 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
17533 SmallVector
<unsigned, 8> IndexVec(NumElems
, 0);
17535 for (unsigned i
= 0; i
< NumElems
; i
++) {
17536 if (VectorMask
[i
] <= 0)
17538 unsigned Index
= N
->getOperand(i
).getConstantOperandVal(1);
17539 IndexVec
[i
] = Index
;
17540 MaxIndex
= std::max(MaxIndex
, Index
);
17543 NearestPow2
= PowerOf2Ceil(MaxIndex
);
17544 if (InVT
.isSimple() && NearestPow2
> 2 && MaxIndex
< NearestPow2
&&
17545 NumElems
* 2 < NearestPow2
) {
17546 unsigned SplitSize
= NearestPow2
/ 2;
17547 EVT SplitVT
= EVT::getVectorVT(*DAG
.getContext(),
17548 InVT
.getVectorElementType(), SplitSize
);
17549 if (TLI
.isTypeLegal(SplitVT
)) {
17550 SDValue VecIn2
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, SplitVT
, Vec
,
17551 DAG
.getConstant(SplitSize
, DL
, IdxTy
));
17552 SDValue VecIn1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, SplitVT
, Vec
,
17553 DAG
.getConstant(0, DL
, IdxTy
));
17555 VecIn
.push_back(VecIn1
);
17556 VecIn
.push_back(VecIn2
);
17557 DidSplitVec
= true;
17559 for (unsigned i
= 0; i
< NumElems
; i
++) {
17560 if (VectorMask
[i
] <= 0)
17562 VectorMask
[i
] = (IndexVec
[i
] < SplitSize
) ? 1 : 2;
17568 // TODO: We want to sort the vectors by descending length, so that adjacent
17569 // pairs have similar length, and the longer vector is always first in the
17572 // TODO: Should this fire if some of the input vectors has illegal type (like
17573 // it does now), or should we let legalization run its course first?
17576 // Take pairs of vectors, and shuffle them so that the result has elements
17577 // from these vectors in the correct places.
17578 // For example, given:
17579 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
17580 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
17581 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
17582 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
17583 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
17584 // We will generate:
17585 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
17586 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
17587 SmallVector
<SDValue
, 4> Shuffles
;
17588 for (unsigned In
= 0, Len
= (VecIn
.size() / 2); In
< Len
; ++In
) {
17589 unsigned LeftIdx
= 2 * In
+ 1;
17590 SDValue VecLeft
= VecIn
[LeftIdx
];
17592 (LeftIdx
+ 1) < VecIn
.size() ? VecIn
[LeftIdx
+ 1] : SDValue();
17594 if (SDValue Shuffle
= createBuildVecShuffle(DL
, N
, VectorMask
, VecLeft
,
17595 VecRight
, LeftIdx
, DidSplitVec
))
17596 Shuffles
.push_back(Shuffle
);
17601 // If we need the zero vector as an "ingredient" in the blend tree, add it
17602 // to the list of shuffles.
17603 if (UsesZeroVector
)
17604 Shuffles
.push_back(VT
.isInteger() ? DAG
.getConstant(0, DL
, VT
)
17605 : DAG
.getConstantFP(0.0, DL
, VT
));
17607 // If we only have one shuffle, we're done.
17608 if (Shuffles
.size() == 1)
17609 return Shuffles
[0];
17611 // Update the vector mask to point to the post-shuffle vectors.
17612 for (int &Vec
: VectorMask
)
17614 Vec
= Shuffles
.size() - 1;
17616 Vec
= (Vec
- 1) / 2;
17618 // More than one shuffle. Generate a binary tree of blends, e.g. if from
17619 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
17621 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
17622 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
17623 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
17624 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
17625 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
17626 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
17627 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
17629 // Make sure the initial size of the shuffle list is even.
17630 if (Shuffles
.size() % 2)
17631 Shuffles
.push_back(DAG
.getUNDEF(VT
));
17633 for (unsigned CurSize
= Shuffles
.size(); CurSize
> 1; CurSize
/= 2) {
17635 Shuffles
[CurSize
] = DAG
.getUNDEF(VT
);
17638 for (unsigned In
= 0, Len
= CurSize
/ 2; In
< Len
; ++In
) {
17640 int Right
= 2 * In
+ 1;
17641 SmallVector
<int, 8> Mask(NumElems
, -1);
17642 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17643 if (VectorMask
[i
] == Left
) {
17645 VectorMask
[i
] = In
;
17646 } else if (VectorMask
[i
] == Right
) {
17647 Mask
[i
] = i
+ NumElems
;
17648 VectorMask
[i
] = In
;
17653 DAG
.getVectorShuffle(VT
, DL
, Shuffles
[Left
], Shuffles
[Right
], Mask
);
17656 return Shuffles
[0];
17659 // Try to turn a build vector of zero extends of extract vector elts into a
17660 // a vector zero extend and possibly an extract subvector.
17661 // TODO: Support sign extend?
17662 // TODO: Allow undef elements?
17663 SDValue
DAGCombiner::convertBuildVecZextToZext(SDNode
*N
) {
17664 if (LegalOperations
)
17667 EVT VT
= N
->getValueType(0);
17669 bool FoundZeroExtend
= false;
17670 SDValue Op0
= N
->getOperand(0);
17671 auto checkElem
= [&](SDValue Op
) -> int64_t {
17672 unsigned Opc
= Op
.getOpcode();
17673 FoundZeroExtend
|= (Opc
== ISD::ZERO_EXTEND
);
17674 if ((Opc
== ISD::ZERO_EXTEND
|| Opc
== ISD::ANY_EXTEND
) &&
17675 Op
.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
17676 Op0
.getOperand(0).getOperand(0) == Op
.getOperand(0).getOperand(0))
17677 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0).getOperand(1)))
17678 return C
->getZExtValue();
17682 // Make sure the first element matches
17683 // (zext (extract_vector_elt X, C))
17684 int64_t Offset
= checkElem(Op0
);
17688 unsigned NumElems
= N
->getNumOperands();
17689 SDValue In
= Op0
.getOperand(0).getOperand(0);
17690 EVT InSVT
= In
.getValueType().getScalarType();
17691 EVT InVT
= EVT::getVectorVT(*DAG
.getContext(), InSVT
, NumElems
);
17693 // Don't create an illegal input type after type legalization.
17694 if (LegalTypes
&& !TLI
.isTypeLegal(InVT
))
17697 // Ensure all the elements come from the same vector and are adjacent.
17698 for (unsigned i
= 1; i
!= NumElems
; ++i
) {
17699 if ((Offset
+ i
) != checkElem(N
->getOperand(i
)))
17704 In
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InVT
, In
,
17705 Op0
.getOperand(0).getOperand(1));
17706 return DAG
.getNode(FoundZeroExtend
? ISD::ZERO_EXTEND
: ISD::ANY_EXTEND
, DL
,
17710 SDValue
DAGCombiner::visitBUILD_VECTOR(SDNode
*N
) {
17711 EVT VT
= N
->getValueType(0);
17713 // A vector built entirely of undefs is undef.
17714 if (ISD::allOperandsUndef(N
))
17715 return DAG
.getUNDEF(VT
);
17717 // If this is a splat of a bitcast from another vector, change to a
17720 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
17721 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
17723 // If X is a build_vector itself, the concat can become a larger build_vector.
17724 // TODO: Maybe this is useful for non-splat too?
17725 if (!LegalOperations
) {
17726 if (SDValue Splat
= cast
<BuildVectorSDNode
>(N
)->getSplatValue()) {
17727 Splat
= peekThroughBitcasts(Splat
);
17728 EVT SrcVT
= Splat
.getValueType();
17729 if (SrcVT
.isVector()) {
17730 unsigned NumElts
= N
->getNumOperands() * SrcVT
.getVectorNumElements();
17731 EVT NewVT
= EVT::getVectorVT(*DAG
.getContext(),
17732 SrcVT
.getVectorElementType(), NumElts
);
17733 if (!LegalTypes
|| TLI
.isTypeLegal(NewVT
)) {
17734 SmallVector
<SDValue
, 8> Ops(N
->getNumOperands(), Splat
);
17735 SDValue Concat
= DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
),
17737 return DAG
.getBitcast(VT
, Concat
);
17743 // Check if we can express BUILD VECTOR via subvector extract.
17744 if (!LegalTypes
&& (N
->getNumOperands() > 1)) {
17745 SDValue Op0
= N
->getOperand(0);
17746 auto checkElem
= [&](SDValue Op
) -> uint64_t {
17747 if ((Op
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) &&
17748 (Op0
.getOperand(0) == Op
.getOperand(0)))
17749 if (auto CNode
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1)))
17750 return CNode
->getZExtValue();
17754 int Offset
= checkElem(Op0
);
17755 for (unsigned i
= 0; i
< N
->getNumOperands(); ++i
) {
17756 if (Offset
+ i
!= checkElem(N
->getOperand(i
))) {
17762 if ((Offset
== 0) &&
17763 (Op0
.getOperand(0).getValueType() == N
->getValueType(0)))
17764 return Op0
.getOperand(0);
17765 if ((Offset
!= -1) &&
17766 ((Offset
% N
->getValueType(0).getVectorNumElements()) ==
17767 0)) // IDX must be multiple of output size.
17768 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), N
->getValueType(0),
17769 Op0
.getOperand(0), Op0
.getOperand(1));
17772 if (SDValue V
= convertBuildVecZextToZext(N
))
17775 if (SDValue V
= reduceBuildVecExtToExtBuildVec(N
))
17778 if (SDValue V
= reduceBuildVecToShuffle(N
))
17784 static SDValue
combineConcatVectorOfScalars(SDNode
*N
, SelectionDAG
&DAG
) {
17785 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17786 EVT OpVT
= N
->getOperand(0).getValueType();
17788 // If the operands are legal vectors, leave them alone.
17789 if (TLI
.isTypeLegal(OpVT
))
17793 EVT VT
= N
->getValueType(0);
17794 SmallVector
<SDValue
, 8> Ops
;
17796 EVT SVT
= EVT::getIntegerVT(*DAG
.getContext(), OpVT
.getSizeInBits());
17797 SDValue ScalarUndef
= DAG
.getNode(ISD::UNDEF
, DL
, SVT
);
17799 // Keep track of what we encounter.
17800 bool AnyInteger
= false;
17801 bool AnyFP
= false;
17802 for (const SDValue
&Op
: N
->ops()) {
17803 if (ISD::BITCAST
== Op
.getOpcode() &&
17804 !Op
.getOperand(0).getValueType().isVector())
17805 Ops
.push_back(Op
.getOperand(0));
17806 else if (ISD::UNDEF
== Op
.getOpcode())
17807 Ops
.push_back(ScalarUndef
);
17811 // Note whether we encounter an integer or floating point scalar.
17812 // If it's neither, bail out, it could be something weird like x86mmx.
17813 EVT LastOpVT
= Ops
.back().getValueType();
17814 if (LastOpVT
.isFloatingPoint())
17816 else if (LastOpVT
.isInteger())
17822 // If any of the operands is a floating point scalar bitcast to a vector,
17823 // use floating point types throughout, and bitcast everything.
17824 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
17826 SVT
= EVT::getFloatingPointVT(OpVT
.getSizeInBits());
17827 ScalarUndef
= DAG
.getNode(ISD::UNDEF
, DL
, SVT
);
17829 for (SDValue
&Op
: Ops
) {
17830 if (Op
.getValueType() == SVT
)
17835 Op
= DAG
.getBitcast(SVT
, Op
);
17840 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), SVT
,
17841 VT
.getSizeInBits() / SVT
.getSizeInBits());
17842 return DAG
.getBitcast(VT
, DAG
.getBuildVector(VecVT
, DL
, Ops
));
17845 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
17846 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
17847 // most two distinct vectors the same size as the result, attempt to turn this
17848 // into a legal shuffle.
17849 static SDValue
combineConcatVectorOfExtracts(SDNode
*N
, SelectionDAG
&DAG
) {
17850 EVT VT
= N
->getValueType(0);
17851 EVT OpVT
= N
->getOperand(0).getValueType();
17852 int NumElts
= VT
.getVectorNumElements();
17853 int NumOpElts
= OpVT
.getVectorNumElements();
17855 SDValue SV0
= DAG
.getUNDEF(VT
), SV1
= DAG
.getUNDEF(VT
);
17856 SmallVector
<int, 8> Mask
;
17858 for (SDValue Op
: N
->ops()) {
17859 Op
= peekThroughBitcasts(Op
);
17861 // UNDEF nodes convert to UNDEF shuffle mask values.
17862 if (Op
.isUndef()) {
17863 Mask
.append((unsigned)NumOpElts
, -1);
17867 if (Op
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
17870 // What vector are we extracting the subvector from and at what index?
17871 SDValue ExtVec
= Op
.getOperand(0);
17873 // We want the EVT of the original extraction to correctly scale the
17874 // extraction index.
17875 EVT ExtVT
= ExtVec
.getValueType();
17876 ExtVec
= peekThroughBitcasts(ExtVec
);
17878 // UNDEF nodes convert to UNDEF shuffle mask values.
17879 if (ExtVec
.isUndef()) {
17880 Mask
.append((unsigned)NumOpElts
, -1);
17884 if (!isa
<ConstantSDNode
>(Op
.getOperand(1)))
17886 int ExtIdx
= Op
.getConstantOperandVal(1);
17888 // Ensure that we are extracting a subvector from a vector the same
17889 // size as the result.
17890 if (ExtVT
.getSizeInBits() != VT
.getSizeInBits())
17893 // Scale the subvector index to account for any bitcast.
17894 int NumExtElts
= ExtVT
.getVectorNumElements();
17895 if (0 == (NumExtElts
% NumElts
))
17896 ExtIdx
/= (NumExtElts
/ NumElts
);
17897 else if (0 == (NumElts
% NumExtElts
))
17898 ExtIdx
*= (NumElts
/ NumExtElts
);
17902 // At most we can reference 2 inputs in the final shuffle.
17903 if (SV0
.isUndef() || SV0
== ExtVec
) {
17905 for (int i
= 0; i
!= NumOpElts
; ++i
)
17906 Mask
.push_back(i
+ ExtIdx
);
17907 } else if (SV1
.isUndef() || SV1
== ExtVec
) {
17909 for (int i
= 0; i
!= NumOpElts
; ++i
)
17910 Mask
.push_back(i
+ ExtIdx
+ NumElts
);
17916 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17917 return TLI
.buildLegalVectorShuffle(VT
, SDLoc(N
), DAG
.getBitcast(VT
, SV0
),
17918 DAG
.getBitcast(VT
, SV1
), Mask
, DAG
);
17921 SDValue
DAGCombiner::visitCONCAT_VECTORS(SDNode
*N
) {
17922 // If we only have one input vector, we don't need to do any concatenation.
17923 if (N
->getNumOperands() == 1)
17924 return N
->getOperand(0);
17926 // Check if all of the operands are undefs.
17927 EVT VT
= N
->getValueType(0);
17928 if (ISD::allOperandsUndef(N
))
17929 return DAG
.getUNDEF(VT
);
17931 // Optimize concat_vectors where all but the first of the vectors are undef.
17932 if (std::all_of(std::next(N
->op_begin()), N
->op_end(), [](const SDValue
&Op
) {
17933 return Op
.isUndef();
17935 SDValue In
= N
->getOperand(0);
17936 assert(In
.getValueType().isVector() && "Must concat vectors");
17938 // If the input is a concat_vectors, just make a larger concat by padding
17939 // with smaller undefs.
17940 if (In
.getOpcode() == ISD::CONCAT_VECTORS
&& In
.hasOneUse()) {
17941 unsigned NumOps
= N
->getNumOperands() * In
.getNumOperands();
17942 SmallVector
<SDValue
, 4> Ops(In
->op_begin(), In
->op_end());
17943 Ops
.resize(NumOps
, DAG
.getUNDEF(Ops
[0].getValueType()));
17944 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
17947 SDValue Scalar
= peekThroughOneUseBitcasts(In
);
17949 // concat_vectors(scalar_to_vector(scalar), undef) ->
17950 // scalar_to_vector(scalar)
17951 if (!LegalOperations
&& Scalar
.getOpcode() == ISD::SCALAR_TO_VECTOR
&&
17952 Scalar
.hasOneUse()) {
17953 EVT SVT
= Scalar
.getValueType().getVectorElementType();
17954 if (SVT
== Scalar
.getOperand(0).getValueType())
17955 Scalar
= Scalar
.getOperand(0);
17958 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
17959 if (!Scalar
.getValueType().isVector()) {
17960 // If the bitcast type isn't legal, it might be a trunc of a legal type;
17961 // look through the trunc so we can still do the transform:
17962 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
17963 if (Scalar
->getOpcode() == ISD::TRUNCATE
&&
17964 !TLI
.isTypeLegal(Scalar
.getValueType()) &&
17965 TLI
.isTypeLegal(Scalar
->getOperand(0).getValueType()))
17966 Scalar
= Scalar
->getOperand(0);
17968 EVT SclTy
= Scalar
.getValueType();
17970 if (!SclTy
.isFloatingPoint() && !SclTy
.isInteger())
17973 // Bail out if the vector size is not a multiple of the scalar size.
17974 if (VT
.getSizeInBits() % SclTy
.getSizeInBits())
17977 unsigned VNTNumElms
= VT
.getSizeInBits() / SclTy
.getSizeInBits();
17978 if (VNTNumElms
< 2)
17981 EVT NVT
= EVT::getVectorVT(*DAG
.getContext(), SclTy
, VNTNumElms
);
17982 if (!TLI
.isTypeLegal(NVT
) || !TLI
.isTypeLegal(Scalar
.getValueType()))
17985 SDValue Res
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, SDLoc(N
), NVT
, Scalar
);
17986 return DAG
.getBitcast(VT
, Res
);
17990 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
17991 // We have already tested above for an UNDEF only concatenation.
17992 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
17993 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
17994 auto IsBuildVectorOrUndef
= [](const SDValue
&Op
) {
17995 return ISD::UNDEF
== Op
.getOpcode() || ISD::BUILD_VECTOR
== Op
.getOpcode();
17997 if (llvm::all_of(N
->ops(), IsBuildVectorOrUndef
)) {
17998 SmallVector
<SDValue
, 8> Opnds
;
17999 EVT SVT
= VT
.getScalarType();
18002 if (!SVT
.isFloatingPoint()) {
18003 // If BUILD_VECTOR are from built from integer, they may have different
18004 // operand types. Get the smallest type and truncate all operands to it.
18005 bool FoundMinVT
= false;
18006 for (const SDValue
&Op
: N
->ops())
18007 if (ISD::BUILD_VECTOR
== Op
.getOpcode()) {
18008 EVT OpSVT
= Op
.getOperand(0).getValueType();
18009 MinVT
= (!FoundMinVT
|| OpSVT
.bitsLE(MinVT
)) ? OpSVT
: MinVT
;
18012 assert(FoundMinVT
&& "Concat vector type mismatch");
18015 for (const SDValue
&Op
: N
->ops()) {
18016 EVT OpVT
= Op
.getValueType();
18017 unsigned NumElts
= OpVT
.getVectorNumElements();
18019 if (ISD::UNDEF
== Op
.getOpcode())
18020 Opnds
.append(NumElts
, DAG
.getUNDEF(MinVT
));
18022 if (ISD::BUILD_VECTOR
== Op
.getOpcode()) {
18023 if (SVT
.isFloatingPoint()) {
18024 assert(SVT
== OpVT
.getScalarType() && "Concat vector type mismatch");
18025 Opnds
.append(Op
->op_begin(), Op
->op_begin() + NumElts
);
18027 for (unsigned i
= 0; i
!= NumElts
; ++i
)
18029 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), MinVT
, Op
.getOperand(i
)));
18034 assert(VT
.getVectorNumElements() == Opnds
.size() &&
18035 "Concat vector type mismatch");
18036 return DAG
.getBuildVector(VT
, SDLoc(N
), Opnds
);
18039 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
18040 if (SDValue V
= combineConcatVectorOfScalars(N
, DAG
))
18043 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
18044 if (Level
< AfterLegalizeVectorOps
&& TLI
.isTypeLegal(VT
))
18045 if (SDValue V
= combineConcatVectorOfExtracts(N
, DAG
))
18048 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
18049 // nodes often generate nop CONCAT_VECTOR nodes.
18050 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
18051 // place the incoming vectors at the exact same location.
18052 SDValue SingleSource
= SDValue();
18053 unsigned PartNumElem
= N
->getOperand(0).getValueType().getVectorNumElements();
18055 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
18056 SDValue Op
= N
->getOperand(i
);
18061 // Check if this is the identity extract:
18062 if (Op
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
18065 // Find the single incoming vector for the extract_subvector.
18066 if (SingleSource
.getNode()) {
18067 if (Op
.getOperand(0) != SingleSource
)
18070 SingleSource
= Op
.getOperand(0);
18072 // Check the source type is the same as the type of the result.
18073 // If not, this concat may extend the vector, so we can not
18074 // optimize it away.
18075 if (SingleSource
.getValueType() != N
->getValueType(0))
18079 auto *CS
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
18080 // The extract index must be constant.
18084 // Check that we are reading from the identity index.
18085 unsigned IdentityIndex
= i
* PartNumElem
;
18086 if (CS
->getAPIntValue() != IdentityIndex
)
18090 if (SingleSource
.getNode())
18091 return SingleSource
;
18096 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
18097 // if the subvector can be sourced for free.
18098 static SDValue
getSubVectorSrc(SDValue V
, SDValue Index
, EVT SubVT
) {
18099 if (V
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
18100 V
.getOperand(1).getValueType() == SubVT
&& V
.getOperand(2) == Index
) {
18101 return V
.getOperand(1);
18103 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
18104 if (IndexC
&& V
.getOpcode() == ISD::CONCAT_VECTORS
&&
18105 V
.getOperand(0).getValueType() == SubVT
&&
18106 (IndexC
->getZExtValue() % SubVT
.getVectorNumElements()) == 0) {
18107 uint64_t SubIdx
= IndexC
->getZExtValue() / SubVT
.getVectorNumElements();
18108 return V
.getOperand(SubIdx
);
18113 static SDValue
narrowInsertExtractVectorBinOp(SDNode
*Extract
,
18114 SelectionDAG
&DAG
) {
18115 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18116 SDValue BinOp
= Extract
->getOperand(0);
18117 unsigned BinOpcode
= BinOp
.getOpcode();
18118 if (!TLI
.isBinOp(BinOpcode
) || BinOp
.getNode()->getNumValues() != 1)
18121 EVT VecVT
= BinOp
.getValueType();
18122 SDValue Bop0
= BinOp
.getOperand(0), Bop1
= BinOp
.getOperand(1);
18123 if (VecVT
!= Bop0
.getValueType() || VecVT
!= Bop1
.getValueType())
18126 SDValue Index
= Extract
->getOperand(1);
18127 EVT SubVT
= Extract
->getValueType(0);
18128 if (!TLI
.isOperationLegalOrCustom(BinOpcode
, SubVT
))
18131 SDValue Sub0
= getSubVectorSrc(Bop0
, Index
, SubVT
);
18132 SDValue Sub1
= getSubVectorSrc(Bop1
, Index
, SubVT
);
18134 // TODO: We could handle the case where only 1 operand is being inserted by
18135 // creating an extract of the other operand, but that requires checking
18136 // number of uses and/or costs.
18137 if (!Sub0
|| !Sub1
)
18140 // We are inserting both operands of the wide binop only to extract back
18141 // to the narrow vector size. Eliminate all of the insert/extract:
18142 // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
18143 return DAG
.getNode(BinOpcode
, SDLoc(Extract
), SubVT
, Sub0
, Sub1
,
18144 BinOp
->getFlags());
18147 /// If we are extracting a subvector produced by a wide binary operator try
18148 /// to use a narrow binary operator and/or avoid concatenation and extraction.
18149 static SDValue
narrowExtractedVectorBinOp(SDNode
*Extract
, SelectionDAG
&DAG
) {
18150 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
18151 // some of these bailouts with other transforms.
18153 if (SDValue V
= narrowInsertExtractVectorBinOp(Extract
, DAG
))
18156 // The extract index must be a constant, so we can map it to a concat operand.
18157 auto *ExtractIndexC
= dyn_cast
<ConstantSDNode
>(Extract
->getOperand(1));
18158 if (!ExtractIndexC
)
18161 // We are looking for an optionally bitcasted wide vector binary operator
18162 // feeding an extract subvector.
18163 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18164 SDValue BinOp
= peekThroughBitcasts(Extract
->getOperand(0));
18165 unsigned BOpcode
= BinOp
.getOpcode();
18166 if (!TLI
.isBinOp(BOpcode
) || BinOp
.getNode()->getNumValues() != 1)
18169 // The binop must be a vector type, so we can extract some fraction of it.
18170 EVT WideBVT
= BinOp
.getValueType();
18171 if (!WideBVT
.isVector())
18174 EVT VT
= Extract
->getValueType(0);
18175 unsigned ExtractIndex
= ExtractIndexC
->getZExtValue();
18176 assert(ExtractIndex
% VT
.getVectorNumElements() == 0 &&
18177 "Extract index is not a multiple of the vector length.");
18179 // Bail out if this is not a proper multiple width extraction.
18180 unsigned WideWidth
= WideBVT
.getSizeInBits();
18181 unsigned NarrowWidth
= VT
.getSizeInBits();
18182 if (WideWidth
% NarrowWidth
!= 0)
18185 // Bail out if we are extracting a fraction of a single operation. This can
18186 // occur because we potentially looked through a bitcast of the binop.
18187 unsigned NarrowingRatio
= WideWidth
/ NarrowWidth
;
18188 unsigned WideNumElts
= WideBVT
.getVectorNumElements();
18189 if (WideNumElts
% NarrowingRatio
!= 0)
18192 // Bail out if the target does not support a narrower version of the binop.
18193 EVT NarrowBVT
= EVT::getVectorVT(*DAG
.getContext(), WideBVT
.getScalarType(),
18194 WideNumElts
/ NarrowingRatio
);
18195 if (!TLI
.isOperationLegalOrCustomOrPromote(BOpcode
, NarrowBVT
))
18198 // If extraction is cheap, we don't need to look at the binop operands
18199 // for concat ops. The narrow binop alone makes this transform profitable.
18200 // We can't just reuse the original extract index operand because we may have
18202 unsigned ConcatOpNum
= ExtractIndex
/ VT
.getVectorNumElements();
18203 unsigned ExtBOIdx
= ConcatOpNum
* NarrowBVT
.getVectorNumElements();
18204 EVT ExtBOIdxVT
= Extract
->getOperand(1).getValueType();
18205 if (TLI
.isExtractSubvectorCheap(NarrowBVT
, WideBVT
, ExtBOIdx
) &&
18206 BinOp
.hasOneUse() && Extract
->getOperand(0)->hasOneUse()) {
18207 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
18209 SDValue NewExtIndex
= DAG
.getConstant(ExtBOIdx
, DL
, ExtBOIdxVT
);
18210 SDValue X
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18211 BinOp
.getOperand(0), NewExtIndex
);
18212 SDValue Y
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18213 BinOp
.getOperand(1), NewExtIndex
);
18214 SDValue NarrowBinOp
= DAG
.getNode(BOpcode
, DL
, NarrowBVT
, X
, Y
,
18215 BinOp
.getNode()->getFlags());
18216 return DAG
.getBitcast(VT
, NarrowBinOp
);
18219 // Only handle the case where we are doubling and then halving. A larger ratio
18220 // may require more than two narrow binops to replace the wide binop.
18221 if (NarrowingRatio
!= 2)
18224 // TODO: The motivating case for this transform is an x86 AVX1 target. That
18225 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
18226 // flavors, but no other 256-bit integer support. This could be extended to
18227 // handle any binop, but that may require fixing/adding other folds to avoid
18228 // codegen regressions.
18229 if (BOpcode
!= ISD::AND
&& BOpcode
!= ISD::OR
&& BOpcode
!= ISD::XOR
)
18232 // We need at least one concatenation operation of a binop operand to make
18233 // this transform worthwhile. The concat must double the input vector sizes.
18234 auto GetSubVector
= [ConcatOpNum
](SDValue V
) -> SDValue
{
18235 if (V
.getOpcode() == ISD::CONCAT_VECTORS
&& V
.getNumOperands() == 2)
18236 return V
.getOperand(ConcatOpNum
);
18239 SDValue SubVecL
= GetSubVector(peekThroughBitcasts(BinOp
.getOperand(0)));
18240 SDValue SubVecR
= GetSubVector(peekThroughBitcasts(BinOp
.getOperand(1)));
18242 if (SubVecL
|| SubVecR
) {
18243 // If a binop operand was not the result of a concat, we must extract a
18244 // half-sized operand for our new narrow binop:
18245 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
18246 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
18247 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
18249 SDValue IndexC
= DAG
.getConstant(ExtBOIdx
, DL
, ExtBOIdxVT
);
18250 SDValue X
= SubVecL
? DAG
.getBitcast(NarrowBVT
, SubVecL
)
18251 : DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18252 BinOp
.getOperand(0), IndexC
);
18254 SDValue Y
= SubVecR
? DAG
.getBitcast(NarrowBVT
, SubVecR
)
18255 : DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18256 BinOp
.getOperand(1), IndexC
);
18258 SDValue NarrowBinOp
= DAG
.getNode(BOpcode
, DL
, NarrowBVT
, X
, Y
);
18259 return DAG
.getBitcast(VT
, NarrowBinOp
);
18265 /// If we are extracting a subvector from a wide vector load, convert to a
18266 /// narrow load to eliminate the extraction:
18267 /// (extract_subvector (load wide vector)) --> (load narrow vector)
18268 static SDValue
narrowExtractedVectorLoad(SDNode
*Extract
, SelectionDAG
&DAG
) {
18269 // TODO: Add support for big-endian. The offset calculation must be adjusted.
18270 if (DAG
.getDataLayout().isBigEndian())
18273 auto *Ld
= dyn_cast
<LoadSDNode
>(Extract
->getOperand(0));
18274 auto *ExtIdx
= dyn_cast
<ConstantSDNode
>(Extract
->getOperand(1));
18275 if (!Ld
|| Ld
->getExtensionType() || !Ld
->isSimple() ||
18279 // Allow targets to opt-out.
18280 EVT VT
= Extract
->getValueType(0);
18281 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18282 if (!TLI
.shouldReduceLoadWidth(Ld
, Ld
->getExtensionType(), VT
))
18285 // The narrow load will be offset from the base address of the old load if
18286 // we are extracting from something besides index 0 (little-endian).
18288 SDValue BaseAddr
= Ld
->getOperand(1);
18289 unsigned Offset
= ExtIdx
->getZExtValue() * VT
.getScalarType().getStoreSize();
18291 // TODO: Use "BaseIndexOffset" to make this more effective.
18292 SDValue NewAddr
= DAG
.getMemBasePlusOffset(BaseAddr
, Offset
, DL
);
18293 MachineFunction
&MF
= DAG
.getMachineFunction();
18294 MachineMemOperand
*MMO
= MF
.getMachineMemOperand(Ld
->getMemOperand(), Offset
,
18295 VT
.getStoreSize());
18296 SDValue NewLd
= DAG
.getLoad(VT
, DL
, Ld
->getChain(), NewAddr
, MMO
);
18297 DAG
.makeEquivalentMemoryOrdering(Ld
, NewLd
);
18301 SDValue
DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode
*N
) {
18302 EVT NVT
= N
->getValueType(0);
18303 SDValue V
= N
->getOperand(0);
18305 // Extract from UNDEF is UNDEF.
18307 return DAG
.getUNDEF(NVT
);
18309 if (TLI
.isOperationLegalOrCustomOrPromote(ISD::LOAD
, NVT
))
18310 if (SDValue NarrowLoad
= narrowExtractedVectorLoad(N
, DAG
))
18313 // Combine an extract of an extract into a single extract_subvector.
18314 // ext (ext X, C), 0 --> ext X, C
18315 SDValue Index
= N
->getOperand(1);
18316 if (isNullConstant(Index
) && V
.getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
18317 V
.hasOneUse() && isa
<ConstantSDNode
>(V
.getOperand(1))) {
18318 if (TLI
.isExtractSubvectorCheap(NVT
, V
.getOperand(0).getValueType(),
18319 V
.getConstantOperandVal(1)) &&
18320 TLI
.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, NVT
)) {
18321 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), NVT
, V
.getOperand(0),
18326 // Try to move vector bitcast after extract_subv by scaling extraction index:
18327 // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
18328 if (isa
<ConstantSDNode
>(Index
) && V
.getOpcode() == ISD::BITCAST
&&
18329 V
.getOperand(0).getValueType().isVector()) {
18330 SDValue SrcOp
= V
.getOperand(0);
18331 EVT SrcVT
= SrcOp
.getValueType();
18332 unsigned SrcNumElts
= SrcVT
.getVectorNumElements();
18333 unsigned DestNumElts
= V
.getValueType().getVectorNumElements();
18334 if ((SrcNumElts
% DestNumElts
) == 0) {
18335 unsigned SrcDestRatio
= SrcNumElts
/ DestNumElts
;
18336 unsigned NewExtNumElts
= NVT
.getVectorNumElements() * SrcDestRatio
;
18337 EVT NewExtVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
.getScalarType(),
18339 if (TLI
.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, NewExtVT
)) {
18340 unsigned IndexValScaled
= N
->getConstantOperandVal(1) * SrcDestRatio
;
18342 SDValue NewIndex
= DAG
.getIntPtrConstant(IndexValScaled
, DL
);
18343 SDValue NewExtract
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NewExtVT
,
18344 V
.getOperand(0), NewIndex
);
18345 return DAG
.getBitcast(NVT
, NewExtract
);
18348 // TODO - handle (DestNumElts % SrcNumElts) == 0
18352 // (extract_subvec (concat V1, V2, ...), i)
18355 // Only operand 0 is checked as 'concat' assumes all inputs of the same
18357 if (V
.getOpcode() == ISD::CONCAT_VECTORS
&& isa
<ConstantSDNode
>(Index
) &&
18358 V
.getOperand(0).getValueType() == NVT
) {
18359 unsigned Idx
= N
->getConstantOperandVal(1);
18360 unsigned NumElems
= NVT
.getVectorNumElements();
18361 assert((Idx
% NumElems
) == 0 &&
18362 "IDX in concat is not a multiple of the result vector length.");
18363 return V
->getOperand(Idx
/ NumElems
);
18366 V
= peekThroughBitcasts(V
);
18368 // If the input is a build vector. Try to make a smaller build vector.
18369 if (V
.getOpcode() == ISD::BUILD_VECTOR
) {
18370 if (auto *IdxC
= dyn_cast
<ConstantSDNode
>(Index
)) {
18371 EVT InVT
= V
.getValueType();
18372 unsigned ExtractSize
= NVT
.getSizeInBits();
18373 unsigned EltSize
= InVT
.getScalarSizeInBits();
18374 // Only do this if we won't split any elements.
18375 if (ExtractSize
% EltSize
== 0) {
18376 unsigned NumElems
= ExtractSize
/ EltSize
;
18377 EVT EltVT
= InVT
.getVectorElementType();
18378 EVT ExtractVT
= NumElems
== 1 ? EltVT
18379 : EVT::getVectorVT(*DAG
.getContext(),
18381 if ((Level
< AfterLegalizeDAG
||
18383 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, ExtractVT
))) &&
18384 (!LegalTypes
|| TLI
.isTypeLegal(ExtractVT
))) {
18385 unsigned IdxVal
= IdxC
->getZExtValue();
18386 IdxVal
*= NVT
.getScalarSizeInBits();
18389 if (NumElems
== 1) {
18390 SDValue Src
= V
->getOperand(IdxVal
);
18391 if (EltVT
!= Src
.getValueType())
18392 Src
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), InVT
, Src
);
18393 return DAG
.getBitcast(NVT
, Src
);
18396 // Extract the pieces from the original build_vector.
18397 SDValue BuildVec
= DAG
.getBuildVector(
18398 ExtractVT
, SDLoc(N
), V
->ops().slice(IdxVal
, NumElems
));
18399 return DAG
.getBitcast(NVT
, BuildVec
);
18405 if (V
.getOpcode() == ISD::INSERT_SUBVECTOR
) {
18406 // Handle only simple case where vector being inserted and vector
18407 // being extracted are of same size.
18408 EVT SmallVT
= V
.getOperand(1).getValueType();
18409 if (!NVT
.bitsEq(SmallVT
))
18412 // Only handle cases where both indexes are constants.
18413 auto *ExtIdx
= dyn_cast
<ConstantSDNode
>(Index
);
18414 auto *InsIdx
= dyn_cast
<ConstantSDNode
>(V
.getOperand(2));
18415 if (InsIdx
&& ExtIdx
) {
18417 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
18419 // indices are equal or bit offsets are equal => V1
18420 // otherwise => (extract_subvec V1, ExtIdx)
18421 if (InsIdx
->getZExtValue() * SmallVT
.getScalarSizeInBits() ==
18422 ExtIdx
->getZExtValue() * NVT
.getScalarSizeInBits())
18423 return DAG
.getBitcast(NVT
, V
.getOperand(1));
18424 return DAG
.getNode(
18425 ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), NVT
,
18426 DAG
.getBitcast(N
->getOperand(0).getValueType(), V
.getOperand(0)),
18431 if (SDValue NarrowBOp
= narrowExtractedVectorBinOp(N
, DAG
))
18434 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
18435 return SDValue(N
, 0);
18440 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
18441 /// followed by concatenation. Narrow vector ops may have better performance
18442 /// than wide ops, and this can unlock further narrowing of other vector ops.
18443 /// Targets can invert this transform later if it is not profitable.
18444 static SDValue
foldShuffleOfConcatUndefs(ShuffleVectorSDNode
*Shuf
,
18445 SelectionDAG
&DAG
) {
18446 SDValue N0
= Shuf
->getOperand(0), N1
= Shuf
->getOperand(1);
18447 if (N0
.getOpcode() != ISD::CONCAT_VECTORS
|| N0
.getNumOperands() != 2 ||
18448 N1
.getOpcode() != ISD::CONCAT_VECTORS
|| N1
.getNumOperands() != 2 ||
18449 !N0
.getOperand(1).isUndef() || !N1
.getOperand(1).isUndef())
18452 // Split the wide shuffle mask into halves. Any mask element that is accessing
18453 // operand 1 is offset down to account for narrowing of the vectors.
18454 ArrayRef
<int> Mask
= Shuf
->getMask();
18455 EVT VT
= Shuf
->getValueType(0);
18456 unsigned NumElts
= VT
.getVectorNumElements();
18457 unsigned HalfNumElts
= NumElts
/ 2;
18458 SmallVector
<int, 16> Mask0(HalfNumElts
, -1);
18459 SmallVector
<int, 16> Mask1(HalfNumElts
, -1);
18460 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18463 int M
= Mask
[i
] < (int)NumElts
? Mask
[i
] : Mask
[i
] - (int)HalfNumElts
;
18464 if (i
< HalfNumElts
)
18467 Mask1
[i
- HalfNumElts
] = M
;
18470 // Ask the target if this is a valid transform.
18471 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18472 EVT HalfVT
= EVT::getVectorVT(*DAG
.getContext(), VT
.getScalarType(),
18474 if (!TLI
.isShuffleMaskLegal(Mask0
, HalfVT
) ||
18475 !TLI
.isShuffleMaskLegal(Mask1
, HalfVT
))
18478 // shuffle (concat X, undef), (concat Y, undef), Mask -->
18479 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
18480 SDValue X
= N0
.getOperand(0), Y
= N1
.getOperand(0);
18482 SDValue Shuf0
= DAG
.getVectorShuffle(HalfVT
, DL
, X
, Y
, Mask0
);
18483 SDValue Shuf1
= DAG
.getVectorShuffle(HalfVT
, DL
, X
, Y
, Mask1
);
18484 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, Shuf0
, Shuf1
);
18487 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
18488 // or turn a shuffle of a single concat into simpler shuffle then concat.
18489 static SDValue
partitionShuffleOfConcats(SDNode
*N
, SelectionDAG
&DAG
) {
18490 EVT VT
= N
->getValueType(0);
18491 unsigned NumElts
= VT
.getVectorNumElements();
18493 SDValue N0
= N
->getOperand(0);
18494 SDValue N1
= N
->getOperand(1);
18495 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N
);
18496 ArrayRef
<int> Mask
= SVN
->getMask();
18498 SmallVector
<SDValue
, 4> Ops
;
18499 EVT ConcatVT
= N0
.getOperand(0).getValueType();
18500 unsigned NumElemsPerConcat
= ConcatVT
.getVectorNumElements();
18501 unsigned NumConcats
= NumElts
/ NumElemsPerConcat
;
18503 auto IsUndefMaskElt
= [](int i
) { return i
== -1; };
18505 // Special case: shuffle(concat(A,B)) can be more efficiently represented
18506 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
18507 // half vector elements.
18508 if (NumElemsPerConcat
* 2 == NumElts
&& N1
.isUndef() &&
18509 llvm::all_of(Mask
.slice(NumElemsPerConcat
, NumElemsPerConcat
),
18511 N0
= DAG
.getVectorShuffle(ConcatVT
, SDLoc(N
), N0
.getOperand(0),
18513 Mask
.slice(0, NumElemsPerConcat
));
18514 N1
= DAG
.getUNDEF(ConcatVT
);
18515 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, N0
, N1
);
18518 // Look at every vector that's inserted. We're looking for exact
18519 // subvector-sized copies from a concatenated vector
18520 for (unsigned I
= 0; I
!= NumConcats
; ++I
) {
18521 unsigned Begin
= I
* NumElemsPerConcat
;
18522 ArrayRef
<int> SubMask
= Mask
.slice(Begin
, NumElemsPerConcat
);
18524 // Make sure we're dealing with a copy.
18525 if (llvm::all_of(SubMask
, IsUndefMaskElt
)) {
18526 Ops
.push_back(DAG
.getUNDEF(ConcatVT
));
18531 for (int i
= 0; i
!= (int)NumElemsPerConcat
; ++i
) {
18532 if (IsUndefMaskElt(SubMask
[i
]))
18534 if ((SubMask
[i
] % (int)NumElemsPerConcat
) != i
)
18536 int EltOpIdx
= SubMask
[i
] / NumElemsPerConcat
;
18537 if (0 <= OpIdx
&& EltOpIdx
!= OpIdx
)
18541 assert(0 <= OpIdx
&& "Unknown concat_vectors op");
18543 if (OpIdx
< (int)N0
.getNumOperands())
18544 Ops
.push_back(N0
.getOperand(OpIdx
));
18546 Ops
.push_back(N1
.getOperand(OpIdx
- N0
.getNumOperands()));
18549 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
18552 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
18553 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
18555 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
18556 // a simplification in some sense, but it isn't appropriate in general: some
18557 // BUILD_VECTORs are substantially cheaper than others. The general case
18558 // of a BUILD_VECTOR requires inserting each element individually (or
18559 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
18560 // all constants is a single constant pool load. A BUILD_VECTOR where each
18561 // element is identical is a splat. A BUILD_VECTOR where most of the operands
18562 // are undef lowers to a small number of element insertions.
18564 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
18565 // We don't fold shuffles where one side is a non-zero constant, and we don't
18566 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
18567 // non-constant operands. This seems to work out reasonably well in practice.
18568 static SDValue
combineShuffleOfScalars(ShuffleVectorSDNode
*SVN
,
18570 const TargetLowering
&TLI
) {
18571 EVT VT
= SVN
->getValueType(0);
18572 unsigned NumElts
= VT
.getVectorNumElements();
18573 SDValue N0
= SVN
->getOperand(0);
18574 SDValue N1
= SVN
->getOperand(1);
18576 if (!N0
->hasOneUse())
18579 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
18580 // discussed above.
18581 if (!N1
.isUndef()) {
18582 if (!N1
->hasOneUse())
18585 bool N0AnyConst
= isAnyConstantBuildVector(N0
);
18586 bool N1AnyConst
= isAnyConstantBuildVector(N1
);
18587 if (N0AnyConst
&& !N1AnyConst
&& !ISD::isBuildVectorAllZeros(N0
.getNode()))
18589 if (!N0AnyConst
&& N1AnyConst
&& !ISD::isBuildVectorAllZeros(N1
.getNode()))
18593 // If both inputs are splats of the same value then we can safely merge this
18594 // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
18595 bool IsSplat
= false;
18596 auto *BV0
= dyn_cast
<BuildVectorSDNode
>(N0
);
18597 auto *BV1
= dyn_cast
<BuildVectorSDNode
>(N1
);
18599 if (SDValue Splat0
= BV0
->getSplatValue())
18600 IsSplat
= (Splat0
== BV1
->getSplatValue());
18602 SmallVector
<SDValue
, 8> Ops
;
18603 SmallSet
<SDValue
, 16> DuplicateOps
;
18604 for (int M
: SVN
->getMask()) {
18605 SDValue Op
= DAG
.getUNDEF(VT
.getScalarType());
18607 int Idx
= M
< (int)NumElts
? M
: M
- NumElts
;
18608 SDValue
&S
= (M
< (int)NumElts
? N0
: N1
);
18609 if (S
.getOpcode() == ISD::BUILD_VECTOR
) {
18610 Op
= S
.getOperand(Idx
);
18611 } else if (S
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
18612 SDValue Op0
= S
.getOperand(0);
18613 Op
= Idx
== 0 ? Op0
: DAG
.getUNDEF(Op0
.getValueType());
18615 // Operand can't be combined - bail out.
18620 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
18621 // generating a splat; semantically, this is fine, but it's likely to
18622 // generate low-quality code if the target can't reconstruct an appropriate
18624 if (!Op
.isUndef() && !isa
<ConstantSDNode
>(Op
) && !isa
<ConstantFPSDNode
>(Op
))
18625 if (!IsSplat
&& !DuplicateOps
.insert(Op
).second
)
18631 // BUILD_VECTOR requires all inputs to be of the same type, find the
18632 // maximum type and extend them all.
18633 EVT SVT
= VT
.getScalarType();
18634 if (SVT
.isInteger())
18635 for (SDValue
&Op
: Ops
)
18636 SVT
= (SVT
.bitsLT(Op
.getValueType()) ? Op
.getValueType() : SVT
);
18637 if (SVT
!= VT
.getScalarType())
18638 for (SDValue
&Op
: Ops
)
18639 Op
= TLI
.isZExtFree(Op
.getValueType(), SVT
)
18640 ? DAG
.getZExtOrTrunc(Op
, SDLoc(SVN
), SVT
)
18641 : DAG
.getSExtOrTrunc(Op
, SDLoc(SVN
), SVT
);
18642 return DAG
.getBuildVector(VT
, SDLoc(SVN
), Ops
);
18645 // Match shuffles that can be converted to any_vector_extend_in_reg.
18646 // This is often generated during legalization.
18647 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
18648 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
18649 static SDValue
combineShuffleToVectorExtend(ShuffleVectorSDNode
*SVN
,
18651 const TargetLowering
&TLI
,
18652 bool LegalOperations
) {
18653 EVT VT
= SVN
->getValueType(0);
18654 bool IsBigEndian
= DAG
.getDataLayout().isBigEndian();
18656 // TODO Add support for big-endian when we have a test case.
18657 if (!VT
.isInteger() || IsBigEndian
)
18660 unsigned NumElts
= VT
.getVectorNumElements();
18661 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
18662 ArrayRef
<int> Mask
= SVN
->getMask();
18663 SDValue N0
= SVN
->getOperand(0);
18665 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
18666 auto isAnyExtend
= [&Mask
, &NumElts
](unsigned Scale
) {
18667 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18670 if ((i
% Scale
) == 0 && Mask
[i
] == (int)(i
/ Scale
))
18677 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
18678 // power-of-2 extensions as they are the most likely.
18679 for (unsigned Scale
= 2; Scale
< NumElts
; Scale
*= 2) {
18680 // Check for non power of 2 vector sizes
18681 if (NumElts
% Scale
!= 0)
18683 if (!isAnyExtend(Scale
))
18686 EVT OutSVT
= EVT::getIntegerVT(*DAG
.getContext(), EltSizeInBits
* Scale
);
18687 EVT OutVT
= EVT::getVectorVT(*DAG
.getContext(), OutSVT
, NumElts
/ Scale
);
18688 // Never create an illegal type. Only create unsupported operations if we
18689 // are pre-legalization.
18690 if (TLI
.isTypeLegal(OutVT
))
18691 if (!LegalOperations
||
18692 TLI
.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG
, OutVT
))
18693 return DAG
.getBitcast(VT
,
18694 DAG
.getNode(ISD::ANY_EXTEND_VECTOR_INREG
,
18695 SDLoc(SVN
), OutVT
, N0
));
18701 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
18702 // each source element of a large type into the lowest elements of a smaller
18703 // destination type. This is often generated during legalization.
18704 // If the source node itself was a '*_extend_vector_inreg' node then we should
18705 // then be able to remove it.
18706 static SDValue
combineTruncationShuffle(ShuffleVectorSDNode
*SVN
,
18707 SelectionDAG
&DAG
) {
18708 EVT VT
= SVN
->getValueType(0);
18709 bool IsBigEndian
= DAG
.getDataLayout().isBigEndian();
18711 // TODO Add support for big-endian when we have a test case.
18712 if (!VT
.isInteger() || IsBigEndian
)
18715 SDValue N0
= peekThroughBitcasts(SVN
->getOperand(0));
18717 unsigned Opcode
= N0
.getOpcode();
18718 if (Opcode
!= ISD::ANY_EXTEND_VECTOR_INREG
&&
18719 Opcode
!= ISD::SIGN_EXTEND_VECTOR_INREG
&&
18720 Opcode
!= ISD::ZERO_EXTEND_VECTOR_INREG
)
18723 SDValue N00
= N0
.getOperand(0);
18724 ArrayRef
<int> Mask
= SVN
->getMask();
18725 unsigned NumElts
= VT
.getVectorNumElements();
18726 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
18727 unsigned ExtSrcSizeInBits
= N00
.getScalarValueSizeInBits();
18728 unsigned ExtDstSizeInBits
= N0
.getScalarValueSizeInBits();
18730 if (ExtDstSizeInBits
% ExtSrcSizeInBits
!= 0)
18732 unsigned ExtScale
= ExtDstSizeInBits
/ ExtSrcSizeInBits
;
18734 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
18735 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
18736 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
18737 auto isTruncate
= [&Mask
, &NumElts
](unsigned Scale
) {
18738 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18741 if ((i
* Scale
) < NumElts
&& Mask
[i
] == (int)(i
* Scale
))
18748 // At the moment we just handle the case where we've truncated back to the
18749 // same size as before the extension.
18750 // TODO: handle more extension/truncation cases as cases arise.
18751 if (EltSizeInBits
!= ExtSrcSizeInBits
)
18754 // We can remove *extend_vector_inreg only if the truncation happens at
18755 // the same scale as the extension.
18756 if (isTruncate(ExtScale
))
18757 return DAG
.getBitcast(VT
, N00
);
18762 // Combine shuffles of splat-shuffles of the form:
18763 // shuffle (shuffle V, undef, splat-mask), undef, M
18764 // If splat-mask contains undef elements, we need to be careful about
18765 // introducing undef's in the folded mask which are not the result of composing
18766 // the masks of the shuffles.
18767 static SDValue
combineShuffleOfSplatVal(ShuffleVectorSDNode
*Shuf
,
18768 SelectionDAG
&DAG
) {
18769 if (!Shuf
->getOperand(1).isUndef())
18771 auto *Splat
= dyn_cast
<ShuffleVectorSDNode
>(Shuf
->getOperand(0));
18772 if (!Splat
|| !Splat
->isSplat())
18775 ArrayRef
<int> ShufMask
= Shuf
->getMask();
18776 ArrayRef
<int> SplatMask
= Splat
->getMask();
18777 assert(ShufMask
.size() == SplatMask
.size() && "Mask length mismatch");
18779 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
18780 // every undef mask element in the splat-shuffle has a corresponding undef
18781 // element in the user-shuffle's mask or if the composition of mask elements
18782 // would result in undef.
18783 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
18784 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
18785 // In this case it is not legal to simplify to the splat-shuffle because we
18786 // may be exposing the users of the shuffle an undef element at index 1
18787 // which was not there before the combine.
18788 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
18789 // In this case the composition of masks yields SplatMask, so it's ok to
18790 // simplify to the splat-shuffle.
18791 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
18792 // In this case the composed mask includes all undef elements of SplatMask
18793 // and in addition sets element zero to undef. It is safe to simplify to
18794 // the splat-shuffle.
18795 auto CanSimplifyToExistingSplat
= [](ArrayRef
<int> UserMask
,
18796 ArrayRef
<int> SplatMask
) {
18797 for (unsigned i
= 0, e
= UserMask
.size(); i
!= e
; ++i
)
18798 if (UserMask
[i
] != -1 && SplatMask
[i
] == -1 &&
18799 SplatMask
[UserMask
[i
]] != -1)
18803 if (CanSimplifyToExistingSplat(ShufMask
, SplatMask
))
18804 return Shuf
->getOperand(0);
18806 // Create a new shuffle with a mask that is composed of the two shuffles'
18808 SmallVector
<int, 32> NewMask
;
18809 for (int Idx
: ShufMask
)
18810 NewMask
.push_back(Idx
== -1 ? -1 : SplatMask
[Idx
]);
18812 return DAG
.getVectorShuffle(Splat
->getValueType(0), SDLoc(Splat
),
18813 Splat
->getOperand(0), Splat
->getOperand(1),
18817 /// If the shuffle mask is taking exactly one element from the first vector
18818 /// operand and passing through all other elements from the second vector
18819 /// operand, return the index of the mask element that is choosing an element
18820 /// from the first operand. Otherwise, return -1.
18821 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef
<int> Mask
) {
18822 int MaskSize
= Mask
.size();
18823 int EltFromOp0
= -1;
18824 // TODO: This does not match if there are undef elements in the shuffle mask.
18825 // Should we ignore undefs in the shuffle mask instead? The trade-off is
18826 // removing an instruction (a shuffle), but losing the knowledge that some
18827 // vector lanes are not needed.
18828 for (int i
= 0; i
!= MaskSize
; ++i
) {
18829 if (Mask
[i
] >= 0 && Mask
[i
] < MaskSize
) {
18830 // We're looking for a shuffle of exactly one element from operand 0.
18831 if (EltFromOp0
!= -1)
18834 } else if (Mask
[i
] != i
+ MaskSize
) {
18835 // Nothing from operand 1 can change lanes.
18842 /// If a shuffle inserts exactly one element from a source vector operand into
18843 /// another vector operand and we can access the specified element as a scalar,
18844 /// then we can eliminate the shuffle.
18845 static SDValue
replaceShuffleOfInsert(ShuffleVectorSDNode
*Shuf
,
18846 SelectionDAG
&DAG
) {
18847 // First, check if we are taking one element of a vector and shuffling that
18848 // element into another vector.
18849 ArrayRef
<int> Mask
= Shuf
->getMask();
18850 SmallVector
<int, 16> CommutedMask(Mask
.begin(), Mask
.end());
18851 SDValue Op0
= Shuf
->getOperand(0);
18852 SDValue Op1
= Shuf
->getOperand(1);
18853 int ShufOp0Index
= getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask
);
18854 if (ShufOp0Index
== -1) {
18855 // Commute mask and check again.
18856 ShuffleVectorSDNode::commuteMask(CommutedMask
);
18857 ShufOp0Index
= getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask
);
18858 if (ShufOp0Index
== -1)
18860 // Commute operands to match the commuted shuffle mask.
18861 std::swap(Op0
, Op1
);
18862 Mask
= CommutedMask
;
18865 // The shuffle inserts exactly one element from operand 0 into operand 1.
18866 // Now see if we can access that element as a scalar via a real insert element
18868 // TODO: We can try harder to locate the element as a scalar. Examples: it
18869 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
18870 assert(Mask
[ShufOp0Index
] >= 0 && Mask
[ShufOp0Index
] < (int)Mask
.size() &&
18871 "Shuffle mask value must be from operand 0");
18872 if (Op0
.getOpcode() != ISD::INSERT_VECTOR_ELT
)
18875 auto *InsIndexC
= dyn_cast
<ConstantSDNode
>(Op0
.getOperand(2));
18876 if (!InsIndexC
|| InsIndexC
->getSExtValue() != Mask
[ShufOp0Index
])
18879 // There's an existing insertelement with constant insertion index, so we
18880 // don't need to check the legality/profitability of a replacement operation
18881 // that differs at most in the constant value. The target should be able to
18882 // lower any of those in a similar way. If not, legalization will expand this
18883 // to a scalar-to-vector plus shuffle.
18885 // Note that the shuffle may move the scalar from the position that the insert
18886 // element used. Therefore, our new insert element occurs at the shuffle's
18887 // mask index value, not the insert's index value.
18888 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
18889 SDValue NewInsIndex
= DAG
.getConstant(ShufOp0Index
, SDLoc(Shuf
),
18890 Op0
.getOperand(2).getValueType());
18891 return DAG
.getNode(ISD::INSERT_VECTOR_ELT
, SDLoc(Shuf
), Op0
.getValueType(),
18892 Op1
, Op0
.getOperand(1), NewInsIndex
);
18895 /// If we have a unary shuffle of a shuffle, see if it can be folded away
18896 /// completely. This has the potential to lose undef knowledge because the first
18897 /// shuffle may not have an undef mask element where the second one does. So
18898 /// only call this after doing simplifications based on demanded elements.
18899 static SDValue
simplifyShuffleOfShuffle(ShuffleVectorSDNode
*Shuf
) {
18900 // shuf (shuf0 X, Y, Mask0), undef, Mask
18901 auto *Shuf0
= dyn_cast
<ShuffleVectorSDNode
>(Shuf
->getOperand(0));
18902 if (!Shuf0
|| !Shuf
->getOperand(1).isUndef())
18905 ArrayRef
<int> Mask
= Shuf
->getMask();
18906 ArrayRef
<int> Mask0
= Shuf0
->getMask();
18907 for (int i
= 0, e
= (int)Mask
.size(); i
!= e
; ++i
) {
18908 // Ignore undef elements.
18911 assert(Mask
[i
] >= 0 && Mask
[i
] < e
&& "Unexpected shuffle mask value");
18913 // Is the element of the shuffle operand chosen by this shuffle the same as
18914 // the element chosen by the shuffle operand itself?
18915 if (Mask0
[Mask
[i
]] != Mask0
[i
])
18918 // Every element of this shuffle is identical to the result of the previous
18919 // shuffle, so we can replace this value.
18920 return Shuf
->getOperand(0);
18923 SDValue
DAGCombiner::visitVECTOR_SHUFFLE(SDNode
*N
) {
18924 EVT VT
= N
->getValueType(0);
18925 unsigned NumElts
= VT
.getVectorNumElements();
18927 SDValue N0
= N
->getOperand(0);
18928 SDValue N1
= N
->getOperand(1);
18930 assert(N0
.getValueType() == VT
&& "Vector shuffle must be normalized in DAG");
18932 // Canonicalize shuffle undef, undef -> undef
18933 if (N0
.isUndef() && N1
.isUndef())
18934 return DAG
.getUNDEF(VT
);
18936 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N
);
18938 // Canonicalize shuffle v, v -> v, undef
18940 SmallVector
<int, 8> NewMask
;
18941 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18942 int Idx
= SVN
->getMaskElt(i
);
18943 if (Idx
>= (int)NumElts
) Idx
-= NumElts
;
18944 NewMask
.push_back(Idx
);
18946 return DAG
.getVectorShuffle(VT
, SDLoc(N
), N0
, DAG
.getUNDEF(VT
), NewMask
);
18949 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
18951 return DAG
.getCommutedVectorShuffle(*SVN
);
18953 // Remove references to rhs if it is undef
18954 if (N1
.isUndef()) {
18955 bool Changed
= false;
18956 SmallVector
<int, 8> NewMask
;
18957 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18958 int Idx
= SVN
->getMaskElt(i
);
18959 if (Idx
>= (int)NumElts
) {
18963 NewMask
.push_back(Idx
);
18966 return DAG
.getVectorShuffle(VT
, SDLoc(N
), N0
, N1
, NewMask
);
18969 if (SDValue InsElt
= replaceShuffleOfInsert(SVN
, DAG
))
18972 // A shuffle of a single vector that is a splatted value can always be folded.
18973 if (SDValue V
= combineShuffleOfSplatVal(SVN
, DAG
))
18976 // If it is a splat, check if the argument vector is another splat or a
18978 if (SVN
->isSplat() && SVN
->getSplatIndex() < (int)NumElts
) {
18979 int SplatIndex
= SVN
->getSplatIndex();
18980 if (TLI
.isExtractVecEltCheap(VT
, SplatIndex
) &&
18981 TLI
.isBinOp(N0
.getOpcode()) && N0
.getNode()->getNumValues() == 1) {
18982 // splat (vector_bo L, R), Index -->
18983 // splat (scalar_bo (extelt L, Index), (extelt R, Index))
18984 SDValue L
= N0
.getOperand(0), R
= N0
.getOperand(1);
18986 EVT EltVT
= VT
.getScalarType();
18987 SDValue Index
= DAG
.getIntPtrConstant(SplatIndex
, DL
);
18988 SDValue ExtL
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, L
, Index
);
18989 SDValue ExtR
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, R
, Index
);
18990 SDValue NewBO
= DAG
.getNode(N0
.getOpcode(), DL
, EltVT
, ExtL
, ExtR
,
18991 N0
.getNode()->getFlags());
18992 SDValue Insert
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, VT
, NewBO
);
18993 SmallVector
<int, 16> ZeroMask(VT
.getVectorNumElements(), 0);
18994 return DAG
.getVectorShuffle(VT
, DL
, Insert
, DAG
.getUNDEF(VT
), ZeroMask
);
18997 // If this is a bit convert that changes the element type of the vector but
18998 // not the number of vector elements, look through it. Be careful not to
18999 // look though conversions that change things like v4f32 to v2f64.
19000 SDNode
*V
= N0
.getNode();
19001 if (V
->getOpcode() == ISD::BITCAST
) {
19002 SDValue ConvInput
= V
->getOperand(0);
19003 if (ConvInput
.getValueType().isVector() &&
19004 ConvInput
.getValueType().getVectorNumElements() == NumElts
)
19005 V
= ConvInput
.getNode();
19008 if (V
->getOpcode() == ISD::BUILD_VECTOR
) {
19009 assert(V
->getNumOperands() == NumElts
&&
19010 "BUILD_VECTOR has wrong number of operands");
19012 bool AllSame
= true;
19013 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
19014 if (!V
->getOperand(i
).isUndef()) {
19015 Base
= V
->getOperand(i
);
19019 // Splat of <u, u, u, u>, return <u, u, u, u>
19020 if (!Base
.getNode())
19022 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
19023 if (V
->getOperand(i
) != Base
) {
19028 // Splat of <x, x, x, x>, return <x, x, x, x>
19032 // Canonicalize any other splat as a build_vector.
19033 SDValue Splatted
= V
->getOperand(SplatIndex
);
19034 SmallVector
<SDValue
, 8> Ops(NumElts
, Splatted
);
19035 SDValue NewBV
= DAG
.getBuildVector(V
->getValueType(0), SDLoc(N
), Ops
);
19037 // We may have jumped through bitcasts, so the type of the
19038 // BUILD_VECTOR may not match the type of the shuffle.
19039 if (V
->getValueType(0) != VT
)
19040 NewBV
= DAG
.getBitcast(VT
, NewBV
);
19045 // Simplify source operands based on shuffle mask.
19046 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
19047 return SDValue(N
, 0);
19049 // This is intentionally placed after demanded elements simplification because
19050 // it could eliminate knowledge of undef elements created by this shuffle.
19051 if (SDValue ShufOp
= simplifyShuffleOfShuffle(SVN
))
19054 // Match shuffles that can be converted to any_vector_extend_in_reg.
19055 if (SDValue V
= combineShuffleToVectorExtend(SVN
, DAG
, TLI
, LegalOperations
))
19058 // Combine "truncate_vector_in_reg" style shuffles.
19059 if (SDValue V
= combineTruncationShuffle(SVN
, DAG
))
19062 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&&
19063 Level
< AfterLegalizeVectorOps
&&
19065 (N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
19066 N0
.getOperand(0).getValueType() == N1
.getOperand(0).getValueType()))) {
19067 if (SDValue V
= partitionShuffleOfConcats(N
, DAG
))
19071 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
19072 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
19073 if (Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
))
19074 if (SDValue Res
= combineShuffleOfScalars(SVN
, DAG
, TLI
))
19077 // If this shuffle only has a single input that is a bitcasted shuffle,
19078 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
19079 // back to their original types.
19080 if (N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse() &&
19081 N1
.isUndef() && Level
< AfterLegalizeVectorOps
&&
19082 TLI
.isTypeLegal(VT
)) {
19083 auto ScaleShuffleMask
= [](ArrayRef
<int> Mask
, int Scale
) {
19085 return SmallVector
<int, 8>(Mask
.begin(), Mask
.end());
19087 SmallVector
<int, 8> NewMask
;
19089 for (int s
= 0; s
!= Scale
; ++s
)
19090 NewMask
.push_back(M
< 0 ? -1 : Scale
* M
+ s
);
19094 SDValue BC0
= peekThroughOneUseBitcasts(N0
);
19095 if (BC0
.getOpcode() == ISD::VECTOR_SHUFFLE
&& BC0
.hasOneUse()) {
19096 EVT SVT
= VT
.getScalarType();
19097 EVT InnerVT
= BC0
->getValueType(0);
19098 EVT InnerSVT
= InnerVT
.getScalarType();
19100 // Determine which shuffle works with the smaller scalar type.
19101 EVT ScaleVT
= SVT
.bitsLT(InnerSVT
) ? VT
: InnerVT
;
19102 EVT ScaleSVT
= ScaleVT
.getScalarType();
19104 if (TLI
.isTypeLegal(ScaleVT
) &&
19105 0 == (InnerSVT
.getSizeInBits() % ScaleSVT
.getSizeInBits()) &&
19106 0 == (SVT
.getSizeInBits() % ScaleSVT
.getSizeInBits())) {
19107 int InnerScale
= InnerSVT
.getSizeInBits() / ScaleSVT
.getSizeInBits();
19108 int OuterScale
= SVT
.getSizeInBits() / ScaleSVT
.getSizeInBits();
19110 // Scale the shuffle masks to the smaller scalar type.
19111 ShuffleVectorSDNode
*InnerSVN
= cast
<ShuffleVectorSDNode
>(BC0
);
19112 SmallVector
<int, 8> InnerMask
=
19113 ScaleShuffleMask(InnerSVN
->getMask(), InnerScale
);
19114 SmallVector
<int, 8> OuterMask
=
19115 ScaleShuffleMask(SVN
->getMask(), OuterScale
);
19117 // Merge the shuffle masks.
19118 SmallVector
<int, 8> NewMask
;
19119 for (int M
: OuterMask
)
19120 NewMask
.push_back(M
< 0 ? -1 : InnerMask
[M
]);
19122 // Test for shuffle mask legality over both commutations.
19123 SDValue SV0
= BC0
->getOperand(0);
19124 SDValue SV1
= BC0
->getOperand(1);
19125 bool LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, ScaleVT
);
19127 std::swap(SV0
, SV1
);
19128 ShuffleVectorSDNode::commuteMask(NewMask
);
19129 LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, ScaleVT
);
19133 SV0
= DAG
.getBitcast(ScaleVT
, SV0
);
19134 SV1
= DAG
.getBitcast(ScaleVT
, SV1
);
19135 return DAG
.getBitcast(
19136 VT
, DAG
.getVectorShuffle(ScaleVT
, SDLoc(N
), SV0
, SV1
, NewMask
));
19142 // Canonicalize shuffles according to rules:
19143 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
19144 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
19145 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
19146 if (N1
.getOpcode() == ISD::VECTOR_SHUFFLE
&&
19147 N0
.getOpcode() != ISD::VECTOR_SHUFFLE
&& Level
< AfterLegalizeDAG
&&
19148 TLI
.isTypeLegal(VT
)) {
19149 // The incoming shuffle must be of the same type as the result of the
19150 // current shuffle.
19151 assert(N1
->getOperand(0).getValueType() == VT
&&
19152 "Shuffle types don't match");
19154 SDValue SV0
= N1
->getOperand(0);
19155 SDValue SV1
= N1
->getOperand(1);
19156 bool HasSameOp0
= N0
== SV0
;
19157 bool IsSV1Undef
= SV1
.isUndef();
19158 if (HasSameOp0
|| IsSV1Undef
|| N0
== SV1
)
19159 // Commute the operands of this shuffle so that next rule
19161 return DAG
.getCommutedVectorShuffle(*SVN
);
19164 // Try to fold according to rules:
19165 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
19166 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
19167 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
19168 // Don't try to fold shuffles with illegal type.
19169 // Only fold if this shuffle is the only user of the other shuffle.
19170 if (N0
.getOpcode() == ISD::VECTOR_SHUFFLE
&& N
->isOnlyUserOf(N0
.getNode()) &&
19171 Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
)) {
19172 ShuffleVectorSDNode
*OtherSV
= cast
<ShuffleVectorSDNode
>(N0
);
19174 // Don't try to fold splats; they're likely to simplify somehow, or they
19176 if (OtherSV
->isSplat())
19179 // The incoming shuffle must be of the same type as the result of the
19180 // current shuffle.
19181 assert(OtherSV
->getOperand(0).getValueType() == VT
&&
19182 "Shuffle types don't match");
19185 SmallVector
<int, 4> Mask
;
19186 // Compute the combined shuffle mask for a shuffle with SV0 as the first
19187 // operand, and SV1 as the second operand.
19188 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
19189 int Idx
= SVN
->getMaskElt(i
);
19191 // Propagate Undef.
19192 Mask
.push_back(Idx
);
19196 SDValue CurrentVec
;
19197 if (Idx
< (int)NumElts
) {
19198 // This shuffle index refers to the inner shuffle N0. Lookup the inner
19199 // shuffle mask to identify which vector is actually referenced.
19200 Idx
= OtherSV
->getMaskElt(Idx
);
19202 // Propagate Undef.
19203 Mask
.push_back(Idx
);
19207 CurrentVec
= (Idx
< (int) NumElts
) ? OtherSV
->getOperand(0)
19208 : OtherSV
->getOperand(1);
19210 // This shuffle index references an element within N1.
19214 // Simple case where 'CurrentVec' is UNDEF.
19215 if (CurrentVec
.isUndef()) {
19216 Mask
.push_back(-1);
19220 // Canonicalize the shuffle index. We don't know yet if CurrentVec
19221 // will be the first or second operand of the combined shuffle.
19222 Idx
= Idx
% NumElts
;
19223 if (!SV0
.getNode() || SV0
== CurrentVec
) {
19224 // Ok. CurrentVec is the left hand side.
19225 // Update the mask accordingly.
19227 Mask
.push_back(Idx
);
19231 // Bail out if we cannot convert the shuffle pair into a single shuffle.
19232 if (SV1
.getNode() && SV1
!= CurrentVec
)
19235 // Ok. CurrentVec is the right hand side.
19236 // Update the mask accordingly.
19238 Mask
.push_back(Idx
+ NumElts
);
19241 // Check if all indices in Mask are Undef. In case, propagate Undef.
19242 bool isUndefMask
= true;
19243 for (unsigned i
= 0; i
!= NumElts
&& isUndefMask
; ++i
)
19244 isUndefMask
&= Mask
[i
] < 0;
19247 return DAG
.getUNDEF(VT
);
19249 if (!SV0
.getNode())
19250 SV0
= DAG
.getUNDEF(VT
);
19251 if (!SV1
.getNode())
19252 SV1
= DAG
.getUNDEF(VT
);
19254 // Avoid introducing shuffles with illegal mask.
19255 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
19256 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
19257 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
19258 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
19259 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
19260 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
19261 return TLI
.buildLegalVectorShuffle(VT
, SDLoc(N
), SV0
, SV1
, Mask
, DAG
);
19264 if (SDValue V
= foldShuffleOfConcatUndefs(SVN
, DAG
))
19270 SDValue
DAGCombiner::visitSCALAR_TO_VECTOR(SDNode
*N
) {
19271 SDValue InVal
= N
->getOperand(0);
19272 EVT VT
= N
->getValueType(0);
19274 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
19275 // with a VECTOR_SHUFFLE and possible truncate.
19276 if (InVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) {
19277 SDValue InVec
= InVal
->getOperand(0);
19278 SDValue EltNo
= InVal
->getOperand(1);
19279 auto InVecT
= InVec
.getValueType();
19280 if (ConstantSDNode
*C0
= dyn_cast
<ConstantSDNode
>(EltNo
)) {
19281 SmallVector
<int, 8> NewMask(InVecT
.getVectorNumElements(), -1);
19282 int Elt
= C0
->getZExtValue();
19284 // If we have an implict truncate do truncate here as long as it's legal.
19285 // if it's not legal, this should
19286 if (VT
.getScalarType() != InVal
.getValueType() &&
19287 InVal
.getValueType().isScalarInteger() &&
19288 isTypeLegal(VT
.getScalarType())) {
19290 DAG
.getNode(ISD::TRUNCATE
, SDLoc(InVal
), VT
.getScalarType(), InVal
);
19291 return DAG
.getNode(ISD::SCALAR_TO_VECTOR
, SDLoc(N
), VT
, Val
);
19293 if (VT
.getScalarType() == InVecT
.getScalarType() &&
19294 VT
.getVectorNumElements() <= InVecT
.getVectorNumElements()) {
19295 SDValue LegalShuffle
=
19296 TLI
.buildLegalVectorShuffle(InVecT
, SDLoc(N
), InVec
,
19297 DAG
.getUNDEF(InVecT
), NewMask
, DAG
);
19298 if (LegalShuffle
) {
19299 // If the initial vector is the correct size this shuffle is a
19302 return LegalShuffle
;
19303 // If not we must truncate the vector.
19304 if (VT
.getVectorNumElements() != InVecT
.getVectorNumElements()) {
19305 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
19306 SDValue ZeroIdx
= DAG
.getConstant(0, SDLoc(N
), IdxTy
);
19308 EVT::getVectorVT(*DAG
.getContext(), InVecT
.getVectorElementType(),
19309 VT
.getVectorNumElements());
19310 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), SubVT
,
19311 LegalShuffle
, ZeroIdx
);
19321 SDValue
DAGCombiner::visitINSERT_SUBVECTOR(SDNode
*N
) {
19322 EVT VT
= N
->getValueType(0);
19323 SDValue N0
= N
->getOperand(0);
19324 SDValue N1
= N
->getOperand(1);
19325 SDValue N2
= N
->getOperand(2);
19327 // If inserting an UNDEF, just return the original vector.
19331 // If this is an insert of an extracted vector into an undef vector, we can
19332 // just use the input to the extract.
19333 if (N0
.isUndef() && N1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
19334 N1
.getOperand(1) == N2
&& N1
.getOperand(0).getValueType() == VT
)
19335 return N1
.getOperand(0);
19337 // If we are inserting a bitcast value into an undef, with the same
19338 // number of elements, just use the bitcast input of the extract.
19339 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
19340 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
19341 if (N0
.isUndef() && N1
.getOpcode() == ISD::BITCAST
&&
19342 N1
.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
19343 N1
.getOperand(0).getOperand(1) == N2
&&
19344 N1
.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
19345 VT
.getVectorNumElements() &&
19346 N1
.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
19347 VT
.getSizeInBits()) {
19348 return DAG
.getBitcast(VT
, N1
.getOperand(0).getOperand(0));
19351 // If both N1 and N2 are bitcast values on which insert_subvector
19352 // would makes sense, pull the bitcast through.
19353 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
19354 // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
19355 if (N0
.getOpcode() == ISD::BITCAST
&& N1
.getOpcode() == ISD::BITCAST
) {
19356 SDValue CN0
= N0
.getOperand(0);
19357 SDValue CN1
= N1
.getOperand(0);
19358 EVT CN0VT
= CN0
.getValueType();
19359 EVT CN1VT
= CN1
.getValueType();
19360 if (CN0VT
.isVector() && CN1VT
.isVector() &&
19361 CN0VT
.getVectorElementType() == CN1VT
.getVectorElementType() &&
19362 CN0VT
.getVectorNumElements() == VT
.getVectorNumElements()) {
19363 SDValue NewINSERT
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
),
19364 CN0
.getValueType(), CN0
, CN1
, N2
);
19365 return DAG
.getBitcast(VT
, NewINSERT
);
19369 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
19370 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
19371 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
19372 if (N0
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
19373 N0
.getOperand(1).getValueType() == N1
.getValueType() &&
19374 N0
.getOperand(2) == N2
)
19375 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
, N0
.getOperand(0),
19378 // Eliminate an intermediate insert into an undef vector:
19379 // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
19380 // insert_subvector undef, X, N2
19381 if (N0
.isUndef() && N1
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
19382 N1
.getOperand(0).isUndef() && isNullConstant(N1
.getOperand(2)))
19383 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
, N0
,
19384 N1
.getOperand(1), N2
);
19386 if (!isa
<ConstantSDNode
>(N2
))
19389 uint64_t InsIdx
= cast
<ConstantSDNode
>(N2
)->getZExtValue();
19391 // Push subvector bitcasts to the output, adjusting the index as we go.
19392 // insert_subvector(bitcast(v), bitcast(s), c1)
19393 // -> bitcast(insert_subvector(v, s, c2))
19394 if ((N0
.isUndef() || N0
.getOpcode() == ISD::BITCAST
) &&
19395 N1
.getOpcode() == ISD::BITCAST
) {
19396 SDValue N0Src
= peekThroughBitcasts(N0
);
19397 SDValue N1Src
= peekThroughBitcasts(N1
);
19398 EVT N0SrcSVT
= N0Src
.getValueType().getScalarType();
19399 EVT N1SrcSVT
= N1Src
.getValueType().getScalarType();
19400 if ((N0
.isUndef() || N0SrcSVT
== N1SrcSVT
) &&
19401 N0Src
.getValueType().isVector() && N1Src
.getValueType().isVector()) {
19405 MVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
19406 LLVMContext
&Ctx
= *DAG
.getContext();
19407 unsigned NumElts
= VT
.getVectorNumElements();
19408 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
19409 if ((EltSizeInBits
% N1SrcSVT
.getSizeInBits()) == 0) {
19410 unsigned Scale
= EltSizeInBits
/ N1SrcSVT
.getSizeInBits();
19411 NewVT
= EVT::getVectorVT(Ctx
, N1SrcSVT
, NumElts
* Scale
);
19412 NewIdx
= DAG
.getConstant(InsIdx
* Scale
, DL
, IdxVT
);
19413 } else if ((N1SrcSVT
.getSizeInBits() % EltSizeInBits
) == 0) {
19414 unsigned Scale
= N1SrcSVT
.getSizeInBits() / EltSizeInBits
;
19415 if ((NumElts
% Scale
) == 0 && (InsIdx
% Scale
) == 0) {
19416 NewVT
= EVT::getVectorVT(Ctx
, N1SrcSVT
, NumElts
/ Scale
);
19417 NewIdx
= DAG
.getConstant(InsIdx
/ Scale
, DL
, IdxVT
);
19420 if (NewIdx
&& hasOperation(ISD::INSERT_SUBVECTOR
, NewVT
)) {
19421 SDValue Res
= DAG
.getBitcast(NewVT
, N0Src
);
19422 Res
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, NewVT
, Res
, N1Src
, NewIdx
);
19423 return DAG
.getBitcast(VT
, Res
);
19428 // Canonicalize insert_subvector dag nodes.
19430 // (insert_subvector (insert_subvector A, Idx0), Idx1)
19431 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
19432 if (N0
.getOpcode() == ISD::INSERT_SUBVECTOR
&& N0
.hasOneUse() &&
19433 N1
.getValueType() == N0
.getOperand(1).getValueType() &&
19434 isa
<ConstantSDNode
>(N0
.getOperand(2))) {
19435 unsigned OtherIdx
= N0
.getConstantOperandVal(2);
19436 if (InsIdx
< OtherIdx
) {
19438 SDValue NewOp
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
,
19439 N0
.getOperand(0), N1
, N2
);
19440 AddToWorklist(NewOp
.getNode());
19441 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N0
.getNode()),
19442 VT
, NewOp
, N0
.getOperand(1), N0
.getOperand(2));
19446 // If the input vector is a concatenation, and the insert replaces
19447 // one of the pieces, we can optimize into a single concat_vectors.
19448 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&& N0
.hasOneUse() &&
19449 N0
.getOperand(0).getValueType() == N1
.getValueType()) {
19450 unsigned Factor
= N1
.getValueType().getVectorNumElements();
19452 SmallVector
<SDValue
, 8> Ops(N0
->op_begin(), N0
->op_end());
19453 Ops
[cast
<ConstantSDNode
>(N2
)->getZExtValue() / Factor
] = N1
;
19455 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
19458 // Simplify source operands based on insertion.
19459 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
19460 return SDValue(N
, 0);
19465 SDValue
DAGCombiner::visitFP_TO_FP16(SDNode
*N
) {
19466 SDValue N0
= N
->getOperand(0);
19468 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
19469 if (N0
->getOpcode() == ISD::FP16_TO_FP
)
19470 return N0
->getOperand(0);
19475 SDValue
DAGCombiner::visitFP16_TO_FP(SDNode
*N
) {
19476 SDValue N0
= N
->getOperand(0);
19478 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
19479 if (N0
->getOpcode() == ISD::AND
) {
19480 ConstantSDNode
*AndConst
= getAsNonOpaqueConstant(N0
.getOperand(1));
19481 if (AndConst
&& AndConst
->getAPIntValue() == 0xffff) {
19482 return DAG
.getNode(ISD::FP16_TO_FP
, SDLoc(N
), N
->getValueType(0),
19490 SDValue
DAGCombiner::visitVECREDUCE(SDNode
*N
) {
19491 SDValue N0
= N
->getOperand(0);
19492 EVT VT
= N0
.getValueType();
19493 unsigned Opcode
= N
->getOpcode();
19495 // VECREDUCE over 1-element vector is just an extract.
19496 if (VT
.getVectorNumElements() == 1) {
19498 SDValue Res
= DAG
.getNode(
19499 ISD::EXTRACT_VECTOR_ELT
, dl
, VT
.getVectorElementType(), N0
,
19500 DAG
.getConstant(0, dl
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
19501 if (Res
.getValueType() != N
->getValueType(0))
19502 Res
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, N
->getValueType(0), Res
);
19506 // On an boolean vector an and/or reduction is the same as a umin/umax
19507 // reduction. Convert them if the latter is legal while the former isn't.
19508 if (Opcode
== ISD::VECREDUCE_AND
|| Opcode
== ISD::VECREDUCE_OR
) {
19509 unsigned NewOpcode
= Opcode
== ISD::VECREDUCE_AND
19510 ? ISD::VECREDUCE_UMIN
: ISD::VECREDUCE_UMAX
;
19511 if (!TLI
.isOperationLegalOrCustom(Opcode
, VT
) &&
19512 TLI
.isOperationLegalOrCustom(NewOpcode
, VT
) &&
19513 DAG
.ComputeNumSignBits(N0
) == VT
.getScalarSizeInBits())
19514 return DAG
.getNode(NewOpcode
, SDLoc(N
), N
->getValueType(0), N0
);
19520 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
19521 /// with the destination vector and a zero vector.
19522 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
19523 /// vector_shuffle V, Zero, <0, 4, 2, 4>
19524 SDValue
DAGCombiner::XformToShuffleWithZero(SDNode
*N
) {
19525 assert(N
->getOpcode() == ISD::AND
&& "Unexpected opcode!");
19527 EVT VT
= N
->getValueType(0);
19528 SDValue LHS
= N
->getOperand(0);
19529 SDValue RHS
= peekThroughBitcasts(N
->getOperand(1));
19532 // Make sure we're not running after operation legalization where it
19533 // may have custom lowered the vector shuffles.
19534 if (LegalOperations
)
19537 if (RHS
.getOpcode() != ISD::BUILD_VECTOR
)
19540 EVT RVT
= RHS
.getValueType();
19541 unsigned NumElts
= RHS
.getNumOperands();
19543 // Attempt to create a valid clear mask, splitting the mask into
19544 // sub elements and checking to see if each is
19545 // all zeros or all ones - suitable for shuffle masking.
19546 auto BuildClearMask
= [&](int Split
) {
19547 int NumSubElts
= NumElts
* Split
;
19548 int NumSubBits
= RVT
.getScalarSizeInBits() / Split
;
19550 SmallVector
<int, 8> Indices
;
19551 for (int i
= 0; i
!= NumSubElts
; ++i
) {
19552 int EltIdx
= i
/ Split
;
19553 int SubIdx
= i
% Split
;
19554 SDValue Elt
= RHS
.getOperand(EltIdx
);
19555 if (Elt
.isUndef()) {
19556 Indices
.push_back(-1);
19561 if (isa
<ConstantSDNode
>(Elt
))
19562 Bits
= cast
<ConstantSDNode
>(Elt
)->getAPIntValue();
19563 else if (isa
<ConstantFPSDNode
>(Elt
))
19564 Bits
= cast
<ConstantFPSDNode
>(Elt
)->getValueAPF().bitcastToAPInt();
19568 // Extract the sub element from the constant bit mask.
19569 if (DAG
.getDataLayout().isBigEndian()) {
19570 Bits
.lshrInPlace((Split
- SubIdx
- 1) * NumSubBits
);
19572 Bits
.lshrInPlace(SubIdx
* NumSubBits
);
19576 Bits
= Bits
.trunc(NumSubBits
);
19578 if (Bits
.isAllOnesValue())
19579 Indices
.push_back(i
);
19580 else if (Bits
== 0)
19581 Indices
.push_back(i
+ NumSubElts
);
19586 // Let's see if the target supports this vector_shuffle.
19587 EVT ClearSVT
= EVT::getIntegerVT(*DAG
.getContext(), NumSubBits
);
19588 EVT ClearVT
= EVT::getVectorVT(*DAG
.getContext(), ClearSVT
, NumSubElts
);
19589 if (!TLI
.isVectorClearMaskLegal(Indices
, ClearVT
))
19592 SDValue Zero
= DAG
.getConstant(0, DL
, ClearVT
);
19593 return DAG
.getBitcast(VT
, DAG
.getVectorShuffle(ClearVT
, DL
,
19594 DAG
.getBitcast(ClearVT
, LHS
),
19598 // Determine maximum split level (byte level masking).
19600 if (RVT
.getScalarSizeInBits() % 8 == 0)
19601 MaxSplit
= RVT
.getScalarSizeInBits() / 8;
19603 for (int Split
= 1; Split
<= MaxSplit
; ++Split
)
19604 if (RVT
.getScalarSizeInBits() % Split
== 0)
19605 if (SDValue S
= BuildClearMask(Split
))
19611 /// If a vector binop is performed on splat values, it may be profitable to
19612 /// extract, scalarize, and insert/splat.
19613 static SDValue
scalarizeBinOpOfSplats(SDNode
*N
, SelectionDAG
&DAG
) {
19614 SDValue N0
= N
->getOperand(0);
19615 SDValue N1
= N
->getOperand(1);
19616 unsigned Opcode
= N
->getOpcode();
19617 EVT VT
= N
->getValueType(0);
19618 EVT EltVT
= VT
.getVectorElementType();
19619 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
19621 // TODO: Remove/replace the extract cost check? If the elements are available
19622 // as scalars, then there may be no extract cost. Should we ask if
19623 // inserting a scalar back into a vector is cheap instead?
19624 int Index0
, Index1
;
19625 SDValue Src0
= DAG
.getSplatSourceVector(N0
, Index0
);
19626 SDValue Src1
= DAG
.getSplatSourceVector(N1
, Index1
);
19627 if (!Src0
|| !Src1
|| Index0
!= Index1
||
19628 Src0
.getValueType().getVectorElementType() != EltVT
||
19629 Src1
.getValueType().getVectorElementType() != EltVT
||
19630 !TLI
.isExtractVecEltCheap(VT
, Index0
) ||
19631 !TLI
.isOperationLegalOrCustom(Opcode
, EltVT
))
19636 DAG
.getConstant(Index0
, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout()));
19637 SDValue X
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, N0
, IndexC
);
19638 SDValue Y
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, N1
, IndexC
);
19639 SDValue ScalarBO
= DAG
.getNode(Opcode
, DL
, EltVT
, X
, Y
, N
->getFlags());
19641 // If all lanes but 1 are undefined, no need to splat the scalar result.
19642 // TODO: Keep track of undefs and use that info in the general case.
19643 if (N0
.getOpcode() == ISD::BUILD_VECTOR
&& N0
.getOpcode() == N1
.getOpcode() &&
19644 count_if(N0
->ops(), [](SDValue V
) { return !V
.isUndef(); }) == 1 &&
19645 count_if(N1
->ops(), [](SDValue V
) { return !V
.isUndef(); }) == 1) {
19646 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
19647 // build_vec ..undef, (bo X, Y), undef...
19648 SmallVector
<SDValue
, 8> Ops(VT
.getVectorNumElements(), DAG
.getUNDEF(EltVT
));
19649 Ops
[Index0
] = ScalarBO
;
19650 return DAG
.getBuildVector(VT
, DL
, Ops
);
19653 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
19654 SmallVector
<SDValue
, 8> Ops(VT
.getVectorNumElements(), ScalarBO
);
19655 return DAG
.getBuildVector(VT
, DL
, Ops
);
19658 /// Visit a binary vector operation, like ADD.
19659 SDValue
DAGCombiner::SimplifyVBinOp(SDNode
*N
) {
19660 assert(N
->getValueType(0).isVector() &&
19661 "SimplifyVBinOp only works on vectors!");
19663 SDValue LHS
= N
->getOperand(0);
19664 SDValue RHS
= N
->getOperand(1);
19665 SDValue Ops
[] = {LHS
, RHS
};
19666 EVT VT
= N
->getValueType(0);
19667 unsigned Opcode
= N
->getOpcode();
19669 // See if we can constant fold the vector operation.
19670 if (SDValue Fold
= DAG
.FoldConstantVectorArithmetic(
19671 Opcode
, SDLoc(LHS
), LHS
.getValueType(), Ops
, N
->getFlags()))
19674 // Move unary shuffles with identical masks after a vector binop:
19675 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
19676 // --> shuffle (VBinOp A, B), Undef, Mask
19677 // This does not require type legality checks because we are creating the
19678 // same types of operations that are in the original sequence. We do have to
19679 // restrict ops like integer div that have immediate UB (eg, div-by-zero)
19680 // though. This code is adapted from the identical transform in instcombine.
19681 if (Opcode
!= ISD::UDIV
&& Opcode
!= ISD::SDIV
&&
19682 Opcode
!= ISD::UREM
&& Opcode
!= ISD::SREM
&&
19683 Opcode
!= ISD::UDIVREM
&& Opcode
!= ISD::SDIVREM
) {
19684 auto *Shuf0
= dyn_cast
<ShuffleVectorSDNode
>(LHS
);
19685 auto *Shuf1
= dyn_cast
<ShuffleVectorSDNode
>(RHS
);
19686 if (Shuf0
&& Shuf1
&& Shuf0
->getMask().equals(Shuf1
->getMask()) &&
19687 LHS
.getOperand(1).isUndef() && RHS
.getOperand(1).isUndef() &&
19688 (LHS
.hasOneUse() || RHS
.hasOneUse() || LHS
== RHS
)) {
19690 SDValue NewBinOp
= DAG
.getNode(Opcode
, DL
, VT
, LHS
.getOperand(0),
19691 RHS
.getOperand(0), N
->getFlags());
19692 SDValue UndefV
= LHS
.getOperand(1);
19693 return DAG
.getVectorShuffle(VT
, DL
, NewBinOp
, UndefV
, Shuf0
->getMask());
19697 // The following pattern is likely to emerge with vector reduction ops. Moving
19698 // the binary operation ahead of insertion may allow using a narrower vector
19699 // instruction that has better performance than the wide version of the op:
19700 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
19701 if (LHS
.getOpcode() == ISD::INSERT_SUBVECTOR
&& LHS
.getOperand(0).isUndef() &&
19702 RHS
.getOpcode() == ISD::INSERT_SUBVECTOR
&& RHS
.getOperand(0).isUndef() &&
19703 LHS
.getOperand(2) == RHS
.getOperand(2) &&
19704 (LHS
.hasOneUse() || RHS
.hasOneUse())) {
19705 SDValue X
= LHS
.getOperand(1);
19706 SDValue Y
= RHS
.getOperand(1);
19707 SDValue Z
= LHS
.getOperand(2);
19708 EVT NarrowVT
= X
.getValueType();
19709 if (NarrowVT
== Y
.getValueType() &&
19710 TLI
.isOperationLegalOrCustomOrPromote(Opcode
, NarrowVT
)) {
19711 // (binop undef, undef) may not return undef, so compute that result.
19714 DAG
.getNode(Opcode
, DL
, VT
, DAG
.getUNDEF(VT
), DAG
.getUNDEF(VT
));
19715 SDValue NarrowBO
= DAG
.getNode(Opcode
, DL
, NarrowVT
, X
, Y
);
19716 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, VT
, VecC
, NarrowBO
, Z
);
19720 // Make sure all but the first op are undef or constant.
19721 auto ConcatWithConstantOrUndef
= [](SDValue Concat
) {
19722 return Concat
.getOpcode() == ISD::CONCAT_VECTORS
&&
19723 std::all_of(std::next(Concat
->op_begin()), Concat
->op_end(),
19724 [](const SDValue
&Op
) {
19725 return Op
.isUndef() ||
19726 ISD::isBuildVectorOfConstantSDNodes(Op
.getNode());
19730 // The following pattern is likely to emerge with vector reduction ops. Moving
19731 // the binary operation ahead of the concat may allow using a narrower vector
19732 // instruction that has better performance than the wide version of the op:
19733 // VBinOp (concat X, undef/constant), (concat Y, undef/constant) -->
19734 // concat (VBinOp X, Y), VecC
19735 if (ConcatWithConstantOrUndef(LHS
) && ConcatWithConstantOrUndef(RHS
) &&
19736 (LHS
.hasOneUse() || RHS
.hasOneUse())) {
19737 EVT NarrowVT
= LHS
.getOperand(0).getValueType();
19738 if (NarrowVT
== RHS
.getOperand(0).getValueType() &&
19739 TLI
.isOperationLegalOrCustomOrPromote(Opcode
, NarrowVT
)) {
19741 unsigned NumOperands
= LHS
.getNumOperands();
19742 SmallVector
<SDValue
, 4> ConcatOps
;
19743 for (unsigned i
= 0; i
!= NumOperands
; ++i
) {
19744 // This constant fold for operands 1 and up.
19745 ConcatOps
.push_back(DAG
.getNode(Opcode
, DL
, NarrowVT
, LHS
.getOperand(i
),
19746 RHS
.getOperand(i
)));
19749 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
);
19753 if (SDValue V
= scalarizeBinOpOfSplats(N
, DAG
))
19759 SDValue
DAGCombiner::SimplifySelect(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
19761 assert(N0
.getOpcode() ==ISD::SETCC
&& "First argument must be a SetCC node!");
19763 SDValue SCC
= SimplifySelectCC(DL
, N0
.getOperand(0), N0
.getOperand(1), N1
, N2
,
19764 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
19766 // If we got a simplified select_cc node back from SimplifySelectCC, then
19767 // break it down into a new SETCC node, and a new SELECT node, and then return
19768 // the SELECT node, since we were called with a SELECT node.
19769 if (SCC
.getNode()) {
19770 // Check to see if we got a select_cc back (to turn into setcc/select).
19771 // Otherwise, just return whatever node we got back, like fabs.
19772 if (SCC
.getOpcode() == ISD::SELECT_CC
) {
19773 const SDNodeFlags Flags
= N0
.getNode()->getFlags();
19774 SDValue SETCC
= DAG
.getNode(ISD::SETCC
, SDLoc(N0
),
19776 SCC
.getOperand(0), SCC
.getOperand(1),
19777 SCC
.getOperand(4), Flags
);
19778 AddToWorklist(SETCC
.getNode());
19779 SDValue SelectNode
= DAG
.getSelect(SDLoc(SCC
), SCC
.getValueType(), SETCC
,
19780 SCC
.getOperand(2), SCC
.getOperand(3));
19781 SelectNode
->setFlags(Flags
);
19790 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
19791 /// being selected between, see if we can simplify the select. Callers of this
19792 /// should assume that TheSelect is deleted if this returns true. As such, they
19793 /// should return the appropriate thing (e.g. the node) back to the top-level of
19794 /// the DAG combiner loop to avoid it being looked at.
19795 bool DAGCombiner::SimplifySelectOps(SDNode
*TheSelect
, SDValue LHS
,
19797 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19798 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
19799 if (const ConstantFPSDNode
*NaN
= isConstOrConstSplatFP(LHS
)) {
19800 if (NaN
->isNaN() && RHS
.getOpcode() == ISD::FSQRT
) {
19801 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
19802 SDValue Sqrt
= RHS
;
19805 const ConstantFPSDNode
*Zero
= nullptr;
19807 if (TheSelect
->getOpcode() == ISD::SELECT_CC
) {
19808 CC
= cast
<CondCodeSDNode
>(TheSelect
->getOperand(4))->get();
19809 CmpLHS
= TheSelect
->getOperand(0);
19810 Zero
= isConstOrConstSplatFP(TheSelect
->getOperand(1));
19812 // SELECT or VSELECT
19813 SDValue Cmp
= TheSelect
->getOperand(0);
19814 if (Cmp
.getOpcode() == ISD::SETCC
) {
19815 CC
= cast
<CondCodeSDNode
>(Cmp
.getOperand(2))->get();
19816 CmpLHS
= Cmp
.getOperand(0);
19817 Zero
= isConstOrConstSplatFP(Cmp
.getOperand(1));
19820 if (Zero
&& Zero
->isZero() &&
19821 Sqrt
.getOperand(0) == CmpLHS
&& (CC
== ISD::SETOLT
||
19822 CC
== ISD::SETULT
|| CC
== ISD::SETLT
)) {
19823 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19824 CombineTo(TheSelect
, Sqrt
);
19829 // Cannot simplify select with vector condition
19830 if (TheSelect
->getOperand(0).getValueType().isVector()) return false;
19832 // If this is a select from two identical things, try to pull the operation
19833 // through the select.
19834 if (LHS
.getOpcode() != RHS
.getOpcode() ||
19835 !LHS
.hasOneUse() || !RHS
.hasOneUse())
19838 // If this is a load and the token chain is identical, replace the select
19839 // of two loads with a load through a select of the address to load from.
19840 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
19841 // constants have been dropped into the constant pool.
19842 if (LHS
.getOpcode() == ISD::LOAD
) {
19843 LoadSDNode
*LLD
= cast
<LoadSDNode
>(LHS
);
19844 LoadSDNode
*RLD
= cast
<LoadSDNode
>(RHS
);
19846 // Token chains must be identical.
19847 if (LHS
.getOperand(0) != RHS
.getOperand(0) ||
19848 // Do not let this transformation reduce the number of volatile loads.
19849 // Be conservative for atomics for the moment
19850 // TODO: This does appear to be legal for unordered atomics (see D66309)
19851 !LLD
->isSimple() || !RLD
->isSimple() ||
19852 // FIXME: If either is a pre/post inc/dec load,
19853 // we'd need to split out the address adjustment.
19854 LLD
->isIndexed() || RLD
->isIndexed() ||
19855 // If this is an EXTLOAD, the VT's must match.
19856 LLD
->getMemoryVT() != RLD
->getMemoryVT() ||
19857 // If this is an EXTLOAD, the kind of extension must match.
19858 (LLD
->getExtensionType() != RLD
->getExtensionType() &&
19859 // The only exception is if one of the extensions is anyext.
19860 LLD
->getExtensionType() != ISD::EXTLOAD
&&
19861 RLD
->getExtensionType() != ISD::EXTLOAD
) ||
19862 // FIXME: this discards src value information. This is
19863 // over-conservative. It would be beneficial to be able to remember
19864 // both potential memory locations. Since we are discarding
19865 // src value info, don't do the transformation if the memory
19866 // locations are not in the default address space.
19867 LLD
->getPointerInfo().getAddrSpace() != 0 ||
19868 RLD
->getPointerInfo().getAddrSpace() != 0 ||
19869 // We can't produce a CMOV of a TargetFrameIndex since we won't
19870 // generate the address generation required.
19871 LLD
->getBasePtr().getOpcode() == ISD::TargetFrameIndex
||
19872 RLD
->getBasePtr().getOpcode() == ISD::TargetFrameIndex
||
19873 !TLI
.isOperationLegalOrCustom(TheSelect
->getOpcode(),
19874 LLD
->getBasePtr().getValueType()))
19877 // The loads must not depend on one another.
19878 if (LLD
->isPredecessorOf(RLD
) || RLD
->isPredecessorOf(LLD
))
19881 // Check that the select condition doesn't reach either load. If so,
19882 // folding this will induce a cycle into the DAG. If not, this is safe to
19883 // xform, so create a select of the addresses.
19885 SmallPtrSet
<const SDNode
*, 32> Visited
;
19886 SmallVector
<const SDNode
*, 16> Worklist
;
19888 // Always fail if LLD and RLD are not independent. TheSelect is a
19889 // predecessor to all Nodes in question so we need not search past it.
19891 Visited
.insert(TheSelect
);
19892 Worklist
.push_back(LLD
);
19893 Worklist
.push_back(RLD
);
19895 if (SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
) ||
19896 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
))
19900 if (TheSelect
->getOpcode() == ISD::SELECT
) {
19901 // We cannot do this optimization if any pair of {RLD, LLD} is a
19902 // predecessor to {RLD, LLD, CondNode}. As we've already compared the
19903 // Loads, we only need to check if CondNode is a successor to one of the
19904 // loads. We can further avoid this if there's no use of their chain
19906 SDNode
*CondNode
= TheSelect
->getOperand(0).getNode();
19907 Worklist
.push_back(CondNode
);
19909 if ((LLD
->hasAnyUseOfValue(1) &&
19910 SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
)) ||
19911 (RLD
->hasAnyUseOfValue(1) &&
19912 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
)))
19915 Addr
= DAG
.getSelect(SDLoc(TheSelect
),
19916 LLD
->getBasePtr().getValueType(),
19917 TheSelect
->getOperand(0), LLD
->getBasePtr(),
19918 RLD
->getBasePtr());
19919 } else { // Otherwise SELECT_CC
19920 // We cannot do this optimization if any pair of {RLD, LLD} is a
19921 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
19922 // the Loads, we only need to check if CondLHS/CondRHS is a successor to
19923 // one of the loads. We can further avoid this if there's no use of their
19926 SDNode
*CondLHS
= TheSelect
->getOperand(0).getNode();
19927 SDNode
*CondRHS
= TheSelect
->getOperand(1).getNode();
19928 Worklist
.push_back(CondLHS
);
19929 Worklist
.push_back(CondRHS
);
19931 if ((LLD
->hasAnyUseOfValue(1) &&
19932 SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
)) ||
19933 (RLD
->hasAnyUseOfValue(1) &&
19934 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
)))
19937 Addr
= DAG
.getNode(ISD::SELECT_CC
, SDLoc(TheSelect
),
19938 LLD
->getBasePtr().getValueType(),
19939 TheSelect
->getOperand(0),
19940 TheSelect
->getOperand(1),
19941 LLD
->getBasePtr(), RLD
->getBasePtr(),
19942 TheSelect
->getOperand(4));
19946 // It is safe to replace the two loads if they have different alignments,
19947 // but the new load must be the minimum (most restrictive) alignment of the
19949 unsigned Alignment
= std::min(LLD
->getAlignment(), RLD
->getAlignment());
19950 MachineMemOperand::Flags MMOFlags
= LLD
->getMemOperand()->getFlags();
19951 if (!RLD
->isInvariant())
19952 MMOFlags
&= ~MachineMemOperand::MOInvariant
;
19953 if (!RLD
->isDereferenceable())
19954 MMOFlags
&= ~MachineMemOperand::MODereferenceable
;
19955 if (LLD
->getExtensionType() == ISD::NON_EXTLOAD
) {
19956 // FIXME: Discards pointer and AA info.
19957 Load
= DAG
.getLoad(TheSelect
->getValueType(0), SDLoc(TheSelect
),
19958 LLD
->getChain(), Addr
, MachinePointerInfo(), Alignment
,
19961 // FIXME: Discards pointer and AA info.
19962 Load
= DAG
.getExtLoad(
19963 LLD
->getExtensionType() == ISD::EXTLOAD
? RLD
->getExtensionType()
19964 : LLD
->getExtensionType(),
19965 SDLoc(TheSelect
), TheSelect
->getValueType(0), LLD
->getChain(), Addr
,
19966 MachinePointerInfo(), LLD
->getMemoryVT(), Alignment
, MMOFlags
);
19969 // Users of the select now use the result of the load.
19970 CombineTo(TheSelect
, Load
);
19972 // Users of the old loads now use the new load's chain. We know the
19973 // old-load value is dead now.
19974 CombineTo(LHS
.getNode(), Load
.getValue(0), Load
.getValue(1));
19975 CombineTo(RHS
.getNode(), Load
.getValue(0), Load
.getValue(1));
19982 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
19984 SDValue
DAGCombiner::foldSelectCCToShiftAnd(const SDLoc
&DL
, SDValue N0
,
19985 SDValue N1
, SDValue N2
, SDValue N3
,
19986 ISD::CondCode CC
) {
19987 // If this is a select where the false operand is zero and the compare is a
19988 // check of the sign bit, see if we can perform the "gzip trick":
19989 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
19990 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
19991 EVT XType
= N0
.getValueType();
19992 EVT AType
= N2
.getValueType();
19993 if (!isNullConstant(N3
) || !XType
.bitsGE(AType
))
19996 // If the comparison is testing for a positive value, we have to invert
19997 // the sign bit mask, so only do that transform if the target has a bitwise
19998 // 'and not' instruction (the invert is free).
19999 if (CC
== ISD::SETGT
&& TLI
.hasAndNot(N2
)) {
20000 // (X > -1) ? A : 0
20001 // (X > 0) ? X : 0 <-- This is canonical signed max.
20002 if (!(isAllOnesConstant(N1
) || (isNullConstant(N1
) && N0
== N2
)))
20004 } else if (CC
== ISD::SETLT
) {
20006 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
20007 if (!(isNullConstant(N1
) || (isOneConstant(N1
) && N0
== N2
)))
20013 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
20015 EVT ShiftAmtTy
= getShiftAmountTy(N0
.getValueType());
20016 auto *N2C
= dyn_cast
<ConstantSDNode
>(N2
.getNode());
20017 if (N2C
&& ((N2C
->getAPIntValue() & (N2C
->getAPIntValue() - 1)) == 0)) {
20018 unsigned ShCt
= XType
.getSizeInBits() - N2C
->getAPIntValue().logBase2() - 1;
20019 SDValue ShiftAmt
= DAG
.getConstant(ShCt
, DL
, ShiftAmtTy
);
20020 SDValue Shift
= DAG
.getNode(ISD::SRL
, DL
, XType
, N0
, ShiftAmt
);
20021 AddToWorklist(Shift
.getNode());
20023 if (XType
.bitsGT(AType
)) {
20024 Shift
= DAG
.getNode(ISD::TRUNCATE
, DL
, AType
, Shift
);
20025 AddToWorklist(Shift
.getNode());
20028 if (CC
== ISD::SETGT
)
20029 Shift
= DAG
.getNOT(DL
, Shift
, AType
);
20031 return DAG
.getNode(ISD::AND
, DL
, AType
, Shift
, N2
);
20034 SDValue ShiftAmt
= DAG
.getConstant(XType
.getSizeInBits() - 1, DL
, ShiftAmtTy
);
20035 SDValue Shift
= DAG
.getNode(ISD::SRA
, DL
, XType
, N0
, ShiftAmt
);
20036 AddToWorklist(Shift
.getNode());
20038 if (XType
.bitsGT(AType
)) {
20039 Shift
= DAG
.getNode(ISD::TRUNCATE
, DL
, AType
, Shift
);
20040 AddToWorklist(Shift
.getNode());
20043 if (CC
== ISD::SETGT
)
20044 Shift
= DAG
.getNOT(DL
, Shift
, AType
);
20046 return DAG
.getNode(ISD::AND
, DL
, AType
, Shift
, N2
);
20049 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
20050 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
20051 /// in it. This may be a win when the constant is not otherwise available
20052 /// because it replaces two constant pool loads with one.
20053 SDValue
DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
20054 const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
, SDValue N3
,
20055 ISD::CondCode CC
) {
20056 if (!TLI
.reduceSelectOfFPConstantLoads(N0
.getValueType()))
20059 // If we are before legalize types, we want the other legalization to happen
20060 // first (for example, to avoid messing with soft float).
20061 auto *TV
= dyn_cast
<ConstantFPSDNode
>(N2
);
20062 auto *FV
= dyn_cast
<ConstantFPSDNode
>(N3
);
20063 EVT VT
= N2
.getValueType();
20064 if (!TV
|| !FV
|| !TLI
.isTypeLegal(VT
))
20067 // If a constant can be materialized without loads, this does not make sense.
20068 if (TLI
.getOperationAction(ISD::ConstantFP
, VT
) == TargetLowering::Legal
||
20069 TLI
.isFPImmLegal(TV
->getValueAPF(), TV
->getValueType(0), ForCodeSize
) ||
20070 TLI
.isFPImmLegal(FV
->getValueAPF(), FV
->getValueType(0), ForCodeSize
))
20073 // If both constants have multiple uses, then we won't need to do an extra
20074 // load. The values are likely around in registers for other users.
20075 if (!TV
->hasOneUse() && !FV
->hasOneUse())
20078 Constant
*Elts
[] = { const_cast<ConstantFP
*>(FV
->getConstantFPValue()),
20079 const_cast<ConstantFP
*>(TV
->getConstantFPValue()) };
20080 Type
*FPTy
= Elts
[0]->getType();
20081 const DataLayout
&TD
= DAG
.getDataLayout();
20083 // Create a ConstantArray of the two constants.
20084 Constant
*CA
= ConstantArray::get(ArrayType::get(FPTy
, 2), Elts
);
20085 SDValue CPIdx
= DAG
.getConstantPool(CA
, TLI
.getPointerTy(DAG
.getDataLayout()),
20086 TD
.getPrefTypeAlignment(FPTy
));
20087 unsigned Alignment
= cast
<ConstantPoolSDNode
>(CPIdx
)->getAlignment();
20089 // Get offsets to the 0 and 1 elements of the array, so we can select between
20091 SDValue Zero
= DAG
.getIntPtrConstant(0, DL
);
20092 unsigned EltSize
= (unsigned)TD
.getTypeAllocSize(Elts
[0]->getType());
20093 SDValue One
= DAG
.getIntPtrConstant(EltSize
, SDLoc(FV
));
20095 DAG
.getSetCC(DL
, getSetCCResultType(N0
.getValueType()), N0
, N1
, CC
);
20096 AddToWorklist(Cond
.getNode());
20097 SDValue CstOffset
= DAG
.getSelect(DL
, Zero
.getValueType(), Cond
, One
, Zero
);
20098 AddToWorklist(CstOffset
.getNode());
20099 CPIdx
= DAG
.getNode(ISD::ADD
, DL
, CPIdx
.getValueType(), CPIdx
, CstOffset
);
20100 AddToWorklist(CPIdx
.getNode());
20101 return DAG
.getLoad(TV
->getValueType(0), DL
, DAG
.getEntryNode(), CPIdx
,
20102 MachinePointerInfo::getConstantPool(
20103 DAG
.getMachineFunction()), Alignment
);
20106 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
20107 /// where 'cond' is the comparison specified by CC.
20108 SDValue
DAGCombiner::SimplifySelectCC(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
20109 SDValue N2
, SDValue N3
, ISD::CondCode CC
,
20110 bool NotExtCompare
) {
20111 // (x ? y : y) -> y.
20112 if (N2
== N3
) return N2
;
20114 EVT CmpOpVT
= N0
.getValueType();
20115 EVT CmpResVT
= getSetCCResultType(CmpOpVT
);
20116 EVT VT
= N2
.getValueType();
20117 auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode());
20118 auto *N2C
= dyn_cast
<ConstantSDNode
>(N2
.getNode());
20119 auto *N3C
= dyn_cast
<ConstantSDNode
>(N3
.getNode());
20121 // Determine if the condition we're dealing with is constant.
20122 if (SDValue SCC
= DAG
.FoldSetCC(CmpResVT
, N0
, N1
, CC
, DL
)) {
20123 AddToWorklist(SCC
.getNode());
20124 if (auto *SCCC
= dyn_cast
<ConstantSDNode
>(SCC
)) {
20125 // fold select_cc true, x, y -> x
20126 // fold select_cc false, x, y -> y
20127 return !(SCCC
->isNullValue()) ? N2
: N3
;
20132 convertSelectOfFPConstantsToLoadOffset(DL
, N0
, N1
, N2
, N3
, CC
))
20135 if (SDValue V
= foldSelectCCToShiftAnd(DL
, N0
, N1
, N2
, N3
, CC
))
20138 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
20139 // where y is has a single bit set.
20140 // A plaintext description would be, we can turn the SELECT_CC into an AND
20141 // when the condition can be materialized as an all-ones register. Any
20142 // single bit-test can be materialized as an all-ones register with
20143 // shift-left and shift-right-arith.
20144 if (CC
== ISD::SETEQ
&& N0
->getOpcode() == ISD::AND
&&
20145 N0
->getValueType(0) == VT
&& isNullConstant(N1
) && isNullConstant(N2
)) {
20146 SDValue AndLHS
= N0
->getOperand(0);
20147 auto *ConstAndRHS
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1));
20148 if (ConstAndRHS
&& ConstAndRHS
->getAPIntValue().countPopulation() == 1) {
20149 // Shift the tested bit over the sign bit.
20150 const APInt
&AndMask
= ConstAndRHS
->getAPIntValue();
20152 DAG
.getConstant(AndMask
.countLeadingZeros(), SDLoc(AndLHS
),
20153 getShiftAmountTy(AndLHS
.getValueType()));
20154 SDValue Shl
= DAG
.getNode(ISD::SHL
, SDLoc(N0
), VT
, AndLHS
, ShlAmt
);
20156 // Now arithmetic right shift it all the way over, so the result is either
20157 // all-ones, or zero.
20159 DAG
.getConstant(AndMask
.getBitWidth() - 1, SDLoc(Shl
),
20160 getShiftAmountTy(Shl
.getValueType()));
20161 SDValue Shr
= DAG
.getNode(ISD::SRA
, SDLoc(N0
), VT
, Shl
, ShrAmt
);
20163 return DAG
.getNode(ISD::AND
, DL
, VT
, Shr
, N3
);
20167 // fold select C, 16, 0 -> shl C, 4
20168 bool Fold
= N2C
&& isNullConstant(N3
) && N2C
->getAPIntValue().isPowerOf2();
20169 bool Swap
= N3C
&& isNullConstant(N2
) && N3C
->getAPIntValue().isPowerOf2();
20171 if ((Fold
|| Swap
) &&
20172 TLI
.getBooleanContents(CmpOpVT
) ==
20173 TargetLowering::ZeroOrOneBooleanContent
&&
20174 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SETCC
, CmpOpVT
))) {
20177 CC
= ISD::getSetCCInverse(CC
, CmpOpVT
.isInteger());
20178 std::swap(N2C
, N3C
);
20181 // If the caller doesn't want us to simplify this into a zext of a compare,
20183 if (NotExtCompare
&& N2C
->isOne())
20187 // zext (setcc n0, n1)
20189 SCC
= DAG
.getSetCC(DL
, CmpResVT
, N0
, N1
, CC
);
20190 if (VT
.bitsLT(SCC
.getValueType()))
20191 Temp
= DAG
.getZeroExtendInReg(SCC
, SDLoc(N2
), VT
);
20193 Temp
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N2
), VT
, SCC
);
20195 SCC
= DAG
.getSetCC(SDLoc(N0
), MVT::i1
, N0
, N1
, CC
);
20196 Temp
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N2
), VT
, SCC
);
20199 AddToWorklist(SCC
.getNode());
20200 AddToWorklist(Temp
.getNode());
20205 // shl setcc result by log2 n2c
20206 return DAG
.getNode(ISD::SHL
, DL
, N2
.getValueType(), Temp
,
20207 DAG
.getConstant(N2C
->getAPIntValue().logBase2(),
20209 getShiftAmountTy(Temp
.getValueType())));
20212 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
20213 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
20214 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
20215 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
20216 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
20217 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
20218 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
20219 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
20220 if (N1C
&& N1C
->isNullValue() && (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
20221 SDValue ValueOnZero
= N2
;
20222 SDValue Count
= N3
;
20223 // If the condition is NE instead of E, swap the operands.
20224 if (CC
== ISD::SETNE
)
20225 std::swap(ValueOnZero
, Count
);
20226 // Check if the value on zero is a constant equal to the bits in the type.
20227 if (auto *ValueOnZeroC
= dyn_cast
<ConstantSDNode
>(ValueOnZero
)) {
20228 if (ValueOnZeroC
->getAPIntValue() == VT
.getSizeInBits()) {
20229 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
20230 // legal, combine to just cttz.
20231 if ((Count
.getOpcode() == ISD::CTTZ
||
20232 Count
.getOpcode() == ISD::CTTZ_ZERO_UNDEF
) &&
20233 N0
== Count
.getOperand(0) &&
20234 (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTTZ
, VT
)))
20235 return DAG
.getNode(ISD::CTTZ
, DL
, VT
, N0
);
20236 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
20237 // legal, combine to just ctlz.
20238 if ((Count
.getOpcode() == ISD::CTLZ
||
20239 Count
.getOpcode() == ISD::CTLZ_ZERO_UNDEF
) &&
20240 N0
== Count
.getOperand(0) &&
20241 (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTLZ
, VT
)))
20242 return DAG
.getNode(ISD::CTLZ
, DL
, VT
, N0
);
20250 /// This is a stub for TargetLowering::SimplifySetCC.
20251 SDValue
DAGCombiner::SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
,
20252 ISD::CondCode Cond
, const SDLoc
&DL
,
20253 bool foldBooleans
) {
20254 TargetLowering::DAGCombinerInfo
20255 DagCombineInfo(DAG
, Level
, false, this);
20256 return TLI
.SimplifySetCC(VT
, N0
, N1
, Cond
, foldBooleans
, DagCombineInfo
, DL
);
20259 /// Given an ISD::SDIV node expressing a divide by constant, return
20260 /// a DAG expression to select that will generate the same value by multiplying
20261 /// by a magic number.
20262 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
20263 SDValue
DAGCombiner::BuildSDIV(SDNode
*N
) {
20264 // when optimising for minimum size, we don't want to expand a div to a mul
20266 if (DAG
.getMachineFunction().getFunction().hasMinSize())
20269 SmallVector
<SDNode
*, 8> Built
;
20270 if (SDValue S
= TLI
.BuildSDIV(N
, DAG
, LegalOperations
, Built
)) {
20271 for (SDNode
*N
: Built
)
20279 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
20280 /// DAG expression that will generate the same value by right shifting.
20281 SDValue
DAGCombiner::BuildSDIVPow2(SDNode
*N
) {
20282 ConstantSDNode
*C
= isConstOrConstSplat(N
->getOperand(1));
20286 // Avoid division by zero.
20287 if (C
->isNullValue())
20290 SmallVector
<SDNode
*, 8> Built
;
20291 if (SDValue S
= TLI
.BuildSDIVPow2(N
, C
->getAPIntValue(), DAG
, Built
)) {
20292 for (SDNode
*N
: Built
)
20300 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
20301 /// expression that will generate the same value by multiplying by a magic
20303 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
20304 SDValue
DAGCombiner::BuildUDIV(SDNode
*N
) {
20305 // when optimising for minimum size, we don't want to expand a div to a mul
20307 if (DAG
.getMachineFunction().getFunction().hasMinSize())
20310 SmallVector
<SDNode
*, 8> Built
;
20311 if (SDValue S
= TLI
.BuildUDIV(N
, DAG
, LegalOperations
, Built
)) {
20312 for (SDNode
*N
: Built
)
20320 /// Determines the LogBase2 value for a non-null input value using the
20321 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
20322 SDValue
DAGCombiner::BuildLogBase2(SDValue V
, const SDLoc
&DL
) {
20323 EVT VT
= V
.getValueType();
20324 unsigned EltBits
= VT
.getScalarSizeInBits();
20325 SDValue Ctlz
= DAG
.getNode(ISD::CTLZ
, DL
, VT
, V
);
20326 SDValue Base
= DAG
.getConstant(EltBits
- 1, DL
, VT
);
20327 SDValue LogBase2
= DAG
.getNode(ISD::SUB
, DL
, VT
, Base
, Ctlz
);
20331 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20332 /// For the reciprocal, we need to find the zero of the function:
20333 /// F(X) = A X - 1 [which has a zero at X = 1/A]
20335 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
20336 /// does not require additional intermediate precision]
20337 /// For the last iteration, put numerator N into it to gain more precision:
20338 /// Result = N X_i + X_i (N - N A X_i)
20339 SDValue
DAGCombiner::BuildDivEstimate(SDValue N
, SDValue Op
,
20340 SDNodeFlags Flags
) {
20341 if (Level
>= AfterLegalizeDAG
)
20344 // TODO: Handle half and/or extended types?
20345 EVT VT
= Op
.getValueType();
20346 if (VT
.getScalarType() != MVT::f32
&& VT
.getScalarType() != MVT::f64
)
20349 // If estimates are explicitly disabled for this function, we're done.
20350 MachineFunction
&MF
= DAG
.getMachineFunction();
20351 int Enabled
= TLI
.getRecipEstimateDivEnabled(VT
, MF
);
20352 if (Enabled
== TLI
.ReciprocalEstimate::Disabled
)
20355 // Estimates may be explicitly enabled for this type with a custom number of
20356 // refinement steps.
20357 int Iterations
= TLI
.getDivRefinementSteps(VT
, MF
);
20358 if (SDValue Est
= TLI
.getRecipEstimate(Op
, DAG
, Enabled
, Iterations
)) {
20359 AddToWorklist(Est
.getNode());
20363 SDValue FPOne
= DAG
.getConstantFP(1.0, DL
, VT
);
20365 // Newton iterations: Est = Est + Est (N - Arg * Est)
20366 // If this is the last iteration, also multiply by the numerator.
20367 for (int i
= 0; i
< Iterations
; ++i
) {
20368 SDValue MulEst
= Est
;
20370 if (i
== Iterations
- 1) {
20371 MulEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, N
, Est
, Flags
);
20372 AddToWorklist(MulEst
.getNode());
20375 SDValue NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Op
, MulEst
, Flags
);
20376 AddToWorklist(NewEst
.getNode());
20378 NewEst
= DAG
.getNode(ISD::FSUB
, DL
, VT
,
20379 (i
== Iterations
- 1 ? N
: FPOne
), NewEst
, Flags
);
20380 AddToWorklist(NewEst
.getNode());
20382 NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, NewEst
, Flags
);
20383 AddToWorklist(NewEst
.getNode());
20385 Est
= DAG
.getNode(ISD::FADD
, DL
, VT
, MulEst
, NewEst
, Flags
);
20386 AddToWorklist(Est
.getNode());
20389 // If no iterations are available, multiply with N.
20390 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, N
, Flags
);
20391 AddToWorklist(Est
.getNode());
20400 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20401 /// For the reciprocal sqrt, we need to find the zero of the function:
20402 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20404 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
20405 /// As a result, we precompute A/2 prior to the iteration loop.
20406 SDValue
DAGCombiner::buildSqrtNROneConst(SDValue Arg
, SDValue Est
,
20407 unsigned Iterations
,
20408 SDNodeFlags Flags
, bool Reciprocal
) {
20409 EVT VT
= Arg
.getValueType();
20411 SDValue ThreeHalves
= DAG
.getConstantFP(1.5, DL
, VT
);
20413 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
20414 // this entire sequence requires only one FP constant.
20415 SDValue HalfArg
= DAG
.getNode(ISD::FMUL
, DL
, VT
, ThreeHalves
, Arg
, Flags
);
20416 HalfArg
= DAG
.getNode(ISD::FSUB
, DL
, VT
, HalfArg
, Arg
, Flags
);
20418 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
20419 for (unsigned i
= 0; i
< Iterations
; ++i
) {
20420 SDValue NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, Est
, Flags
);
20421 NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, HalfArg
, NewEst
, Flags
);
20422 NewEst
= DAG
.getNode(ISD::FSUB
, DL
, VT
, ThreeHalves
, NewEst
, Flags
);
20423 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, NewEst
, Flags
);
20426 // If non-reciprocal square root is requested, multiply the result by Arg.
20428 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, Arg
, Flags
);
20433 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20434 /// For the reciprocal sqrt, we need to find the zero of the function:
20435 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20437 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
20438 SDValue
DAGCombiner::buildSqrtNRTwoConst(SDValue Arg
, SDValue Est
,
20439 unsigned Iterations
,
20440 SDNodeFlags Flags
, bool Reciprocal
) {
20441 EVT VT
= Arg
.getValueType();
20443 SDValue MinusThree
= DAG
.getConstantFP(-3.0, DL
, VT
);
20444 SDValue MinusHalf
= DAG
.getConstantFP(-0.5, DL
, VT
);
20446 // This routine must enter the loop below to work correctly
20447 // when (Reciprocal == false).
20448 assert(Iterations
> 0);
20450 // Newton iterations for reciprocal square root:
20451 // E = (E * -0.5) * ((A * E) * E + -3.0)
20452 for (unsigned i
= 0; i
< Iterations
; ++i
) {
20453 SDValue AE
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Arg
, Est
, Flags
);
20454 SDValue AEE
= DAG
.getNode(ISD::FMUL
, DL
, VT
, AE
, Est
, Flags
);
20455 SDValue RHS
= DAG
.getNode(ISD::FADD
, DL
, VT
, AEE
, MinusThree
, Flags
);
20457 // When calculating a square root at the last iteration build:
20458 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
20459 // (notice a common subexpression)
20461 if (Reciprocal
|| (i
+ 1) < Iterations
) {
20462 // RSQRT: LHS = (E * -0.5)
20463 LHS
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, MinusHalf
, Flags
);
20465 // SQRT: LHS = (A * E) * -0.5
20466 LHS
= DAG
.getNode(ISD::FMUL
, DL
, VT
, AE
, MinusHalf
, Flags
);
20469 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, LHS
, RHS
, Flags
);
20475 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
20476 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
20477 /// Op can be zero.
20478 SDValue
DAGCombiner::buildSqrtEstimateImpl(SDValue Op
, SDNodeFlags Flags
,
20480 if (Level
>= AfterLegalizeDAG
)
20483 // TODO: Handle half and/or extended types?
20484 EVT VT
= Op
.getValueType();
20485 if (VT
.getScalarType() != MVT::f32
&& VT
.getScalarType() != MVT::f64
)
20488 // If estimates are explicitly disabled for this function, we're done.
20489 MachineFunction
&MF
= DAG
.getMachineFunction();
20490 int Enabled
= TLI
.getRecipEstimateSqrtEnabled(VT
, MF
);
20491 if (Enabled
== TLI
.ReciprocalEstimate::Disabled
)
20494 // Estimates may be explicitly enabled for this type with a custom number of
20495 // refinement steps.
20496 int Iterations
= TLI
.getSqrtRefinementSteps(VT
, MF
);
20498 bool UseOneConstNR
= false;
20500 TLI
.getSqrtEstimate(Op
, DAG
, Enabled
, Iterations
, UseOneConstNR
,
20502 AddToWorklist(Est
.getNode());
20505 Est
= UseOneConstNR
20506 ? buildSqrtNROneConst(Op
, Est
, Iterations
, Flags
, Reciprocal
)
20507 : buildSqrtNRTwoConst(Op
, Est
, Iterations
, Flags
, Reciprocal
);
20510 // The estimate is now completely wrong if the input was exactly 0.0 or
20511 // possibly a denormal. Force the answer to 0.0 for those cases.
20513 EVT CCVT
= getSetCCResultType(VT
);
20514 ISD::NodeType SelOpcode
= VT
.isVector() ? ISD::VSELECT
: ISD::SELECT
;
20515 const Function
&F
= DAG
.getMachineFunction().getFunction();
20516 Attribute Denorms
= F
.getFnAttribute("denormal-fp-math");
20517 if (Denorms
.getValueAsString().equals("ieee")) {
20518 // fabs(X) < SmallestNormal ? 0.0 : Est
20519 const fltSemantics
&FltSem
= DAG
.EVTToAPFloatSemantics(VT
);
20520 APFloat SmallestNorm
= APFloat::getSmallestNormalized(FltSem
);
20521 SDValue NormC
= DAG
.getConstantFP(SmallestNorm
, DL
, VT
);
20522 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
20523 SDValue Fabs
= DAG
.getNode(ISD::FABS
, DL
, VT
, Op
);
20524 SDValue IsDenorm
= DAG
.getSetCC(DL
, CCVT
, Fabs
, NormC
, ISD::SETLT
);
20525 Est
= DAG
.getNode(SelOpcode
, DL
, VT
, IsDenorm
, FPZero
, Est
);
20527 // X == 0.0 ? 0.0 : Est
20528 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
20529 SDValue IsZero
= DAG
.getSetCC(DL
, CCVT
, Op
, FPZero
, ISD::SETEQ
);
20530 Est
= DAG
.getNode(SelOpcode
, DL
, VT
, IsZero
, FPZero
, Est
);
20540 SDValue
DAGCombiner::buildRsqrtEstimate(SDValue Op
, SDNodeFlags Flags
) {
20541 return buildSqrtEstimateImpl(Op
, Flags
, true);
20544 SDValue
DAGCombiner::buildSqrtEstimate(SDValue Op
, SDNodeFlags Flags
) {
20545 return buildSqrtEstimateImpl(Op
, Flags
, false);
20548 /// Return true if there is any possibility that the two addresses overlap.
20549 bool DAGCombiner::isAlias(SDNode
*Op0
, SDNode
*Op1
) const {
20551 struct MemUseCharacteristics
{
20556 Optional
<int64_t> NumBytes
;
20557 MachineMemOperand
*MMO
;
20560 auto getCharacteristics
= [](SDNode
*N
) -> MemUseCharacteristics
{
20561 if (const auto *LSN
= dyn_cast
<LSBaseSDNode
>(N
)) {
20562 int64_t Offset
= 0;
20563 if (auto *C
= dyn_cast
<ConstantSDNode
>(LSN
->getOffset()))
20564 Offset
= (LSN
->getAddressingMode() == ISD::PRE_INC
)
20565 ? C
->getSExtValue()
20566 : (LSN
->getAddressingMode() == ISD::PRE_DEC
)
20567 ? -1 * C
->getSExtValue()
20569 return {LSN
->isVolatile(), LSN
->isAtomic(), LSN
->getBasePtr(),
20570 Offset
/*base offset*/,
20571 Optional
<int64_t>(LSN
->getMemoryVT().getStoreSize()),
20572 LSN
->getMemOperand()};
20574 if (const auto *LN
= cast
<LifetimeSDNode
>(N
))
20575 return {false /*isVolatile*/, /*isAtomic*/ false, LN
->getOperand(1),
20576 (LN
->hasOffset()) ? LN
->getOffset() : 0,
20577 (LN
->hasOffset()) ? Optional
<int64_t>(LN
->getSize())
20578 : Optional
<int64_t>(),
20579 (MachineMemOperand
*)nullptr};
20581 return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(),
20582 (int64_t)0 /*offset*/,
20583 Optional
<int64_t>() /*size*/, (MachineMemOperand
*)nullptr};
20586 MemUseCharacteristics MUC0
= getCharacteristics(Op0
),
20587 MUC1
= getCharacteristics(Op1
);
20589 // If they are to the same address, then they must be aliases.
20590 if (MUC0
.BasePtr
.getNode() && MUC0
.BasePtr
== MUC1
.BasePtr
&&
20591 MUC0
.Offset
== MUC1
.Offset
)
20594 // If they are both volatile then they cannot be reordered.
20595 if (MUC0
.IsVolatile
&& MUC1
.IsVolatile
)
20598 // Be conservative about atomics for the moment
20599 // TODO: This is way overconservative for unordered atomics (see D66309)
20600 if (MUC0
.IsAtomic
&& MUC1
.IsAtomic
)
20603 if (MUC0
.MMO
&& MUC1
.MMO
) {
20604 if ((MUC0
.MMO
->isInvariant() && MUC1
.MMO
->isStore()) ||
20605 (MUC1
.MMO
->isInvariant() && MUC0
.MMO
->isStore()))
20609 // Try to prove that there is aliasing, or that there is no aliasing. Either
20610 // way, we can return now. If nothing can be proved, proceed with more tests.
20612 if (BaseIndexOffset::computeAliasing(Op0
, MUC0
.NumBytes
, Op1
, MUC1
.NumBytes
,
20616 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
20617 // either are not known.
20618 if (!MUC0
.MMO
|| !MUC1
.MMO
)
20621 // If one operation reads from invariant memory, and the other may store, they
20622 // cannot alias. These should really be checking the equivalent of mayWrite,
20623 // but it only matters for memory nodes other than load /store.
20624 if ((MUC0
.MMO
->isInvariant() && MUC1
.MMO
->isStore()) ||
20625 (MUC1
.MMO
->isInvariant() && MUC0
.MMO
->isStore()))
20628 // If we know required SrcValue1 and SrcValue2 have relatively large
20629 // alignment compared to the size and offset of the access, we may be able
20630 // to prove they do not alias. This check is conservative for now to catch
20631 // cases created by splitting vector types.
20632 int64_t SrcValOffset0
= MUC0
.MMO
->getOffset();
20633 int64_t SrcValOffset1
= MUC1
.MMO
->getOffset();
20634 unsigned OrigAlignment0
= MUC0
.MMO
->getBaseAlignment();
20635 unsigned OrigAlignment1
= MUC1
.MMO
->getBaseAlignment();
20636 if (OrigAlignment0
== OrigAlignment1
&& SrcValOffset0
!= SrcValOffset1
&&
20637 MUC0
.NumBytes
.hasValue() && MUC1
.NumBytes
.hasValue() &&
20638 *MUC0
.NumBytes
== *MUC1
.NumBytes
&& OrigAlignment0
> *MUC0
.NumBytes
) {
20639 int64_t OffAlign0
= SrcValOffset0
% OrigAlignment0
;
20640 int64_t OffAlign1
= SrcValOffset1
% OrigAlignment1
;
20642 // There is no overlap between these relatively aligned accesses of
20643 // similar size. Return no alias.
20644 if ((OffAlign0
+ *MUC0
.NumBytes
) <= OffAlign1
||
20645 (OffAlign1
+ *MUC1
.NumBytes
) <= OffAlign0
)
20649 bool UseAA
= CombinerGlobalAA
.getNumOccurrences() > 0
20651 : DAG
.getSubtarget().useAA();
20653 if (CombinerAAOnlyFunc
.getNumOccurrences() &&
20654 CombinerAAOnlyFunc
!= DAG
.getMachineFunction().getName())
20658 if (UseAA
&& AA
&& MUC0
.MMO
->getValue() && MUC1
.MMO
->getValue()) {
20659 // Use alias analysis information.
20660 int64_t MinOffset
= std::min(SrcValOffset0
, SrcValOffset1
);
20661 int64_t Overlap0
= *MUC0
.NumBytes
+ SrcValOffset0
- MinOffset
;
20662 int64_t Overlap1
= *MUC1
.NumBytes
+ SrcValOffset1
- MinOffset
;
20663 AliasResult AAResult
= AA
->alias(
20664 MemoryLocation(MUC0
.MMO
->getValue(), Overlap0
,
20665 UseTBAA
? MUC0
.MMO
->getAAInfo() : AAMDNodes()),
20666 MemoryLocation(MUC1
.MMO
->getValue(), Overlap1
,
20667 UseTBAA
? MUC1
.MMO
->getAAInfo() : AAMDNodes()));
20668 if (AAResult
== NoAlias
)
20672 // Otherwise we have to assume they alias.
20676 /// Walk up chain skipping non-aliasing memory nodes,
20677 /// looking for aliasing nodes and adding them to the Aliases vector.
20678 void DAGCombiner::GatherAllAliases(SDNode
*N
, SDValue OriginalChain
,
20679 SmallVectorImpl
<SDValue
> &Aliases
) {
20680 SmallVector
<SDValue
, 8> Chains
; // List of chains to visit.
20681 SmallPtrSet
<SDNode
*, 16> Visited
; // Visited node set.
20683 // Get alias information for node.
20684 // TODO: relax aliasing for unordered atomics (see D66309)
20685 const bool IsLoad
= isa
<LoadSDNode
>(N
) && cast
<LoadSDNode
>(N
)->isSimple();
20688 Chains
.push_back(OriginalChain
);
20689 unsigned Depth
= 0;
20691 // Attempt to improve chain by a single step
20692 std::function
<bool(SDValue
&)> ImproveChain
= [&](SDValue
&C
) -> bool {
20693 switch (C
.getOpcode()) {
20694 case ISD::EntryToken
:
20695 // No need to mark EntryToken.
20700 // Get alias information for C.
20701 // TODO: Relax aliasing for unordered atomics (see D66309)
20702 bool IsOpLoad
= isa
<LoadSDNode
>(C
.getNode()) &&
20703 cast
<LSBaseSDNode
>(C
.getNode())->isSimple();
20704 if ((IsLoad
&& IsOpLoad
) || !isAlias(N
, C
.getNode())) {
20705 // Look further up the chain.
20706 C
= C
.getOperand(0);
20709 // Alias, so stop here.
20713 case ISD::CopyFromReg
:
20714 // Always forward past past CopyFromReg.
20715 C
= C
.getOperand(0);
20718 case ISD::LIFETIME_START
:
20719 case ISD::LIFETIME_END
: {
20720 // We can forward past any lifetime start/end that can be proven not to
20721 // alias the memory access.
20722 if (!isAlias(N
, C
.getNode())) {
20723 // Look further up the chain.
20724 C
= C
.getOperand(0);
20734 // Look at each chain and determine if it is an alias. If so, add it to the
20735 // aliases list. If not, then continue up the chain looking for the next
20737 while (!Chains
.empty()) {
20738 SDValue Chain
= Chains
.pop_back_val();
20740 // Don't bother if we've seen Chain before.
20741 if (!Visited
.insert(Chain
.getNode()).second
)
20744 // For TokenFactor nodes, look at each operand and only continue up the
20745 // chain until we reach the depth limit.
20747 // FIXME: The depth check could be made to return the last non-aliasing
20748 // chain we found before we hit a tokenfactor rather than the original
20750 if (Depth
> TLI
.getGatherAllAliasesMaxDepth()) {
20752 Aliases
.push_back(OriginalChain
);
20756 if (Chain
.getOpcode() == ISD::TokenFactor
) {
20757 // We have to check each of the operands of the token factor for "small"
20758 // token factors, so we queue them up. Adding the operands to the queue
20759 // (stack) in reverse order maintains the original order and increases the
20760 // likelihood that getNode will find a matching token factor (CSE.)
20761 if (Chain
.getNumOperands() > 16) {
20762 Aliases
.push_back(Chain
);
20765 for (unsigned n
= Chain
.getNumOperands(); n
;)
20766 Chains
.push_back(Chain
.getOperand(--n
));
20771 if (ImproveChain(Chain
)) {
20772 // Updated Chain Found, Consider new chain if one exists.
20773 if (Chain
.getNode())
20774 Chains
.push_back(Chain
);
20778 // No Improved Chain Possible, treat as Alias.
20779 Aliases
.push_back(Chain
);
20783 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
20784 /// (aliasing node.)
20785 SDValue
DAGCombiner::FindBetterChain(SDNode
*N
, SDValue OldChain
) {
20786 if (OptLevel
== CodeGenOpt::None
)
20789 // Ops for replacing token factor.
20790 SmallVector
<SDValue
, 8> Aliases
;
20792 // Accumulate all the aliases to this node.
20793 GatherAllAliases(N
, OldChain
, Aliases
);
20795 // If no operands then chain to entry token.
20796 if (Aliases
.size() == 0)
20797 return DAG
.getEntryNode();
20799 // If a single operand then chain to it. We don't need to revisit it.
20800 if (Aliases
.size() == 1)
20803 // Construct a custom tailored token factor.
20804 return DAG
.getTokenFactor(SDLoc(N
), Aliases
);
20808 // TODO: Replace with with std::monostate when we move to C++17.
20809 struct UnitT
{ } Unit
;
20810 bool operator==(const UnitT
&, const UnitT
&) { return true; }
20811 bool operator!=(const UnitT
&, const UnitT
&) { return false; }
20814 // This function tries to collect a bunch of potentially interesting
20815 // nodes to improve the chains of, all at once. This might seem
20816 // redundant, as this function gets called when visiting every store
20817 // node, so why not let the work be done on each store as it's visited?
20819 // I believe this is mainly important because MergeConsecutiveStores
20820 // is unable to deal with merging stores of different sizes, so unless
20821 // we improve the chains of all the potential candidates up-front
20822 // before running MergeConsecutiveStores, it might only see some of
20823 // the nodes that will eventually be candidates, and then not be able
20824 // to go from a partially-merged state to the desired final
20825 // fully-merged state.
20827 bool DAGCombiner::parallelizeChainedStores(StoreSDNode
*St
) {
20828 SmallVector
<StoreSDNode
*, 8> ChainedStores
;
20829 StoreSDNode
*STChain
= St
;
20830 // Intervals records which offsets from BaseIndex have been covered. In
20831 // the common case, every store writes to the immediately previous address
20832 // space and thus merged with the previous interval at insertion time.
20835 llvm::IntervalMap
<int64_t, UnitT
, 8, IntervalMapHalfOpenInfo
<int64_t>>;
20839 // This holds the base pointer, index, and the offset in bytes from the base
20841 const BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
20843 // We must have a base and an offset.
20844 if (!BasePtr
.getBase().getNode())
20847 // Do not handle stores to undef base pointers.
20848 if (BasePtr
.getBase().isUndef())
20851 // Add ST's interval.
20852 Intervals
.insert(0, (St
->getMemoryVT().getSizeInBits() + 7) / 8, Unit
);
20854 while (StoreSDNode
*Chain
= dyn_cast
<StoreSDNode
>(STChain
->getChain())) {
20855 // If the chain has more than one use, then we can't reorder the mem ops.
20856 if (!SDValue(Chain
, 0)->hasOneUse())
20858 // TODO: Relax for unordered atomics (see D66309)
20859 if (!Chain
->isSimple() || Chain
->isIndexed())
20862 // Find the base pointer and offset for this memory node.
20863 const BaseIndexOffset Ptr
= BaseIndexOffset::match(Chain
, DAG
);
20864 // Check that the base pointer is the same as the original one.
20866 if (!BasePtr
.equalBaseIndex(Ptr
, DAG
, Offset
))
20868 int64_t Length
= (Chain
->getMemoryVT().getSizeInBits() + 7) / 8;
20869 // Make sure we don't overlap with other intervals by checking the ones to
20870 // the left or right before inserting.
20871 auto I
= Intervals
.find(Offset
);
20872 // If there's a next interval, we should end before it.
20873 if (I
!= Intervals
.end() && I
.start() < (Offset
+ Length
))
20875 // If there's a previous interval, we should start after it.
20876 if (I
!= Intervals
.begin() && (--I
).stop() <= Offset
)
20878 Intervals
.insert(Offset
, Offset
+ Length
, Unit
);
20880 ChainedStores
.push_back(Chain
);
20884 // If we didn't find a chained store, exit.
20885 if (ChainedStores
.size() == 0)
20888 // Improve all chained stores (St and ChainedStores members) starting from
20889 // where the store chain ended and return single TokenFactor.
20890 SDValue NewChain
= STChain
->getChain();
20891 SmallVector
<SDValue
, 8> TFOps
;
20892 for (unsigned I
= ChainedStores
.size(); I
;) {
20893 StoreSDNode
*S
= ChainedStores
[--I
];
20894 SDValue BetterChain
= FindBetterChain(S
, NewChain
);
20895 S
= cast
<StoreSDNode
>(DAG
.UpdateNodeOperands(
20896 S
, BetterChain
, S
->getOperand(1), S
->getOperand(2), S
->getOperand(3)));
20897 TFOps
.push_back(SDValue(S
, 0));
20898 ChainedStores
[I
] = S
;
20901 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
20902 SDValue BetterChain
= FindBetterChain(St
, NewChain
);
20904 if (St
->isTruncatingStore())
20905 NewST
= DAG
.getTruncStore(BetterChain
, SDLoc(St
), St
->getValue(),
20906 St
->getBasePtr(), St
->getMemoryVT(),
20907 St
->getMemOperand());
20909 NewST
= DAG
.getStore(BetterChain
, SDLoc(St
), St
->getValue(),
20910 St
->getBasePtr(), St
->getMemOperand());
20912 TFOps
.push_back(NewST
);
20914 // If we improved every element of TFOps, then we've lost the dependence on
20915 // NewChain to successors of St and we need to add it back to TFOps. Do so at
20916 // the beginning to keep relative order consistent with FindBetterChains.
20917 auto hasImprovedChain
= [&](SDValue ST
) -> bool {
20918 return ST
->getOperand(0) != NewChain
;
20920 bool AddNewChain
= llvm::all_of(TFOps
, hasImprovedChain
);
20922 TFOps
.insert(TFOps
.begin(), NewChain
);
20924 SDValue TF
= DAG
.getTokenFactor(SDLoc(STChain
), TFOps
);
20927 // Add TF and its operands to the worklist.
20928 AddToWorklist(TF
.getNode());
20929 for (const SDValue
&Op
: TF
->ops())
20930 AddToWorklist(Op
.getNode());
20931 AddToWorklist(STChain
);
20935 bool DAGCombiner::findBetterNeighborChains(StoreSDNode
*St
) {
20936 if (OptLevel
== CodeGenOpt::None
)
20939 const BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
20941 // We must have a base and an offset.
20942 if (!BasePtr
.getBase().getNode())
20945 // Do not handle stores to undef base pointers.
20946 if (BasePtr
.getBase().isUndef())
20949 // Directly improve a chain of disjoint stores starting at St.
20950 if (parallelizeChainedStores(St
))
20953 // Improve St's Chain..
20954 SDValue BetterChain
= FindBetterChain(St
, St
->getChain());
20955 if (St
->getChain() != BetterChain
) {
20956 replaceStoreChain(St
, BetterChain
);
20962 /// This is the entry point for the file.
20963 void SelectionDAG::Combine(CombineLevel Level
, AliasAnalysis
*AA
,
20964 CodeGenOpt::Level OptLevel
) {
20965 /// This is the main entry point to this class.
20966 DAGCombiner(*this, AA
, OptLevel
).Run(Level
);