1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryLocation.h"
34 #include "llvm/CodeGen/DAGCombine.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineValueType.h"
40 #include "llvm/CodeGen/RuntimeLibcalls.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
45 #include "llvm/CodeGen/TargetLowering.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/Constant.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.h"
79 #define DEBUG_TYPE "dagcombine"
81 STATISTIC(NodesCombined , "Number of dag nodes combined");
82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
84 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
85 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
86 STATISTIC(SlicedLoads, "Number of load sliced");
89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
90 cl::desc("Enable DAG combiner's use of IR alias analysis"));
93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
94 cl::desc("Enable DAG combiner's use of TBAA"));
97 static cl::opt<std::string>
98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
99 cl::desc("Only use DAG-combiner alias analysis in this"
103 /// Hidden option to stress test load slicing, i.e., when this option
104 /// is enabled, load slicing bypasses most of its profitability guards.
106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
107 cl::desc("Bypass the profitability model of load slicing"),
111 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
112 cl::desc("DAG combiner may split indexing from loads"));
118 const TargetLowering &TLI;
120 CodeGenOpt::Level OptLevel;
121 bool LegalOperations = false;
122 bool LegalTypes = false;
125 /// \brief Worklist of all of the nodes that need to be simplified.
127 /// This must behave as a stack -- new nodes to process are pushed onto the
128 /// back and when processing we pop off of the back.
130 /// The worklist will not contain duplicates but may contain null entries
131 /// due to nodes being deleted from the underlying DAG.
132 SmallVector<SDNode *, 64> Worklist;
134 /// \brief Mapping from an SDNode to its position on the worklist.
136 /// This is used to find and remove nodes from the worklist (by nulling
137 /// them) when they are deleted from the underlying DAG. It relies on
138 /// stable indices of nodes within the worklist.
139 DenseMap<SDNode *, unsigned> WorklistMap;
141 /// \brief Set of nodes which have been combined (at least once).
143 /// This is used to allow us to reliably add any operands of a DAG node
144 /// which have not yet been combined to the worklist.
145 SmallPtrSet<SDNode *, 32> CombinedNodes;
147 // AA - Used for DAG load/store alias analysis.
150 /// When an instruction is simplified, add all users of the instruction to
151 /// the work lists because they might get more simplified now.
152 void AddUsersToWorklist(SDNode *N) {
153 for (SDNode *Node : N->uses())
157 /// Call the node-specific routine that folds each particular type of node.
158 SDValue visit(SDNode *N);
161 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
162 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
163 OptLevel(OL), AA(AA) {
164 ForCodeSize = DAG.getMachineFunction().getFunction().optForSize();
166 MaximumLegalStoreInBits = 0;
167 for (MVT VT : MVT::all_valuetypes())
168 if (EVT(VT).isSimple() && VT != MVT::Other &&
169 TLI.isTypeLegal(EVT(VT)) &&
170 VT.getSizeInBits() >= MaximumLegalStoreInBits)
171 MaximumLegalStoreInBits = VT.getSizeInBits();
174 /// Add to the worklist making sure its instance is at the back (next to be
176 void AddToWorklist(SDNode *N) {
177 assert(N->getOpcode() != ISD::DELETED_NODE &&
178 "Deleted Node added to Worklist");
180 // Skip handle nodes as they can't usefully be combined and confuse the
181 // zero-use deletion strategy.
182 if (N->getOpcode() == ISD::HANDLENODE)
185 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
186 Worklist.push_back(N);
189 /// Remove all instances of N from the worklist.
190 void removeFromWorklist(SDNode *N) {
191 CombinedNodes.erase(N);
193 auto It = WorklistMap.find(N);
194 if (It == WorklistMap.end())
195 return; // Not in the worklist.
197 // Null out the entry rather than erasing it to avoid a linear operation.
198 Worklist[It->second] = nullptr;
199 WorklistMap.erase(It);
202 void deleteAndRecombine(SDNode *N);
203 bool recursivelyDeleteUnusedNodes(SDNode *N);
205 /// Replaces all uses of the results of one DAG node with new values.
206 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
209 /// Replaces all uses of the results of one DAG node with new values.
210 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
211 return CombineTo(N, &Res, 1, AddTo);
214 /// Replaces all uses of the results of one DAG node with new values.
215 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
217 SDValue To[] = { Res0, Res1 };
218 return CombineTo(N, To, 2, AddTo);
221 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
224 unsigned MaximumLegalStoreInBits;
226 /// Check the specified integer node value to see if it can be simplified or
227 /// if things it uses can be simplified by bit propagation.
228 /// If so, return true.
229 bool SimplifyDemandedBits(SDValue Op) {
230 unsigned BitWidth = Op.getScalarValueSizeInBits();
231 APInt Demanded = APInt::getAllOnesValue(BitWidth);
232 return SimplifyDemandedBits(Op, Demanded);
235 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
237 bool CombineToPreIndexedLoadStore(SDNode *N);
238 bool CombineToPostIndexedLoadStore(SDNode *N);
239 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
240 bool SliceUpLoad(SDNode *N);
242 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
245 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
246 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
247 /// \param EltNo index of the vector element to load.
248 /// \param OriginalLoad load that EVE came from to be replaced.
249 /// \returns EVE on success SDValue() on failure.
250 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
251 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
252 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
253 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
254 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
255 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
256 SDValue PromoteIntBinOp(SDValue Op);
257 SDValue PromoteIntShiftOp(SDValue Op);
258 SDValue PromoteExtend(SDValue Op);
259 bool PromoteLoad(SDValue Op);
261 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
262 SDValue ExtLoad, const SDLoc &DL,
263 ISD::NodeType ExtType);
265 /// Call the node-specific routine that knows how to fold each
266 /// particular type of node. If that doesn't do anything, try the
267 /// target-specific DAG combines.
268 SDValue combine(SDNode *N);
270 // Visitation implementation - Implement dag node combining for different
271 // node types. The semantics are as follows:
273 // SDValue.getNode() == 0 - No change was made
274 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
275 // otherwise - N should be replaced by the returned Operand.
277 SDValue visitTokenFactor(SDNode *N);
278 SDValue visitMERGE_VALUES(SDNode *N);
279 SDValue visitADD(SDNode *N);
280 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
281 SDValue visitSUB(SDNode *N);
282 SDValue visitADDC(SDNode *N);
283 SDValue visitUADDO(SDNode *N);
284 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
285 SDValue visitSUBC(SDNode *N);
286 SDValue visitUSUBO(SDNode *N);
287 SDValue visitADDE(SDNode *N);
288 SDValue visitADDCARRY(SDNode *N);
289 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
290 SDValue visitSUBE(SDNode *N);
291 SDValue visitSUBCARRY(SDNode *N);
292 SDValue visitMUL(SDNode *N);
293 SDValue useDivRem(SDNode *N);
294 SDValue visitSDIV(SDNode *N);
295 SDValue visitUDIV(SDNode *N);
296 SDValue visitREM(SDNode *N);
297 SDValue visitMULHU(SDNode *N);
298 SDValue visitMULHS(SDNode *N);
299 SDValue visitSMUL_LOHI(SDNode *N);
300 SDValue visitUMUL_LOHI(SDNode *N);
301 SDValue visitSMULO(SDNode *N);
302 SDValue visitUMULO(SDNode *N);
303 SDValue visitIMINMAX(SDNode *N);
304 SDValue visitAND(SDNode *N);
305 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
306 SDValue visitOR(SDNode *N);
307 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
308 SDValue visitXOR(SDNode *N);
309 SDValue SimplifyVBinOp(SDNode *N);
310 SDValue visitSHL(SDNode *N);
311 SDValue visitSRA(SDNode *N);
312 SDValue visitSRL(SDNode *N);
313 SDValue visitRotate(SDNode *N);
314 SDValue visitABS(SDNode *N);
315 SDValue visitBSWAP(SDNode *N);
316 SDValue visitBITREVERSE(SDNode *N);
317 SDValue visitCTLZ(SDNode *N);
318 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
319 SDValue visitCTTZ(SDNode *N);
320 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
321 SDValue visitCTPOP(SDNode *N);
322 SDValue visitSELECT(SDNode *N);
323 SDValue visitVSELECT(SDNode *N);
324 SDValue visitSELECT_CC(SDNode *N);
325 SDValue visitSETCC(SDNode *N);
326 SDValue visitSETCCE(SDNode *N);
327 SDValue visitSETCCCARRY(SDNode *N);
328 SDValue visitSIGN_EXTEND(SDNode *N);
329 SDValue visitZERO_EXTEND(SDNode *N);
330 SDValue visitANY_EXTEND(SDNode *N);
331 SDValue visitAssertExt(SDNode *N);
332 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
333 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
334 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
335 SDValue visitTRUNCATE(SDNode *N);
336 SDValue visitBITCAST(SDNode *N);
337 SDValue visitBUILD_PAIR(SDNode *N);
338 SDValue visitFADD(SDNode *N);
339 SDValue visitFSUB(SDNode *N);
340 SDValue visitFMUL(SDNode *N);
341 SDValue visitFMA(SDNode *N);
342 SDValue visitFDIV(SDNode *N);
343 SDValue visitFREM(SDNode *N);
344 SDValue visitFSQRT(SDNode *N);
345 SDValue visitFCOPYSIGN(SDNode *N);
346 SDValue visitSINT_TO_FP(SDNode *N);
347 SDValue visitUINT_TO_FP(SDNode *N);
348 SDValue visitFP_TO_SINT(SDNode *N);
349 SDValue visitFP_TO_UINT(SDNode *N);
350 SDValue visitFP_ROUND(SDNode *N);
351 SDValue visitFP_ROUND_INREG(SDNode *N);
352 SDValue visitFP_EXTEND(SDNode *N);
353 SDValue visitFNEG(SDNode *N);
354 SDValue visitFABS(SDNode *N);
355 SDValue visitFCEIL(SDNode *N);
356 SDValue visitFTRUNC(SDNode *N);
357 SDValue visitFFLOOR(SDNode *N);
358 SDValue visitFMINNUM(SDNode *N);
359 SDValue visitFMAXNUM(SDNode *N);
360 SDValue visitBRCOND(SDNode *N);
361 SDValue visitBR_CC(SDNode *N);
362 SDValue visitLOAD(SDNode *N);
364 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
365 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
367 SDValue visitSTORE(SDNode *N);
368 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
369 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
370 SDValue visitBUILD_VECTOR(SDNode *N);
371 SDValue visitCONCAT_VECTORS(SDNode *N);
372 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
373 SDValue visitVECTOR_SHUFFLE(SDNode *N);
374 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
375 SDValue visitINSERT_SUBVECTOR(SDNode *N);
376 SDValue visitMLOAD(SDNode *N);
377 SDValue visitMSTORE(SDNode *N);
378 SDValue visitMGATHER(SDNode *N);
379 SDValue visitMSCATTER(SDNode *N);
380 SDValue visitFP_TO_FP16(SDNode *N);
381 SDValue visitFP16_TO_FP(SDNode *N);
383 SDValue visitFADDForFMACombine(SDNode *N);
384 SDValue visitFSUBForFMACombine(SDNode *N);
385 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
387 SDValue XformToShuffleWithZero(SDNode *N);
388 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
391 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
393 SDValue foldSelectOfConstants(SDNode *N);
394 SDValue foldVSelectOfConstants(SDNode *N);
395 SDValue foldBinOpIntoSelect(SDNode *BO);
396 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
397 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
398 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
399 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
400 SDValue N2, SDValue N3, ISD::CondCode CC,
401 bool NotExtCompare = false);
402 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
403 SDValue N2, SDValue N3, ISD::CondCode CC);
404 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
406 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
407 const SDLoc &DL, bool foldBooleans = true);
409 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
411 bool isOneUseSetCC(SDValue N) const;
413 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
415 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
416 SDValue CombineExtLoad(SDNode *N);
417 SDValue combineRepeatedFPDivisors(SDNode *N);
418 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
419 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
420 SDValue BuildSDIV(SDNode *N);
421 SDValue BuildSDIVPow2(SDNode *N);
422 SDValue BuildUDIV(SDNode *N);
423 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
424 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
425 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
426 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
427 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
428 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
429 SDNodeFlags Flags, bool Reciprocal);
430 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
431 SDNodeFlags Flags, bool Reciprocal);
432 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
433 bool DemandHighBits = true);
434 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
435 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
436 SDValue InnerPos, SDValue InnerNeg,
437 unsigned PosOpcode, unsigned NegOpcode,
439 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
440 SDValue MatchLoadCombine(SDNode *N);
441 SDValue ReduceLoadWidth(SDNode *N);
442 SDValue ReduceLoadOpStoreWidth(SDNode *N);
443 SDValue splitMergedValStore(StoreSDNode *ST);
444 SDValue TransformFPLoadStorePair(SDNode *N);
445 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
446 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
447 SDValue reduceBuildVecToShuffle(SDNode *N);
448 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
449 ArrayRef<int> VectorMask, SDValue VecIn1,
450 SDValue VecIn2, unsigned LeftIdx);
451 SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
453 /// Walk up chain skipping non-aliasing memory nodes,
454 /// looking for aliasing nodes and adding them to the Aliases vector.
455 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
456 SmallVectorImpl<SDValue> &Aliases);
458 /// Return true if there is any possibility that the two addresses overlap.
459 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
461 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
462 /// chain (aliasing node.)
463 SDValue FindBetterChain(SDNode *N, SDValue Chain);
465 /// Try to replace a store and any possibly adjacent stores on
466 /// consecutive chains with better chains. Return true only if St is
469 /// Notice that other chains may still be replaced even if the function
471 bool findBetterNeighborChains(StoreSDNode *St);
473 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
474 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
476 /// Holds a pointer to an LSBaseSDNode as well as information on where it
477 /// is located in a sequence of memory operations connected by a chain.
479 // Ptr to the mem node.
480 LSBaseSDNode *MemNode;
482 // Offset from the base ptr.
483 int64_t OffsetFromBase;
485 MemOpLink(LSBaseSDNode *N, int64_t Offset)
486 : MemNode(N), OffsetFromBase(Offset) {}
489 /// This is a helper function for visitMUL to check the profitability
490 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
491 /// MulNode is the original multiply, AddNode is (add x, c1),
492 /// and ConstNode is c2.
493 bool isMulAddWithConstProfitable(SDNode *MulNode,
497 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
498 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
499 /// the type of the loaded value to be extended.
500 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
501 EVT LoadResultTy, EVT &ExtVT);
503 /// Helper function to calculate whether the given Load can have its
504 /// width reduced to ExtVT.
505 bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
506 EVT &ExtVT, unsigned ShAmt = 0);
508 /// Used by BackwardsPropagateMask to find suitable loads.
509 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
510 SmallPtrSetImpl<SDNode*> &NodeWithConsts,
511 ConstantSDNode *Mask, SDNode *&UncombinedNode);
512 /// Attempt to propagate a given AND node back to load leaves so that they
513 /// can be combined into narrow loads.
514 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
516 /// Helper function for MergeConsecutiveStores which merges the
517 /// component store chains.
518 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
521 /// This is a helper function for MergeConsecutiveStores. When the
522 /// source elements of the consecutive stores are all constants or
523 /// all extracted vector elements, try to merge them into one
524 /// larger store introducing bitcasts if necessary. \return True
525 /// if a merged store was created.
526 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
527 EVT MemVT, unsigned NumStores,
528 bool IsConstantSrc, bool UseVector,
531 /// This is a helper function for MergeConsecutiveStores. Stores
532 /// that potentially may be merged with St are placed in
534 void getStoreMergeCandidates(StoreSDNode *St,
535 SmallVectorImpl<MemOpLink> &StoreNodes);
537 /// Helper function for MergeConsecutiveStores. Checks if
538 /// candidate stores have indirect dependency through their
539 /// operands. \return True if safe to merge.
540 bool checkMergeStoreCandidatesForDependencies(
541 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
543 /// Merge consecutive store operations into a wide store.
544 /// This optimization uses wide integers or vectors when possible.
545 /// \return number of stores that were merged into a merged store (the
546 /// affected nodes are stored as a prefix in \p StoreNodes).
547 bool MergeConsecutiveStores(StoreSDNode *N);
549 /// \brief Try to transform a truncation where C is a constant:
550 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
552 /// \p N needs to be a truncation and its first operand an AND. Other
553 /// requirements are checked by the function (e.g. that trunc is
554 /// single-use) and if missed an empty SDValue is returned.
555 SDValue distributeTruncateThroughAnd(SDNode *N);
558 /// Runs the dag combiner on all nodes in the work list
559 void Run(CombineLevel AtLevel);
561 SelectionDAG &getDAG() const { return DAG; }
563 /// Returns a type large enough to hold any valid shift amount - before type
564 /// legalization these can be huge.
565 EVT getShiftAmountTy(EVT LHSTy) {
566 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
567 if (LHSTy.isVector())
569 auto &DL = DAG.getDataLayout();
570 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
571 : TLI.getPointerTy(DL);
574 /// This method returns true if we are running before type legalization or
575 /// if the specified VT is legal.
576 bool isTypeLegal(const EVT &VT) {
577 if (!LegalTypes) return true;
578 return TLI.isTypeLegal(VT);
581 /// Convenience wrapper around TargetLowering::getSetCCResultType
582 EVT getSetCCResultType(EVT VT) const {
583 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
587 /// This class is a DAGUpdateListener that removes any deleted
588 /// nodes from the worklist.
589 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
593 explicit WorklistRemover(DAGCombiner &dc)
594 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
596 void NodeDeleted(SDNode *N, SDNode *E) override {
597 DC.removeFromWorklist(N);
601 } // end anonymous namespace
603 //===----------------------------------------------------------------------===//
604 // TargetLowering::DAGCombinerInfo implementation
605 //===----------------------------------------------------------------------===//
607 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
608 ((DAGCombiner*)DC)->AddToWorklist(N);
611 SDValue TargetLowering::DAGCombinerInfo::
612 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
613 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
616 SDValue TargetLowering::DAGCombinerInfo::
617 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
618 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
621 SDValue TargetLowering::DAGCombinerInfo::
622 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
623 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
626 void TargetLowering::DAGCombinerInfo::
627 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
628 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
631 //===----------------------------------------------------------------------===//
633 //===----------------------------------------------------------------------===//
635 void DAGCombiner::deleteAndRecombine(SDNode *N) {
636 removeFromWorklist(N);
638 // If the operands of this node are only used by the node, they will now be
639 // dead. Make sure to re-visit them and recursively delete dead nodes.
640 for (const SDValue &Op : N->ops())
641 // For an operand generating multiple values, one of the values may
642 // become dead allowing further simplification (e.g. split index
643 // arithmetic from an indexed load).
644 if (Op->hasOneUse() || Op->getNumValues() > 1)
645 AddToWorklist(Op.getNode());
650 /// Return 1 if we can compute the negated form of the specified expression for
651 /// the same cost as the expression itself, or 2 if we can compute the negated
652 /// form more cheaply than the expression itself.
653 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
654 const TargetLowering &TLI,
655 const TargetOptions *Options,
656 unsigned Depth = 0) {
657 // fneg is removable even if it has multiple uses.
658 if (Op.getOpcode() == ISD::FNEG) return 2;
660 // Don't allow anything with multiple uses.
661 if (!Op.hasOneUse()) return 0;
663 // Don't recurse exponentially.
664 if (Depth > 6) return 0;
666 switch (Op.getOpcode()) {
667 default: return false;
668 case ISD::ConstantFP: {
669 if (!LegalOperations)
672 // Don't invert constant FP values after legalization unless the target says
673 // the negated constant is legal.
674 EVT VT = Op.getValueType();
675 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
676 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
679 // FIXME: determine better conditions for this xform.
680 if (!Options->UnsafeFPMath) return 0;
682 // After operation legalization, it might not be legal to create new FSUBs.
683 if (LegalOperations &&
684 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
687 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
688 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
691 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
692 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
695 // We can't turn -(A-B) into B-A when we honor signed zeros.
696 if (!Options->NoSignedZerosFPMath &&
697 !Op.getNode()->getFlags().hasNoSignedZeros())
700 // fold (fneg (fsub A, B)) -> (fsub B, A)
705 if (Options->HonorSignDependentRoundingFPMath()) return 0;
707 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
708 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
712 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
718 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
723 /// If isNegatibleForFree returns true, return the newly negated expression.
724 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
725 bool LegalOperations, unsigned Depth = 0) {
726 const TargetOptions &Options = DAG.getTarget().Options;
727 // fneg is removable even if it has multiple uses.
728 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
730 // Don't allow anything with multiple uses.
731 assert(Op.hasOneUse() && "Unknown reuse!");
733 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
735 const SDNodeFlags Flags = Op.getNode()->getFlags();
737 switch (Op.getOpcode()) {
738 default: llvm_unreachable("Unknown code");
739 case ISD::ConstantFP: {
740 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
742 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
745 // FIXME: determine better conditions for this xform.
746 assert(Options.UnsafeFPMath);
748 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
749 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
750 DAG.getTargetLoweringInfo(), &Options, Depth+1))
751 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
752 GetNegatedExpression(Op.getOperand(0), DAG,
753 LegalOperations, Depth+1),
754 Op.getOperand(1), Flags);
755 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
756 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
757 GetNegatedExpression(Op.getOperand(1), DAG,
758 LegalOperations, Depth+1),
759 Op.getOperand(0), Flags);
761 // fold (fneg (fsub 0, B)) -> B
762 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
764 return Op.getOperand(1);
766 // fold (fneg (fsub A, B)) -> (fsub B, A)
767 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
768 Op.getOperand(1), Op.getOperand(0), Flags);
772 assert(!Options.HonorSignDependentRoundingFPMath());
774 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
775 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
776 DAG.getTargetLoweringInfo(), &Options, Depth+1))
777 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
778 GetNegatedExpression(Op.getOperand(0), DAG,
779 LegalOperations, Depth+1),
780 Op.getOperand(1), Flags);
782 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
783 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
785 GetNegatedExpression(Op.getOperand(1), DAG,
786 LegalOperations, Depth+1), Flags);
790 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
791 GetNegatedExpression(Op.getOperand(0), DAG,
792 LegalOperations, Depth+1));
794 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
795 GetNegatedExpression(Op.getOperand(0), DAG,
796 LegalOperations, Depth+1),
801 // APInts must be the same size for most operations, this helper
802 // function zero extends the shorter of the pair so that they match.
803 // We provide an Offset so that we can create bitwidths that won't overflow.
804 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
805 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
806 LHS = LHS.zextOrSelf(Bits);
807 RHS = RHS.zextOrSelf(Bits);
810 // Return true if this node is a setcc, or is a select_cc
811 // that selects between the target values used for true and false, making it
812 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
813 // the appropriate nodes based on the type of node we are checking. This
814 // simplifies life a bit for the callers.
815 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
817 if (N.getOpcode() == ISD::SETCC) {
818 LHS = N.getOperand(0);
819 RHS = N.getOperand(1);
820 CC = N.getOperand(2);
824 if (N.getOpcode() != ISD::SELECT_CC ||
825 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
826 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
829 if (TLI.getBooleanContents(N.getValueType()) ==
830 TargetLowering::UndefinedBooleanContent)
833 LHS = N.getOperand(0);
834 RHS = N.getOperand(1);
835 CC = N.getOperand(4);
839 /// Return true if this is a SetCC-equivalent operation with only one use.
840 /// If this is true, it allows the users to invert the operation for free when
841 /// it is profitable to do so.
842 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
844 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
849 // \brief Returns the SDNode if it is a constant float BuildVector
850 // or constant float.
851 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
852 if (isa<ConstantFPSDNode>(N))
854 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
859 // Determines if it is a constant integer or a build vector of constant
860 // integers (and undefs).
861 // Do not permit build vector implicit truncation.
862 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
863 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
864 return !(Const->isOpaque() && NoOpaques);
865 if (N.getOpcode() != ISD::BUILD_VECTOR)
867 unsigned BitWidth = N.getScalarValueSizeInBits();
868 for (const SDValue &Op : N->op_values()) {
871 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
872 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
873 (Const->isOpaque() && NoOpaques))
879 // Determines if it is a constant null integer or a splatted vector of a
880 // constant null integer (with no undefs).
881 // Build vector implicit truncation is not an issue for null values.
882 static bool isNullConstantOrNullSplatConstant(SDValue N) {
883 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
884 return Splat->isNullValue();
888 // Determines if it is a constant integer of one or a splatted vector of a
889 // constant integer of one (with no undefs).
890 // Do not permit build vector implicit truncation.
891 static bool isOneConstantOrOneSplatConstant(SDValue N) {
892 unsigned BitWidth = N.getScalarValueSizeInBits();
893 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
894 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
898 // Determines if it is a constant integer of all ones or a splatted vector of a
899 // constant integer of all ones (with no undefs).
900 // Do not permit build vector implicit truncation.
901 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
902 unsigned BitWidth = N.getScalarValueSizeInBits();
903 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
904 return Splat->isAllOnesValue() &&
905 Splat->getAPIntValue().getBitWidth() == BitWidth;
909 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
911 static bool isAnyConstantBuildVector(const SDNode *N) {
912 return ISD::isBuildVectorOfConstantSDNodes(N) ||
913 ISD::isBuildVectorOfConstantFPSDNodes(N);
916 // Attempt to match a unary predicate against a scalar/splat constant or
917 // every element of a constant BUILD_VECTOR.
918 static bool matchUnaryPredicate(SDValue Op,
919 std::function<bool(ConstantSDNode *)> Match) {
920 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
923 if (ISD::BUILD_VECTOR != Op.getOpcode())
926 EVT SVT = Op.getValueType().getScalarType();
927 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
928 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
929 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
935 // Attempt to match a binary predicate against a pair of scalar/splat constants
936 // or every element of a pair of constant BUILD_VECTORs.
937 static bool matchBinaryPredicate(
938 SDValue LHS, SDValue RHS,
939 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
940 if (LHS.getValueType() != RHS.getValueType())
943 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
944 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
945 return Match(LHSCst, RHSCst);
947 if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
948 ISD::BUILD_VECTOR != RHS.getOpcode())
951 EVT SVT = LHS.getValueType().getScalarType();
952 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
953 auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
954 auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
955 if (!LHSCst || !RHSCst)
957 if (LHSCst->getValueType(0) != SVT ||
958 LHSCst->getValueType(0) != RHSCst->getValueType(0))
960 if (!Match(LHSCst, RHSCst))
966 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
968 EVT VT = N0.getValueType();
969 if (N0.getOpcode() == Opc) {
970 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
971 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
972 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
973 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
974 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
977 if (N0.hasOneUse()) {
978 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
980 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
981 if (!OpNode.getNode())
983 AddToWorklist(OpNode.getNode());
984 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
989 if (N1.getOpcode() == Opc) {
990 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
991 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
992 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
993 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
994 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
997 if (N1.hasOneUse()) {
998 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
1000 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
1001 if (!OpNode.getNode())
1003 AddToWorklist(OpNode.getNode());
1004 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
1012 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1014 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1016 DEBUG(dbgs() << "\nReplacing.1 ";
1018 dbgs() << "\nWith: ";
1019 To[0].getNode()->dump(&DAG);
1020 dbgs() << " and " << NumTo-1 << " other values\n");
1021 for (unsigned i = 0, e = NumTo; i != e; ++i)
1022 assert((!To[i].getNode() ||
1023 N->getValueType(i) == To[i].getValueType()) &&
1024 "Cannot combine value to value of different type!");
1026 WorklistRemover DeadNodes(*this);
1027 DAG.ReplaceAllUsesWith(N, To);
1029 // Push the new nodes and any users onto the worklist
1030 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1031 if (To[i].getNode()) {
1032 AddToWorklist(To[i].getNode());
1033 AddUsersToWorklist(To[i].getNode());
1038 // Finally, if the node is now dead, remove it from the graph. The node
1039 // may not be dead if the replacement process recursively simplified to
1040 // something else needing this node.
1042 deleteAndRecombine(N);
1043 return SDValue(N, 0);
1047 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1048 // Replace all uses. If any nodes become isomorphic to other nodes and
1049 // are deleted, make sure to remove them from our worklist.
1050 WorklistRemover DeadNodes(*this);
1051 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1053 // Push the new node and any (possibly new) users onto the worklist.
1054 AddToWorklist(TLO.New.getNode());
1055 AddUsersToWorklist(TLO.New.getNode());
1057 // Finally, if the node is now dead, remove it from the graph. The node
1058 // may not be dead if the replacement process recursively simplified to
1059 // something else needing this node.
1060 if (TLO.Old.getNode()->use_empty())
1061 deleteAndRecombine(TLO.Old.getNode());
1064 /// Check the specified integer node value to see if it can be simplified or if
1065 /// things it uses can be simplified by bit propagation. If so, return true.
1066 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1067 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1069 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1072 // Revisit the node.
1073 AddToWorklist(Op.getNode());
1075 // Replace the old value with the new one.
1077 DEBUG(dbgs() << "\nReplacing.2 ";
1078 TLO.Old.getNode()->dump(&DAG);
1079 dbgs() << "\nWith: ";
1080 TLO.New.getNode()->dump(&DAG);
1083 CommitTargetLoweringOpt(TLO);
1087 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1089 EVT VT = Load->getValueType(0);
1090 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1092 DEBUG(dbgs() << "\nReplacing.9 ";
1094 dbgs() << "\nWith: ";
1095 Trunc.getNode()->dump(&DAG);
1097 WorklistRemover DeadNodes(*this);
1098 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1099 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1100 deleteAndRecombine(Load);
1101 AddToWorklist(Trunc.getNode());
1104 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1107 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1108 LoadSDNode *LD = cast<LoadSDNode>(Op);
1109 EVT MemVT = LD->getMemoryVT();
1110 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1111 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1113 : LD->getExtensionType();
1115 return DAG.getExtLoad(ExtType, DL, PVT,
1116 LD->getChain(), LD->getBasePtr(),
1117 MemVT, LD->getMemOperand());
1120 unsigned Opc = Op.getOpcode();
1123 case ISD::AssertSext:
1124 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1125 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1127 case ISD::AssertZext:
1128 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1129 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1131 case ISD::Constant: {
1133 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1134 return DAG.getNode(ExtOpc, DL, PVT, Op);
1138 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1140 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1143 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1144 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1146 EVT OldVT = Op.getValueType();
1148 bool Replace = false;
1149 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1150 if (!NewOp.getNode())
1152 AddToWorklist(NewOp.getNode());
1155 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1156 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1157 DAG.getValueType(OldVT));
1160 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1161 EVT OldVT = Op.getValueType();
1163 bool Replace = false;
1164 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1165 if (!NewOp.getNode())
1167 AddToWorklist(NewOp.getNode());
1170 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1171 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1174 /// Promote the specified integer binary operation if the target indicates it is
1175 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1176 /// i32 since i16 instructions are longer.
1177 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1178 if (!LegalOperations)
1181 EVT VT = Op.getValueType();
1182 if (VT.isVector() || !VT.isInteger())
1185 // If operation type is 'undesirable', e.g. i16 on x86, consider
1187 unsigned Opc = Op.getOpcode();
1188 if (TLI.isTypeDesirableForOp(Opc, VT))
1192 // Consult target whether it is a good idea to promote this operation and
1193 // what's the right type to promote it to.
1194 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1195 assert(PVT != VT && "Don't know what type to promote to!");
1197 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1199 bool Replace0 = false;
1200 SDValue N0 = Op.getOperand(0);
1201 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1203 bool Replace1 = false;
1204 SDValue N1 = Op.getOperand(1);
1205 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1209 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1211 // We are always replacing N0/N1's use in N and only need
1212 // additional replacements if there are additional uses.
1213 Replace0 &= !N0->hasOneUse();
1214 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1216 // Combine Op here so it is preserved past replacements.
1217 CombineTo(Op.getNode(), RV);
1219 // If operands have a use ordering, make sure we deal with
1220 // predecessor first.
1221 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1223 std::swap(NN0, NN1);
1227 AddToWorklist(NN0.getNode());
1228 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1231 AddToWorklist(NN1.getNode());
1232 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1239 /// Promote the specified integer shift operation if the target indicates it is
1240 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1241 /// i32 since i16 instructions are longer.
1242 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1243 if (!LegalOperations)
1246 EVT VT = Op.getValueType();
1247 if (VT.isVector() || !VT.isInteger())
1250 // If operation type is 'undesirable', e.g. i16 on x86, consider
1252 unsigned Opc = Op.getOpcode();
1253 if (TLI.isTypeDesirableForOp(Opc, VT))
1257 // Consult target whether it is a good idea to promote this operation and
1258 // what's the right type to promote it to.
1259 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1260 assert(PVT != VT && "Don't know what type to promote to!");
1262 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1264 bool Replace = false;
1265 SDValue N0 = Op.getOperand(0);
1266 SDValue N1 = Op.getOperand(1);
1267 if (Opc == ISD::SRA)
1268 N0 = SExtPromoteOperand(N0, PVT);
1269 else if (Opc == ISD::SRL)
1270 N0 = ZExtPromoteOperand(N0, PVT);
1272 N0 = PromoteOperand(N0, PVT, Replace);
1279 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1281 AddToWorklist(N0.getNode());
1283 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1285 // Deal with Op being deleted.
1286 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1292 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1293 if (!LegalOperations)
1296 EVT VT = Op.getValueType();
1297 if (VT.isVector() || !VT.isInteger())
1300 // If operation type is 'undesirable', e.g. i16 on x86, consider
1302 unsigned Opc = Op.getOpcode();
1303 if (TLI.isTypeDesirableForOp(Opc, VT))
1307 // Consult target whether it is a good idea to promote this operation and
1308 // what's the right type to promote it to.
1309 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1310 assert(PVT != VT && "Don't know what type to promote to!");
1311 // fold (aext (aext x)) -> (aext x)
1312 // fold (aext (zext x)) -> (zext x)
1313 // fold (aext (sext x)) -> (sext x)
1314 DEBUG(dbgs() << "\nPromoting ";
1315 Op.getNode()->dump(&DAG));
1316 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1321 bool DAGCombiner::PromoteLoad(SDValue Op) {
1322 if (!LegalOperations)
1325 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1328 EVT VT = Op.getValueType();
1329 if (VT.isVector() || !VT.isInteger())
1332 // If operation type is 'undesirable', e.g. i16 on x86, consider
1334 unsigned Opc = Op.getOpcode();
1335 if (TLI.isTypeDesirableForOp(Opc, VT))
1339 // Consult target whether it is a good idea to promote this operation and
1340 // what's the right type to promote it to.
1341 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1342 assert(PVT != VT && "Don't know what type to promote to!");
1345 SDNode *N = Op.getNode();
1346 LoadSDNode *LD = cast<LoadSDNode>(N);
1347 EVT MemVT = LD->getMemoryVT();
1348 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1349 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1351 : LD->getExtensionType();
1352 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1353 LD->getChain(), LD->getBasePtr(),
1354 MemVT, LD->getMemOperand());
1355 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1357 DEBUG(dbgs() << "\nPromoting ";
1360 Result.getNode()->dump(&DAG);
1362 WorklistRemover DeadNodes(*this);
1363 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1364 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1365 deleteAndRecombine(N);
1366 AddToWorklist(Result.getNode());
1372 /// \brief Recursively delete a node which has no uses and any operands for
1373 /// which it is the only use.
1375 /// Note that this both deletes the nodes and removes them from the worklist.
1376 /// It also adds any nodes who have had a user deleted to the worklist as they
1377 /// may now have only one use and subject to other combines.
1378 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1379 if (!N->use_empty())
1382 SmallSetVector<SDNode *, 16> Nodes;
1385 N = Nodes.pop_back_val();
1389 if (N->use_empty()) {
1390 for (const SDValue &ChildN : N->op_values())
1391 Nodes.insert(ChildN.getNode());
1393 removeFromWorklist(N);
1398 } while (!Nodes.empty());
1402 //===----------------------------------------------------------------------===//
1403 // Main DAG Combiner implementation
1404 //===----------------------------------------------------------------------===//
1406 void DAGCombiner::Run(CombineLevel AtLevel) {
1407 // set the instance variables, so that the various visit routines may use it.
1409 LegalOperations = Level >= AfterLegalizeVectorOps;
1410 LegalTypes = Level >= AfterLegalizeTypes;
1412 // Add all the dag nodes to the worklist.
1413 for (SDNode &Node : DAG.allnodes())
1414 AddToWorklist(&Node);
1416 // Create a dummy node (which is not added to allnodes), that adds a reference
1417 // to the root node, preventing it from being deleted, and tracking any
1418 // changes of the root.
1419 HandleSDNode Dummy(DAG.getRoot());
1421 // While the worklist isn't empty, find a node and try to combine it.
1422 while (!WorklistMap.empty()) {
1424 // The Worklist holds the SDNodes in order, but it may contain null entries.
1426 N = Worklist.pop_back_val();
1429 bool GoodWorklistEntry = WorklistMap.erase(N);
1430 (void)GoodWorklistEntry;
1431 assert(GoodWorklistEntry &&
1432 "Found a worklist entry without a corresponding map entry!");
1434 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1435 // N is deleted from the DAG, since they too may now be dead or may have a
1436 // reduced number of uses, allowing other xforms.
1437 if (recursivelyDeleteUnusedNodes(N))
1440 WorklistRemover DeadNodes(*this);
1442 // If this combine is running after legalizing the DAG, re-legalize any
1443 // nodes pulled off the worklist.
1444 if (Level == AfterLegalizeDAG) {
1445 SmallSetVector<SDNode *, 16> UpdatedNodes;
1446 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1448 for (SDNode *LN : UpdatedNodes) {
1450 AddUsersToWorklist(LN);
1456 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1458 // Add any operands of the new node which have not yet been combined to the
1459 // worklist as well. Because the worklist uniques things already, this
1460 // won't repeatedly process the same operand.
1461 CombinedNodes.insert(N);
1462 for (const SDValue &ChildN : N->op_values())
1463 if (!CombinedNodes.count(ChildN.getNode()))
1464 AddToWorklist(ChildN.getNode());
1466 SDValue RV = combine(N);
1473 // If we get back the same node we passed in, rather than a new node or
1474 // zero, we know that the node must have defined multiple values and
1475 // CombineTo was used. Since CombineTo takes care of the worklist
1476 // mechanics for us, we have no work to do in this case.
1477 if (RV.getNode() == N)
1480 assert(N->getOpcode() != ISD::DELETED_NODE &&
1481 RV.getOpcode() != ISD::DELETED_NODE &&
1482 "Node was deleted but visit returned new node!");
1484 DEBUG(dbgs() << " ... into: ";
1485 RV.getNode()->dump(&DAG));
1487 if (N->getNumValues() == RV.getNode()->getNumValues())
1488 DAG.ReplaceAllUsesWith(N, RV.getNode());
1490 assert(N->getValueType(0) == RV.getValueType() &&
1491 N->getNumValues() == 1 && "Type mismatch");
1492 DAG.ReplaceAllUsesWith(N, &RV);
1495 // Push the new node and any users onto the worklist
1496 AddToWorklist(RV.getNode());
1497 AddUsersToWorklist(RV.getNode());
1499 // Finally, if the node is now dead, remove it from the graph. The node
1500 // may not be dead if the replacement process recursively simplified to
1501 // something else needing this node. This will also take care of adding any
1502 // operands which have lost a user to the worklist.
1503 recursivelyDeleteUnusedNodes(N);
1506 // If the root changed (e.g. it was a dead load, update the root).
1507 DAG.setRoot(Dummy.getValue());
1508 DAG.RemoveDeadNodes();
1511 SDValue DAGCombiner::visit(SDNode *N) {
1512 switch (N->getOpcode()) {
1514 case ISD::TokenFactor: return visitTokenFactor(N);
1515 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1516 case ISD::ADD: return visitADD(N);
1517 case ISD::SUB: return visitSUB(N);
1518 case ISD::ADDC: return visitADDC(N);
1519 case ISD::UADDO: return visitUADDO(N);
1520 case ISD::SUBC: return visitSUBC(N);
1521 case ISD::USUBO: return visitUSUBO(N);
1522 case ISD::ADDE: return visitADDE(N);
1523 case ISD::ADDCARRY: return visitADDCARRY(N);
1524 case ISD::SUBE: return visitSUBE(N);
1525 case ISD::SUBCARRY: return visitSUBCARRY(N);
1526 case ISD::MUL: return visitMUL(N);
1527 case ISD::SDIV: return visitSDIV(N);
1528 case ISD::UDIV: return visitUDIV(N);
1530 case ISD::UREM: return visitREM(N);
1531 case ISD::MULHU: return visitMULHU(N);
1532 case ISD::MULHS: return visitMULHS(N);
1533 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1534 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1535 case ISD::SMULO: return visitSMULO(N);
1536 case ISD::UMULO: return visitUMULO(N);
1540 case ISD::UMAX: return visitIMINMAX(N);
1541 case ISD::AND: return visitAND(N);
1542 case ISD::OR: return visitOR(N);
1543 case ISD::XOR: return visitXOR(N);
1544 case ISD::SHL: return visitSHL(N);
1545 case ISD::SRA: return visitSRA(N);
1546 case ISD::SRL: return visitSRL(N);
1548 case ISD::ROTL: return visitRotate(N);
1549 case ISD::ABS: return visitABS(N);
1550 case ISD::BSWAP: return visitBSWAP(N);
1551 case ISD::BITREVERSE: return visitBITREVERSE(N);
1552 case ISD::CTLZ: return visitCTLZ(N);
1553 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1554 case ISD::CTTZ: return visitCTTZ(N);
1555 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1556 case ISD::CTPOP: return visitCTPOP(N);
1557 case ISD::SELECT: return visitSELECT(N);
1558 case ISD::VSELECT: return visitVSELECT(N);
1559 case ISD::SELECT_CC: return visitSELECT_CC(N);
1560 case ISD::SETCC: return visitSETCC(N);
1561 case ISD::SETCCE: return visitSETCCE(N);
1562 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1563 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1564 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1565 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1566 case ISD::AssertSext:
1567 case ISD::AssertZext: return visitAssertExt(N);
1568 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1569 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1570 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1571 case ISD::TRUNCATE: return visitTRUNCATE(N);
1572 case ISD::BITCAST: return visitBITCAST(N);
1573 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1574 case ISD::FADD: return visitFADD(N);
1575 case ISD::FSUB: return visitFSUB(N);
1576 case ISD::FMUL: return visitFMUL(N);
1577 case ISD::FMA: return visitFMA(N);
1578 case ISD::FDIV: return visitFDIV(N);
1579 case ISD::FREM: return visitFREM(N);
1580 case ISD::FSQRT: return visitFSQRT(N);
1581 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1582 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1583 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1584 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1585 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1586 case ISD::FP_ROUND: return visitFP_ROUND(N);
1587 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1588 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1589 case ISD::FNEG: return visitFNEG(N);
1590 case ISD::FABS: return visitFABS(N);
1591 case ISD::FFLOOR: return visitFFLOOR(N);
1592 case ISD::FMINNUM: return visitFMINNUM(N);
1593 case ISD::FMAXNUM: return visitFMAXNUM(N);
1594 case ISD::FCEIL: return visitFCEIL(N);
1595 case ISD::FTRUNC: return visitFTRUNC(N);
1596 case ISD::BRCOND: return visitBRCOND(N);
1597 case ISD::BR_CC: return visitBR_CC(N);
1598 case ISD::LOAD: return visitLOAD(N);
1599 case ISD::STORE: return visitSTORE(N);
1600 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1601 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1602 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1603 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1604 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1605 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1606 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1607 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1608 case ISD::MGATHER: return visitMGATHER(N);
1609 case ISD::MLOAD: return visitMLOAD(N);
1610 case ISD::MSCATTER: return visitMSCATTER(N);
1611 case ISD::MSTORE: return visitMSTORE(N);
1612 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1613 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1618 SDValue DAGCombiner::combine(SDNode *N) {
1619 SDValue RV = visit(N);
1621 // If nothing happened, try a target-specific DAG combine.
1622 if (!RV.getNode()) {
1623 assert(N->getOpcode() != ISD::DELETED_NODE &&
1624 "Node was deleted but visit returned NULL!");
1626 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1627 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1629 // Expose the DAG combiner to the target combiner impls.
1630 TargetLowering::DAGCombinerInfo
1631 DagCombineInfo(DAG, Level, false, this);
1633 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1637 // If nothing happened still, try promoting the operation.
1638 if (!RV.getNode()) {
1639 switch (N->getOpcode()) {
1647 RV = PromoteIntBinOp(SDValue(N, 0));
1652 RV = PromoteIntShiftOp(SDValue(N, 0));
1654 case ISD::SIGN_EXTEND:
1655 case ISD::ZERO_EXTEND:
1656 case ISD::ANY_EXTEND:
1657 RV = PromoteExtend(SDValue(N, 0));
1660 if (PromoteLoad(SDValue(N, 0)))
1666 // If N is a commutative binary node, try eliminate it if the commuted
1667 // version is already present in the DAG.
1668 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1669 N->getNumValues() == 1) {
1670 SDValue N0 = N->getOperand(0);
1671 SDValue N1 = N->getOperand(1);
1673 // Constant operands are canonicalized to RHS.
1674 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1675 SDValue Ops[] = {N1, N0};
1676 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1679 return SDValue(CSENode, 0);
1686 /// Given a node, return its input chain if it has one, otherwise return a null
1688 static SDValue getInputChainForNode(SDNode *N) {
1689 if (unsigned NumOps = N->getNumOperands()) {
1690 if (N->getOperand(0).getValueType() == MVT::Other)
1691 return N->getOperand(0);
1692 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1693 return N->getOperand(NumOps-1);
1694 for (unsigned i = 1; i < NumOps-1; ++i)
1695 if (N->getOperand(i).getValueType() == MVT::Other)
1696 return N->getOperand(i);
1701 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1702 // If N has two operands, where one has an input chain equal to the other,
1703 // the 'other' chain is redundant.
1704 if (N->getNumOperands() == 2) {
1705 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1706 return N->getOperand(0);
1707 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1708 return N->getOperand(1);
1711 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1712 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1713 SmallPtrSet<SDNode*, 16> SeenOps;
1714 bool Changed = false; // If we should replace this token factor.
1716 // Start out with this token factor.
1719 // Iterate through token factors. The TFs grows when new token factors are
1721 for (unsigned i = 0; i < TFs.size(); ++i) {
1722 SDNode *TF = TFs[i];
1724 // Check each of the operands.
1725 for (const SDValue &Op : TF->op_values()) {
1726 switch (Op.getOpcode()) {
1727 case ISD::EntryToken:
1728 // Entry tokens don't need to be added to the list. They are
1733 case ISD::TokenFactor:
1734 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1735 // Queue up for processing.
1736 TFs.push_back(Op.getNode());
1737 // Clean up in case the token factor is removed.
1738 AddToWorklist(Op.getNode());
1745 // Only add if it isn't already in the list.
1746 if (SeenOps.insert(Op.getNode()).second)
1755 // Remove Nodes that are chained to another node in the list. Do so
1756 // by walking up chains breath-first stopping when we've seen
1757 // another operand. In general we must climb to the EntryNode, but we can exit
1758 // early if we find all remaining work is associated with just one operand as
1759 // no further pruning is possible.
1761 // List of nodes to search through and original Ops from which they originate.
1762 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1763 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1764 SmallPtrSet<SDNode *, 16> SeenChains;
1765 bool DidPruneOps = false;
1767 unsigned NumLeftToConsider = 0;
1768 for (const SDValue &Op : Ops) {
1769 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1770 OpWorkCount.push_back(1);
1773 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1774 // If this is an Op, we can remove the op from the list. Remark any
1775 // search associated with it as from the current OpNumber.
1776 if (SeenOps.count(Op) != 0) {
1779 unsigned OrigOpNumber = 0;
1780 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1782 assert((OrigOpNumber != Ops.size()) &&
1783 "expected to find TokenFactor Operand");
1784 // Re-mark worklist from OrigOpNumber to OpNumber
1785 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1786 if (Worklist[i].second == OrigOpNumber) {
1787 Worklist[i].second = OpNumber;
1790 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1791 OpWorkCount[OrigOpNumber] = 0;
1792 NumLeftToConsider--;
1794 // Add if it's a new chain
1795 if (SeenChains.insert(Op).second) {
1796 OpWorkCount[OpNumber]++;
1797 Worklist.push_back(std::make_pair(Op, OpNumber));
1801 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1802 // We need at least be consider at least 2 Ops to prune.
1803 if (NumLeftToConsider <= 1)
1805 auto CurNode = Worklist[i].first;
1806 auto CurOpNumber = Worklist[i].second;
1807 assert((OpWorkCount[CurOpNumber] > 0) &&
1808 "Node should not appear in worklist");
1809 switch (CurNode->getOpcode()) {
1810 case ISD::EntryToken:
1811 // Hitting EntryToken is the only way for the search to terminate without
1813 // another operand's search. Prevent us from marking this operand
1815 NumLeftToConsider++;
1817 case ISD::TokenFactor:
1818 for (const SDValue &Op : CurNode->op_values())
1819 AddToWorklist(i, Op.getNode(), CurOpNumber);
1821 case ISD::CopyFromReg:
1822 case ISD::CopyToReg:
1823 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1826 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1827 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1830 OpWorkCount[CurOpNumber]--;
1831 if (OpWorkCount[CurOpNumber] == 0)
1832 NumLeftToConsider--;
1835 // If we've changed things around then replace token factor.
1839 // The entry token is the only possible outcome.
1840 Result = DAG.getEntryNode();
1843 SmallVector<SDValue, 8> PrunedOps;
1845 for (const SDValue &Op : Ops) {
1846 if (SeenChains.count(Op.getNode()) == 0)
1847 PrunedOps.push_back(Op);
1849 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1851 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1859 /// MERGE_VALUES can always be eliminated.
1860 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1861 WorklistRemover DeadNodes(*this);
1862 // Replacing results may cause a different MERGE_VALUES to suddenly
1863 // be CSE'd with N, and carry its uses with it. Iterate until no
1864 // uses remain, to ensure that the node can be safely deleted.
1865 // First add the users of this node to the work list so that they
1866 // can be tried again once they have new operands.
1867 AddUsersToWorklist(N);
1869 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1871 } while (!N->use_empty());
1872 deleteAndRecombine(N);
1873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1876 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1877 /// ConstantSDNode pointer else nullptr.
1878 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1879 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1880 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1883 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1884 auto BinOpcode = BO->getOpcode();
1885 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1886 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1887 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1888 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1889 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1890 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1891 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1892 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1893 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1894 "Unexpected binary operator");
1896 // Bail out if any constants are opaque because we can't constant fold those.
1897 SDValue C1 = BO->getOperand(1);
1898 if (!isConstantOrConstantVector(C1, true) &&
1899 !isConstantFPBuildVectorOrConstantFP(C1))
1902 // Don't do this unless the old select is going away. We want to eliminate the
1903 // binary operator, not replace a binop with a select.
1904 // TODO: Handle ISD::SELECT_CC.
1905 SDValue Sel = BO->getOperand(0);
1906 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1909 SDValue CT = Sel.getOperand(1);
1910 if (!isConstantOrConstantVector(CT, true) &&
1911 !isConstantFPBuildVectorOrConstantFP(CT))
1914 SDValue CF = Sel.getOperand(2);
1915 if (!isConstantOrConstantVector(CF, true) &&
1916 !isConstantFPBuildVectorOrConstantFP(CF))
1919 // We have a select-of-constants followed by a binary operator with a
1920 // constant. Eliminate the binop by pulling the constant math into the select.
1921 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1922 EVT VT = Sel.getValueType();
1924 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1925 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1926 isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1927 "Failed to constant fold a binop with constant operands");
1929 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1930 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1931 isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1932 "Failed to constant fold a binop with constant operands");
1934 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1937 SDValue DAGCombiner::visitADD(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
1940 EVT VT = N0.getValueType();
1944 if (VT.isVector()) {
1945 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1948 // fold (add x, 0) -> x, vector edition
1949 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1951 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1955 // fold (add x, undef) -> undef
1962 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1963 // canonicalize constant to RHS
1964 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1965 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1966 // fold (add c1, c2) -> c1+c2
1967 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1971 // fold (add x, 0) -> x
1972 if (isNullConstant(N1))
1975 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1976 // fold ((c1-A)+c2) -> (c1+c2)-A
1977 if (N0.getOpcode() == ISD::SUB &&
1978 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1979 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1980 return DAG.getNode(ISD::SUB, DL, VT,
1981 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1985 // add (sext i1 X), 1 -> zext (not i1 X)
1986 // We don't transform this pattern:
1987 // add (zext i1 X), -1 -> sext (not i1 X)
1988 // because most (?) targets generate better code for the zext form.
1989 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1990 isOneConstantOrOneSplatConstant(N1)) {
1991 SDValue X = N0.getOperand(0);
1992 if ((!LegalOperations ||
1993 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1994 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1995 X.getScalarValueSizeInBits() == 1) {
1996 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1997 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2001 // Undo the add -> or combine to merge constant offsets from a frame index.
2002 if (N0.getOpcode() == ISD::OR &&
2003 isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2004 isa<ConstantSDNode>(N0.getOperand(1)) &&
2005 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2006 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2007 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2011 if (SDValue NewSel = foldBinOpIntoSelect(N))
2015 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2018 // fold ((0-A) + B) -> B-A
2019 if (N0.getOpcode() == ISD::SUB &&
2020 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2021 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2023 // fold (A + (0-B)) -> A-B
2024 if (N1.getOpcode() == ISD::SUB &&
2025 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2026 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2028 // fold (A+(B-A)) -> B
2029 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2030 return N1.getOperand(0);
2032 // fold ((B-A)+A) -> B
2033 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2034 return N0.getOperand(0);
2036 // fold (A+(B-(A+C))) to (B-C)
2037 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2038 N0 == N1.getOperand(1).getOperand(0))
2039 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2040 N1.getOperand(1).getOperand(1));
2042 // fold (A+(B-(C+A))) to (B-C)
2043 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2044 N0 == N1.getOperand(1).getOperand(1))
2045 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2046 N1.getOperand(1).getOperand(0));
2048 // fold (A+((B-A)+or-C)) to (B+or-C)
2049 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2050 N1.getOperand(0).getOpcode() == ISD::SUB &&
2051 N0 == N1.getOperand(0).getOperand(1))
2052 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2055 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2056 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2057 SDValue N00 = N0.getOperand(0);
2058 SDValue N01 = N0.getOperand(1);
2059 SDValue N10 = N1.getOperand(0);
2060 SDValue N11 = N1.getOperand(1);
2062 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2063 return DAG.getNode(ISD::SUB, DL, VT,
2064 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2065 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2068 if (SimplifyDemandedBits(SDValue(N, 0)))
2069 return SDValue(N, 0);
2071 // fold (a+b) -> (a|b) iff a and b share no bits.
2072 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2073 DAG.haveNoCommonBitsSet(N0, N1))
2074 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2076 if (SDValue Combined = visitADDLike(N0, N1, N))
2079 if (SDValue Combined = visitADDLike(N1, N0, N))
2085 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2086 bool Masked = false;
2088 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2090 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2091 V = V.getOperand(0);
2095 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2097 V = V.getOperand(0);
2104 // If this is not a carry, return.
2105 if (V.getResNo() != 1)
2108 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2109 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2112 // If the result is masked, then no matter what kind of bool it is we can
2113 // return. If it isn't, then we need to make sure the bool type is either 0 or
2114 // 1 and not other values.
2116 TLI.getBooleanContents(V.getValueType()) ==
2117 TargetLoweringBase::ZeroOrOneBooleanContent)
2123 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2124 EVT VT = N0.getValueType();
2125 SDLoc DL(LocReference);
2127 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2128 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2129 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2130 return DAG.getNode(ISD::SUB, DL, VT, N0,
2131 DAG.getNode(ISD::SHL, DL, VT,
2132 N1.getOperand(0).getOperand(1),
2135 if (N1.getOpcode() == ISD::AND) {
2136 SDValue AndOp0 = N1.getOperand(0);
2137 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2138 unsigned DestBits = VT.getScalarSizeInBits();
2140 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2141 // and similar xforms where the inner op is either ~0 or 0.
2142 if (NumSignBits == DestBits &&
2143 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2144 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2147 // add (sext i1), X -> sub X, (zext i1)
2148 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2149 N0.getOperand(0).getValueType() == MVT::i1 &&
2150 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2151 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2152 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2155 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2156 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2157 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2158 if (TN->getVT() == MVT::i1) {
2159 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2160 DAG.getConstant(1, DL, VT));
2161 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2165 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2166 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2168 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2169 N0, N1.getOperand(0), N1.getOperand(2));
2171 // (add X, Carry) -> (addcarry X, 0, Carry)
2172 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2173 if (SDValue Carry = getAsCarry(TLI, N1))
2174 return DAG.getNode(ISD::ADDCARRY, DL,
2175 DAG.getVTList(VT, Carry.getValueType()), N0,
2176 DAG.getConstant(0, DL, VT), Carry);
2181 SDValue DAGCombiner::visitADDC(SDNode *N) {
2182 SDValue N0 = N->getOperand(0);
2183 SDValue N1 = N->getOperand(1);
2184 EVT VT = N0.getValueType();
2187 // If the flag result is dead, turn this into an ADD.
2188 if (!N->hasAnyUseOfValue(1))
2189 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2190 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2192 // canonicalize constant to RHS.
2193 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2194 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2196 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2198 // fold (addc x, 0) -> x + no carry out
2199 if (isNullConstant(N1))
2200 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2203 // If it cannot overflow, transform into an add.
2204 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2205 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2206 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2211 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2212 SDValue N0 = N->getOperand(0);
2213 SDValue N1 = N->getOperand(1);
2214 EVT VT = N0.getValueType();
2218 EVT CarryVT = N->getValueType(1);
2221 // If the flag result is dead, turn this into an ADD.
2222 if (!N->hasAnyUseOfValue(1))
2223 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2224 DAG.getUNDEF(CarryVT));
2226 // canonicalize constant to RHS.
2227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2230 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2232 // fold (uaddo x, 0) -> x + no carry out
2233 if (isNullConstant(N1))
2234 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2236 // If it cannot overflow, transform into an add.
2237 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2238 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2239 DAG.getConstant(0, DL, CarryVT));
2241 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2244 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2250 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2251 auto VT = N0.getValueType();
2253 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2254 // If Y + 1 cannot overflow.
2255 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2256 SDValue Y = N1.getOperand(0);
2257 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2258 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2259 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2263 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2264 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2265 if (SDValue Carry = getAsCarry(TLI, N1))
2266 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2267 DAG.getConstant(0, SDLoc(N), VT), Carry);
2272 SDValue DAGCombiner::visitADDE(SDNode *N) {
2273 SDValue N0 = N->getOperand(0);
2274 SDValue N1 = N->getOperand(1);
2275 SDValue CarryIn = N->getOperand(2);
2277 // canonicalize constant to RHS
2278 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2281 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2284 // fold (adde x, y, false) -> (addc x, y)
2285 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2286 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2291 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2292 SDValue N0 = N->getOperand(0);
2293 SDValue N1 = N->getOperand(1);
2294 SDValue CarryIn = N->getOperand(2);
2297 // canonicalize constant to RHS
2298 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2299 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2303 // fold (addcarry x, y, false) -> (uaddo x, y)
2304 if (isNullConstant(CarryIn))
2305 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2307 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2308 if (isNullConstant(N0) && isNullConstant(N1)) {
2309 EVT VT = N0.getValueType();
2310 EVT CarryVT = CarryIn.getValueType();
2311 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2312 AddToWorklist(CarryExt.getNode());
2313 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2314 DAG.getConstant(1, DL, VT)),
2315 DAG.getConstant(0, DL, CarryVT));
2318 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2321 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2327 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2329 // Iff the flag result is dead:
2330 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2331 if ((N0.getOpcode() == ISD::ADD ||
2332 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2333 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2334 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2335 N0.getOperand(0), N0.getOperand(1), CarryIn);
2338 * When one of the addcarry argument is itself a carry, we may be facing
2339 * a diamond carry propagation. In which case we try to transform the DAG
2340 * to ensure linear carry propagation if that is possible.
2342 * We are trying to get:
2343 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2345 if (auto Y = getAsCarry(TLI, N1)) {
2351 * | (addcarry *, 0, Z)
2355 * (addcarry X, *, *)
2357 if (Y.getOpcode() == ISD::UADDO &&
2358 CarryIn.getResNo() == 1 &&
2359 CarryIn.getOpcode() == ISD::ADDCARRY &&
2360 isNullConstant(CarryIn.getOperand(1)) &&
2361 CarryIn.getOperand(0) == Y.getValue(0)) {
2362 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2363 Y.getOperand(0), Y.getOperand(1),
2364 CarryIn.getOperand(2));
2365 AddToWorklist(NewY.getNode());
2366 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2367 DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2375 // Since it may not be valid to emit a fold to zero for vector initializers
2376 // check if we can before folding.
2377 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2378 SelectionDAG &DAG, bool LegalOperations,
2381 return DAG.getConstant(0, DL, VT);
2382 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2383 return DAG.getConstant(0, DL, VT);
2387 SDValue DAGCombiner::visitSUB(SDNode *N) {
2388 SDValue N0 = N->getOperand(0);
2389 SDValue N1 = N->getOperand(1);
2390 EVT VT = N0.getValueType();
2394 if (VT.isVector()) {
2395 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2398 // fold (sub x, 0) -> x, vector edition
2399 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2403 // fold (sub x, x) -> 0
2404 // FIXME: Refactor this and xor and other similar operations together.
2406 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2407 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2408 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2409 // fold (sub c1, c2) -> c1-c2
2410 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2414 if (SDValue NewSel = foldBinOpIntoSelect(N))
2417 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2419 // fold (sub x, c) -> (add x, -c)
2421 return DAG.getNode(ISD::ADD, DL, VT, N0,
2422 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2425 if (isNullConstantOrNullSplatConstant(N0)) {
2426 unsigned BitWidth = VT.getScalarSizeInBits();
2427 // Right-shifting everything out but the sign bit followed by negation is
2428 // the same as flipping arithmetic/logical shift type without the negation:
2429 // -(X >>u 31) -> (X >>s 31)
2430 // -(X >>s 31) -> (X >>u 31)
2431 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2432 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2433 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2434 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2435 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2436 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2440 // 0 - X --> 0 if the sub is NUW.
2441 if (N->getFlags().hasNoUnsignedWrap())
2444 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2445 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2446 // N1 must be 0 because negating the minimum signed value is undefined.
2447 if (N->getFlags().hasNoSignedWrap())
2450 // 0 - X --> X if X is 0 or the minimum signed value.
2455 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2456 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2457 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2459 // fold A-(A-B) -> B
2460 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2461 return N1.getOperand(1);
2463 // fold (A+B)-A -> B
2464 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2465 return N0.getOperand(1);
2467 // fold (A+B)-B -> A
2468 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2469 return N0.getOperand(0);
2471 // fold C2-(A+C1) -> (C2-C1)-A
2472 if (N1.getOpcode() == ISD::ADD) {
2473 SDValue N11 = N1.getOperand(1);
2474 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2475 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2476 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2477 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2481 // fold ((A+(B+or-C))-B) -> A+or-C
2482 if (N0.getOpcode() == ISD::ADD &&
2483 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2484 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2485 N0.getOperand(1).getOperand(0) == N1)
2486 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2487 N0.getOperand(1).getOperand(1));
2489 // fold ((A+(C+B))-B) -> A+C
2490 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2491 N0.getOperand(1).getOperand(1) == N1)
2492 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2493 N0.getOperand(1).getOperand(0));
2495 // fold ((A-(B-C))-C) -> A-B
2496 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2497 N0.getOperand(1).getOperand(1) == N1)
2498 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2499 N0.getOperand(1).getOperand(0));
2501 // If either operand of a sub is undef, the result is undef
2507 // If the relocation model supports it, consider symbol offsets.
2508 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2509 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2510 // fold (sub Sym, c) -> Sym-c
2511 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2512 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2514 (uint64_t)N1C->getSExtValue());
2515 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2516 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2517 if (GA->getGlobal() == GB->getGlobal())
2518 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2522 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2523 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2524 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2525 if (TN->getVT() == MVT::i1) {
2526 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2527 DAG.getConstant(1, DL, VT));
2528 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2535 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2536 SDValue N0 = N->getOperand(0);
2537 SDValue N1 = N->getOperand(1);
2538 EVT VT = N0.getValueType();
2541 // If the flag result is dead, turn this into an SUB.
2542 if (!N->hasAnyUseOfValue(1))
2543 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2544 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2546 // fold (subc x, x) -> 0 + no borrow
2548 return CombineTo(N, DAG.getConstant(0, DL, VT),
2549 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2551 // fold (subc x, 0) -> x + no borrow
2552 if (isNullConstant(N1))
2553 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2555 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2556 if (isAllOnesConstant(N0))
2557 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2558 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2563 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2564 SDValue N0 = N->getOperand(0);
2565 SDValue N1 = N->getOperand(1);
2566 EVT VT = N0.getValueType();
2570 EVT CarryVT = N->getValueType(1);
2573 // If the flag result is dead, turn this into an SUB.
2574 if (!N->hasAnyUseOfValue(1))
2575 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2576 DAG.getUNDEF(CarryVT));
2578 // fold (usubo x, x) -> 0 + no borrow
2580 return CombineTo(N, DAG.getConstant(0, DL, VT),
2581 DAG.getConstant(0, DL, CarryVT));
2583 // fold (usubo x, 0) -> x + no borrow
2584 if (isNullConstant(N1))
2585 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2587 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2588 if (isAllOnesConstant(N0))
2589 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2590 DAG.getConstant(0, DL, CarryVT));
2595 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2596 SDValue N0 = N->getOperand(0);
2597 SDValue N1 = N->getOperand(1);
2598 SDValue CarryIn = N->getOperand(2);
2600 // fold (sube x, y, false) -> (subc x, y)
2601 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2602 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2607 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2608 SDValue N0 = N->getOperand(0);
2609 SDValue N1 = N->getOperand(1);
2610 SDValue CarryIn = N->getOperand(2);
2612 // fold (subcarry x, y, false) -> (usubo x, y)
2613 if (isNullConstant(CarryIn))
2614 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2619 SDValue DAGCombiner::visitMUL(SDNode *N) {
2620 SDValue N0 = N->getOperand(0);
2621 SDValue N1 = N->getOperand(1);
2622 EVT VT = N0.getValueType();
2624 // fold (mul x, undef) -> 0
2625 if (N0.isUndef() || N1.isUndef())
2626 return DAG.getConstant(0, SDLoc(N), VT);
2628 bool N0IsConst = false;
2629 bool N1IsConst = false;
2630 bool N1IsOpaqueConst = false;
2631 bool N0IsOpaqueConst = false;
2632 APInt ConstValue0, ConstValue1;
2634 if (VT.isVector()) {
2635 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2638 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2639 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2640 assert((!N0IsConst ||
2641 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2642 "Splat APInt should be element width");
2643 assert((!N1IsConst ||
2644 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2645 "Splat APInt should be element width");
2647 N0IsConst = isa<ConstantSDNode>(N0);
2649 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2650 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2652 N1IsConst = isa<ConstantSDNode>(N1);
2654 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2655 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2659 // fold (mul c1, c2) -> c1*c2
2660 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2661 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2662 N0.getNode(), N1.getNode());
2664 // canonicalize constant to RHS (vector doesn't have to splat)
2665 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2666 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2667 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2668 // fold (mul x, 0) -> 0
2669 if (N1IsConst && ConstValue1.isNullValue())
2671 // fold (mul x, 1) -> x
2672 if (N1IsConst && ConstValue1.isOneValue())
2675 if (SDValue NewSel = foldBinOpIntoSelect(N))
2678 // fold (mul x, -1) -> 0-x
2679 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2681 return DAG.getNode(ISD::SUB, DL, VT,
2682 DAG.getConstant(0, DL, VT), N0);
2684 // fold (mul x, (1 << c)) -> x << c
2685 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2686 DAG.isKnownToBeAPowerOfTwo(N1) &&
2687 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2689 SDValue LogBase2 = BuildLogBase2(N1, DL);
2690 AddToWorklist(LogBase2.getNode());
2692 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2693 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2694 AddToWorklist(Trunc.getNode());
2695 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2697 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2698 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2699 unsigned Log2Val = (-ConstValue1).logBase2();
2701 // FIXME: If the input is something that is easily negated (e.g. a
2702 // single-use add), we should put the negate there.
2703 return DAG.getNode(ISD::SUB, DL, VT,
2704 DAG.getConstant(0, DL, VT),
2705 DAG.getNode(ISD::SHL, DL, VT, N0,
2706 DAG.getConstant(Log2Val, DL,
2707 getShiftAmountTy(N0.getValueType()))));
2710 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2711 if (N0.getOpcode() == ISD::SHL &&
2712 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2713 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2714 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2715 if (isConstantOrConstantVector(C3))
2716 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2719 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2722 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2724 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2725 if (N0.getOpcode() == ISD::SHL &&
2726 isConstantOrConstantVector(N0.getOperand(1)) &&
2727 N0.getNode()->hasOneUse()) {
2729 } else if (N1.getOpcode() == ISD::SHL &&
2730 isConstantOrConstantVector(N1.getOperand(1)) &&
2731 N1.getNode()->hasOneUse()) {
2736 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2737 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2741 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2742 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2743 N0.getOpcode() == ISD::ADD &&
2744 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2745 isMulAddWithConstProfitable(N, N0, N1))
2746 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2747 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2748 N0.getOperand(0), N1),
2749 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2750 N0.getOperand(1), N1));
2753 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2759 /// Return true if divmod libcall is available.
2760 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2761 const TargetLowering &TLI) {
2763 EVT NodeType = Node->getValueType(0);
2764 if (!NodeType.isSimple())
2766 switch (NodeType.getSimpleVT().SimpleTy) {
2767 default: return false; // No libcall for vector types.
2768 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2769 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2770 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2771 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2772 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2775 return TLI.getLibcallName(LC) != nullptr;
2778 /// Issue divrem if both quotient and remainder are needed.
2779 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2780 if (Node->use_empty())
2781 return SDValue(); // This is a dead node, leave it alone.
2783 unsigned Opcode = Node->getOpcode();
2784 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2785 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2787 // DivMod lib calls can still work on non-legal types if using lib-calls.
2788 EVT VT = Node->getValueType(0);
2789 if (VT.isVector() || !VT.isInteger())
2792 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2795 // If DIVREM is going to get expanded into a libcall,
2796 // but there is no libcall available, then don't combine.
2797 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2798 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2801 // If div is legal, it's better to do the normal expansion
2802 unsigned OtherOpcode = 0;
2803 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2804 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2805 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2808 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2809 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2813 SDValue Op0 = Node->getOperand(0);
2814 SDValue Op1 = Node->getOperand(1);
2816 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2817 UE = Op0.getNode()->use_end(); UI != UE;) {
2818 SDNode *User = *UI++;
2819 if (User == Node || User->use_empty())
2821 // Convert the other matching node(s), too;
2822 // otherwise, the DIVREM may get target-legalized into something
2823 // target-specific that we won't be able to recognize.
2824 unsigned UserOpc = User->getOpcode();
2825 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2826 User->getOperand(0) == Op0 &&
2827 User->getOperand(1) == Op1) {
2829 if (UserOpc == OtherOpcode) {
2830 SDVTList VTs = DAG.getVTList(VT, VT);
2831 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2832 } else if (UserOpc == DivRemOpc) {
2833 combined = SDValue(User, 0);
2835 assert(UserOpc == Opcode);
2839 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2840 CombineTo(User, combined);
2841 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2842 CombineTo(User, combined.getValue(1));
2848 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2849 SDValue N0 = N->getOperand(0);
2850 SDValue N1 = N->getOperand(1);
2851 EVT VT = N->getValueType(0);
2854 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2855 return DAG.getUNDEF(VT);
2860 return DAG.getConstant(0, DL, VT);
2865 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2866 SDValue N0 = N->getOperand(0);
2867 SDValue N1 = N->getOperand(1);
2868 EVT VT = N->getValueType(0);
2872 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2877 // fold (sdiv c1, c2) -> c1/c2
2878 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2879 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2880 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2881 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2882 // fold (sdiv X, 1) -> X
2883 if (N1C && N1C->isOne())
2885 // fold (sdiv X, -1) -> 0-X
2886 if (N1C && N1C->isAllOnesValue())
2887 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2889 if (SDValue V = simplifyDivRem(N, DAG))
2892 if (SDValue NewSel = foldBinOpIntoSelect(N))
2895 // If we know the sign bits of both operands are zero, strength reduce to a
2896 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2897 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2898 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2900 // fold (sdiv X, pow2) -> simple ops after legalize
2901 // FIXME: We check for the exact bit here because the generic lowering gives
2902 // better results in that case. The target-specific lowering should learn how
2903 // to handle exact sdivs efficiently.
2904 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2905 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2906 (-N1C->getAPIntValue()).isPowerOf2())) {
2907 // Target-specific implementation of sdiv x, pow2.
2908 if (SDValue Res = BuildSDIVPow2(N))
2911 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2913 // Splat the sign bit into the register
2915 DAG.getNode(ISD::SRA, DL, VT, N0,
2916 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2917 getShiftAmountTy(N0.getValueType())));
2918 AddToWorklist(SGN.getNode());
2920 // Add (N0 < 0) ? abs2 - 1 : 0;
2922 DAG.getNode(ISD::SRL, DL, VT, SGN,
2923 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2924 getShiftAmountTy(SGN.getValueType())));
2925 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2926 AddToWorklist(SRL.getNode());
2927 AddToWorklist(ADD.getNode()); // Divide by pow2
2928 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2929 DAG.getConstant(lg2, DL,
2930 getShiftAmountTy(ADD.getValueType())));
2932 // If we're dividing by a positive value, we're done. Otherwise, we must
2933 // negate the result.
2934 if (N1C->getAPIntValue().isNonNegative())
2937 AddToWorklist(SRA.getNode());
2938 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2941 // If integer divide is expensive and we satisfy the requirements, emit an
2942 // alternate sequence. Targets may check function attributes for size/speed
2944 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2945 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2946 if (SDValue Op = BuildSDIV(N))
2949 // sdiv, srem -> sdivrem
2950 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2951 // true. Otherwise, we break the simplification logic in visitREM().
2952 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2953 if (SDValue DivRem = useDivRem(N))
2959 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2960 SDValue N0 = N->getOperand(0);
2961 SDValue N1 = N->getOperand(1);
2962 EVT VT = N->getValueType(0);
2966 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2971 // fold (udiv c1, c2) -> c1/c2
2972 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2973 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2975 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2979 if (SDValue V = simplifyDivRem(N, DAG))
2982 if (SDValue NewSel = foldBinOpIntoSelect(N))
2985 // fold (udiv x, (1 << c)) -> x >>u c
2986 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2987 DAG.isKnownToBeAPowerOfTwo(N1)) {
2988 SDValue LogBase2 = BuildLogBase2(N1, DL);
2989 AddToWorklist(LogBase2.getNode());
2991 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2992 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2993 AddToWorklist(Trunc.getNode());
2994 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2997 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2998 if (N1.getOpcode() == ISD::SHL) {
2999 SDValue N10 = N1.getOperand(0);
3000 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3001 DAG.isKnownToBeAPowerOfTwo(N10)) {
3002 SDValue LogBase2 = BuildLogBase2(N10, DL);
3003 AddToWorklist(LogBase2.getNode());
3005 EVT ADDVT = N1.getOperand(1).getValueType();
3006 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3007 AddToWorklist(Trunc.getNode());
3008 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3009 AddToWorklist(Add.getNode());
3010 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3014 // fold (udiv x, c) -> alternate
3015 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3016 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3017 if (SDValue Op = BuildUDIV(N))
3020 // sdiv, srem -> sdivrem
3021 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3022 // true. Otherwise, we break the simplification logic in visitREM().
3023 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3024 if (SDValue DivRem = useDivRem(N))
3030 // handles ISD::SREM and ISD::UREM
3031 SDValue DAGCombiner::visitREM(SDNode *N) {
3032 unsigned Opcode = N->getOpcode();
3033 SDValue N0 = N->getOperand(0);
3034 SDValue N1 = N->getOperand(1);
3035 EVT VT = N->getValueType(0);
3036 bool isSigned = (Opcode == ISD::SREM);
3039 // fold (rem c1, c2) -> c1%c2
3040 ConstantSDNode *N0C = isConstOrConstSplat(N0);
3041 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3043 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3046 if (SDValue V = simplifyDivRem(N, DAG))
3049 if (SDValue NewSel = foldBinOpIntoSelect(N))
3053 // If we know the sign bits of both operands are zero, strength reduce to a
3054 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3055 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3056 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3058 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3059 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3060 // fold (urem x, pow2) -> (and x, pow2-1)
3061 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3062 AddToWorklist(Add.getNode());
3063 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3065 if (N1.getOpcode() == ISD::SHL &&
3066 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3067 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3068 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3069 AddToWorklist(Add.getNode());
3070 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3074 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3076 // If X/C can be simplified by the division-by-constant logic, lower
3077 // X%C to the equivalent of X-X/C*C.
3078 // To avoid mangling nodes, this simplification requires that the combine()
3079 // call for the speculative DIV must not cause a DIVREM conversion. We guard
3080 // against this by skipping the simplification if isIntDivCheap(). When
3081 // div is not cheap, combine will not return a DIVREM. Regardless,
3082 // checking cheapness here makes sense since the simplification results in
3084 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3085 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3086 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3087 AddToWorklist(Div.getNode());
3088 SDValue OptimizedDiv = combine(Div.getNode());
3089 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3090 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3091 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3092 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3093 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3094 AddToWorklist(Mul.getNode());
3099 // sdiv, srem -> sdivrem
3100 if (SDValue DivRem = useDivRem(N))
3101 return DivRem.getValue(1);
3106 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3107 SDValue N0 = N->getOperand(0);
3108 SDValue N1 = N->getOperand(1);
3109 EVT VT = N->getValueType(0);
3112 if (VT.isVector()) {
3113 // fold (mulhs x, 0) -> 0
3114 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3116 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3120 // fold (mulhs x, 0) -> 0
3121 if (isNullConstant(N1))
3123 // fold (mulhs x, 1) -> (sra x, size(x)-1)
3124 if (isOneConstant(N1))
3125 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3126 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3127 getShiftAmountTy(N0.getValueType())));
3129 // fold (mulhs x, undef) -> 0
3130 if (N0.isUndef() || N1.isUndef())
3131 return DAG.getConstant(0, DL, VT);
3133 // If the type twice as wide is legal, transform the mulhs to a wider multiply
3135 if (VT.isSimple() && !VT.isVector()) {
3136 MVT Simple = VT.getSimpleVT();
3137 unsigned SimpleSize = Simple.getSizeInBits();
3138 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3139 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3140 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3141 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3142 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3143 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3144 DAG.getConstant(SimpleSize, DL,
3145 getShiftAmountTy(N1.getValueType())));
3146 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3153 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3154 SDValue N0 = N->getOperand(0);
3155 SDValue N1 = N->getOperand(1);
3156 EVT VT = N->getValueType(0);
3159 if (VT.isVector()) {
3160 // fold (mulhu x, 0) -> 0
3161 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3163 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3167 // fold (mulhu x, 0) -> 0
3168 if (isNullConstant(N1))
3170 // fold (mulhu x, 1) -> 0
3171 if (isOneConstant(N1))
3172 return DAG.getConstant(0, DL, N0.getValueType());
3173 // fold (mulhu x, undef) -> 0
3174 if (N0.isUndef() || N1.isUndef())
3175 return DAG.getConstant(0, DL, VT);
3177 // If the type twice as wide is legal, transform the mulhu to a wider multiply
3179 if (VT.isSimple() && !VT.isVector()) {
3180 MVT Simple = VT.getSimpleVT();
3181 unsigned SimpleSize = Simple.getSizeInBits();
3182 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3183 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3184 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3185 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3186 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3187 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3188 DAG.getConstant(SimpleSize, DL,
3189 getShiftAmountTy(N1.getValueType())));
3190 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3197 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3198 /// give the opcodes for the two computations that are being performed. Return
3199 /// true if a simplification was made.
3200 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3202 // If the high half is not needed, just compute the low half.
3203 bool HiExists = N->hasAnyUseOfValue(1);
3205 (!LegalOperations ||
3206 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3207 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3208 return CombineTo(N, Res, Res);
3211 // If the low half is not needed, just compute the high half.
3212 bool LoExists = N->hasAnyUseOfValue(0);
3214 (!LegalOperations ||
3215 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3216 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3217 return CombineTo(N, Res, Res);
3220 // If both halves are used, return as it is.
3221 if (LoExists && HiExists)
3224 // If the two computed results can be simplified separately, separate them.
3226 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3227 AddToWorklist(Lo.getNode());
3228 SDValue LoOpt = combine(Lo.getNode());
3229 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3230 (!LegalOperations ||
3231 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3232 return CombineTo(N, LoOpt, LoOpt);
3236 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3237 AddToWorklist(Hi.getNode());
3238 SDValue HiOpt = combine(Hi.getNode());
3239 if (HiOpt.getNode() && HiOpt != Hi &&
3240 (!LegalOperations ||
3241 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3242 return CombineTo(N, HiOpt, HiOpt);
3248 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3249 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3252 EVT VT = N->getValueType(0);
3255 // If the type is twice as wide is legal, transform the mulhu to a wider
3256 // multiply plus a shift.
3257 if (VT.isSimple() && !VT.isVector()) {
3258 MVT Simple = VT.getSimpleVT();
3259 unsigned SimpleSize = Simple.getSizeInBits();
3260 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3261 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3262 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3263 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3264 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3265 // Compute the high part as N1.
3266 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3267 DAG.getConstant(SimpleSize, DL,
3268 getShiftAmountTy(Lo.getValueType())));
3269 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3270 // Compute the low part as N0.
3271 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3272 return CombineTo(N, Lo, Hi);
3279 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3280 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3283 EVT VT = N->getValueType(0);
3286 // If the type is twice as wide is legal, transform the mulhu to a wider
3287 // multiply plus a shift.
3288 if (VT.isSimple() && !VT.isVector()) {
3289 MVT Simple = VT.getSimpleVT();
3290 unsigned SimpleSize = Simple.getSizeInBits();
3291 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3292 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3293 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3294 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3295 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3296 // Compute the high part as N1.
3297 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3298 DAG.getConstant(SimpleSize, DL,
3299 getShiftAmountTy(Lo.getValueType())));
3300 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3301 // Compute the low part as N0.
3302 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3303 return CombineTo(N, Lo, Hi);
3310 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3311 // (smulo x, 2) -> (saddo x, x)
3312 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3313 if (C2->getAPIntValue() == 2)
3314 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3315 N->getOperand(0), N->getOperand(0));
3320 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3321 // (umulo x, 2) -> (uaddo x, x)
3322 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3323 if (C2->getAPIntValue() == 2)
3324 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3325 N->getOperand(0), N->getOperand(0));
3330 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3331 SDValue N0 = N->getOperand(0);
3332 SDValue N1 = N->getOperand(1);
3333 EVT VT = N0.getValueType();
3337 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3340 // fold operation with constant operands.
3341 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3342 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3344 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3346 // canonicalize constant to RHS
3347 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3348 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3349 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3354 /// If this is a binary operator with two operands of the same opcode, try to
3356 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3357 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3358 EVT VT = N0.getValueType();
3359 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3361 // Bail early if none of these transforms apply.
3362 if (N0.getNumOperands() == 0) return SDValue();
3364 // For each of OP in AND/OR/XOR:
3365 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3366 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3367 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3368 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3369 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3371 // do not sink logical op inside of a vector extend, since it may combine
3373 EVT Op0VT = N0.getOperand(0).getValueType();
3374 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3375 N0.getOpcode() == ISD::SIGN_EXTEND ||
3376 N0.getOpcode() == ISD::BSWAP ||
3377 // Avoid infinite looping with PromoteIntBinOp.
3378 (N0.getOpcode() == ISD::ANY_EXTEND &&
3379 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3380 (N0.getOpcode() == ISD::TRUNCATE &&
3381 (!TLI.isZExtFree(VT, Op0VT) ||
3382 !TLI.isTruncateFree(Op0VT, VT)) &&
3383 TLI.isTypeLegal(Op0VT))) &&
3385 Op0VT == N1.getOperand(0).getValueType() &&
3386 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3387 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3388 N0.getOperand(0).getValueType(),
3389 N0.getOperand(0), N1.getOperand(0));
3390 AddToWorklist(ORNode.getNode());
3391 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3394 // For each of OP in SHL/SRL/SRA/AND...
3395 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3396 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3397 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3398 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3399 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3400 N0.getOperand(1) == N1.getOperand(1)) {
3401 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3402 N0.getOperand(0).getValueType(),
3403 N0.getOperand(0), N1.getOperand(0));
3404 AddToWorklist(ORNode.getNode());
3405 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3406 ORNode, N0.getOperand(1));
3409 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3410 // Only perform this optimization up until type legalization, before
3411 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3412 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3413 // we don't want to undo this promotion.
3414 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3416 if ((N0.getOpcode() == ISD::BITCAST ||
3417 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3418 Level <= AfterLegalizeTypes) {
3419 SDValue In0 = N0.getOperand(0);
3420 SDValue In1 = N1.getOperand(0);
3421 EVT In0Ty = In0.getValueType();
3422 EVT In1Ty = In1.getValueType();
3424 // If both incoming values are integers, and the original types are the
3426 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3427 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3428 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3429 AddToWorklist(Op.getNode());
3434 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3435 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3436 // If both shuffles use the same mask, and both shuffle within a single
3437 // vector, then it is worthwhile to move the swizzle after the operation.
3438 // The type-legalizer generates this pattern when loading illegal
3439 // vector types from memory. In many cases this allows additional shuffle
3441 // There are other cases where moving the shuffle after the xor/and/or
3442 // is profitable even if shuffles don't perform a swizzle.
3443 // If both shuffles use the same mask, and both shuffles have the same first
3444 // or second operand, then it might still be profitable to move the shuffle
3445 // after the xor/and/or operation.
3446 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3447 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3448 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3450 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3451 "Inputs to shuffles are not the same type");
3453 // Check that both shuffles use the same mask. The masks are known to be of
3454 // the same length because the result vector type is the same.
3455 // Check also that shuffles have only one use to avoid introducing extra
3457 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3458 SVN0->getMask().equals(SVN1->getMask())) {
3459 SDValue ShOp = N0->getOperand(1);
3461 // Don't try to fold this node if it requires introducing a
3462 // build vector of all zeros that might be illegal at this stage.
3463 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3465 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3470 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3471 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3472 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3473 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3474 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3475 N0->getOperand(0), N1->getOperand(0));
3476 AddToWorklist(NewNode.getNode());
3477 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3481 // Don't try to fold this node if it requires introducing a
3482 // build vector of all zeros that might be illegal at this stage.
3483 ShOp = N0->getOperand(0);
3484 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3486 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3491 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3492 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3493 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3494 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3495 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3496 N0->getOperand(1), N1->getOperand(1));
3497 AddToWorklist(NewNode.getNode());
3498 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3507 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3508 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3510 SDValue LL, LR, RL, RR, N0CC, N1CC;
3511 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3512 !isSetCCEquivalent(N1, RL, RR, N1CC))
3515 assert(N0.getValueType() == N1.getValueType() &&
3516 "Unexpected operand types for bitwise logic op");
3517 assert(LL.getValueType() == LR.getValueType() &&
3518 RL.getValueType() == RR.getValueType() &&
3519 "Unexpected operand types for setcc");
3521 // If we're here post-legalization or the logic op type is not i1, the logic
3522 // op type must match a setcc result type. Also, all folds require new
3523 // operations on the left and right operands, so those types must match.
3524 EVT VT = N0.getValueType();
3525 EVT OpVT = LL.getValueType();
3526 if (LegalOperations || VT != MVT::i1)
3527 if (VT != getSetCCResultType(OpVT))
3529 if (OpVT != RL.getValueType())
3532 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3533 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3534 bool IsInteger = OpVT.isInteger();
3535 if (LR == RR && CC0 == CC1 && IsInteger) {
3536 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3537 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3540 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3541 // All sign bits clear?
3542 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3544 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3545 // Any sign bits set?
3546 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3548 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3549 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3550 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3551 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3552 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3553 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3554 AddToWorklist(Or.getNode());
3555 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3559 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3560 // All sign bits set?
3561 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3563 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3564 // Any sign bits clear?
3565 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3567 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3568 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3569 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3570 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3571 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3572 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3573 AddToWorklist(And.getNode());
3574 return DAG.getSetCC(DL, VT, And, LR, CC1);
3578 // TODO: What is the 'or' equivalent of this fold?
3579 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3580 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3581 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3582 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3583 SDValue One = DAG.getConstant(1, DL, OpVT);
3584 SDValue Two = DAG.getConstant(2, DL, OpVT);
3585 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3586 AddToWorklist(Add.getNode());
3587 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3590 // Try more general transforms if the predicates match and the only user of
3591 // the compares is the 'and' or 'or'.
3592 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3593 N0.hasOneUse() && N1.hasOneUse()) {
3594 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3595 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3596 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3597 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3598 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3599 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3600 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3601 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3605 // Canonicalize equivalent operands to LL == RL.
3606 if (LL == RR && LR == RL) {
3607 CC1 = ISD::getSetCCSwappedOperands(CC1);
3611 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3612 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3613 if (LL == RL && LR == RR) {
3614 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3615 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3616 if (NewCC != ISD::SETCC_INVALID &&
3617 (!LegalOperations ||
3618 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3619 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3620 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3626 /// This contains all DAGCombine rules which reduce two values combined by
3627 /// an And operation to a single value. This makes them reusable in the context
3628 /// of visitSELECT(). Rules involving constants are not included as
3629 /// visitSELECT() already handles those cases.
3630 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3631 EVT VT = N1.getValueType();
3634 // fold (and x, undef) -> 0
3635 if (N0.isUndef() || N1.isUndef())
3636 return DAG.getConstant(0, DL, VT);
3638 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3641 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3642 VT.getSizeInBits() <= 64) {
3643 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3644 APInt ADDC = ADDI->getAPIntValue();
3645 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3646 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3647 // immediate for an add, but it is legal if its top c2 bits are set,
3648 // transform the ADD so the immediate doesn't need to be materialized
3650 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3651 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3652 SRLI->getZExtValue());
3653 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3655 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3658 DAG.getNode(ISD::ADD, DL0, VT,
3659 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3660 CombineTo(N0.getNode(), NewAdd);
3661 // Return N so it doesn't get rechecked!
3662 return SDValue(N, 0);
3670 // Reduce bit extract of low half of an integer to the narrower type.
3671 // (and (srl i64:x, K), KMask) ->
3672 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3673 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3674 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3675 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3676 unsigned Size = VT.getSizeInBits();
3677 const APInt &AndMask = CAnd->getAPIntValue();
3678 unsigned ShiftBits = CShift->getZExtValue();
3680 // Bail out, this node will probably disappear anyway.
3684 unsigned MaskBits = AndMask.countTrailingOnes();
3685 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3687 if (AndMask.isMask() &&
3688 // Required bits must not span the two halves of the integer and
3689 // must fit in the half size type.
3690 (ShiftBits + MaskBits <= Size / 2) &&
3691 TLI.isNarrowingProfitable(VT, HalfVT) &&
3692 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3693 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3694 TLI.isTruncateFree(VT, HalfVT) &&
3695 TLI.isZExtFree(HalfVT, VT)) {
3696 // The isNarrowingProfitable is to avoid regressions on PPC and
3697 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3698 // on downstream users of this. Those patterns could probably be
3699 // extended to handle extensions mixed in.
3702 assert(MaskBits <= Size);
3704 // Extracting the highest bit of the low half.
3705 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3706 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3709 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3710 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3711 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3712 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3713 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3722 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3723 EVT LoadResultTy, EVT &ExtVT) {
3724 if (!AndC->getAPIntValue().isMask())
3727 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3729 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3730 EVT LoadedVT = LoadN->getMemoryVT();
3732 if (ExtVT == LoadedVT &&
3733 (!LegalOperations ||
3734 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3735 // ZEXTLOAD will match without needing to change the size of the value being
3740 // Do not change the width of a volatile load.
3741 if (LoadN->isVolatile())
3744 // Do not generate loads of non-round integer types since these can
3745 // be expensive (and would be wrong if the type is not byte sized).
3746 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3749 if (LegalOperations &&
3750 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3753 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3759 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3760 EVT &ExtVT, unsigned ShAmt) {
3761 // Don't transform one with multiple uses, this would require adding a new
3763 if (!SDValue(LoadN, 0).hasOneUse())
3766 if (LegalOperations &&
3767 !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3770 // Do not generate loads of non-round integer types since these can
3771 // be expensive (and would be wrong if the type is not byte sized).
3772 if (!ExtVT.isRound())
3775 // Don't change the width of a volatile load.
3776 if (LoadN->isVolatile())
3779 // Verify that we are actually reducing a load width here.
3780 if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3783 // For the transform to be legal, the load must produce only two values
3784 // (the value loaded and the chain). Don't transform a pre-increment
3785 // load, for example, which produces an extra value. Otherwise the
3786 // transformation is not equivalent, and the downstream logic to replace
3787 // uses gets things wrong.
3788 if (LoadN->getNumValues() > 2)
3791 // If the load that we're shrinking is an extload and we're not just
3792 // discarding the extension we can't simply shrink the load. Bail.
3793 // TODO: It would be possible to merge the extensions in some cases.
3794 if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3795 LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3798 if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3801 // It's not possible to generate a constant of extended or untyped type.
3802 EVT PtrType = LoadN->getOperand(1).getValueType();
3803 if (PtrType == MVT::Untyped || PtrType.isExtended())
3809 bool DAGCombiner::SearchForAndLoads(SDNode *N,
3810 SmallPtrSetImpl<LoadSDNode*> &Loads,
3811 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3812 ConstantSDNode *Mask,
3813 SDNode *&NodeToMask) {
3814 // Recursively search for the operands, looking for loads which can be
3816 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3817 SDValue Op = N->getOperand(i);
3819 if (Op.getValueType().isVector())
3822 // Some constants may need fixing up later if they are too large.
3823 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3824 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3825 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3826 NodesWithConsts.insert(N);
3830 if (!Op.hasOneUse())
3833 switch(Op.getOpcode()) {
3835 auto *Load = cast<LoadSDNode>(Op);
3837 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3838 isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3839 // Only add this load if we can make it more narrow.
3840 if (ExtVT.bitsLT(Load->getMemoryVT()))
3846 case ISD::ZERO_EXTEND:
3847 case ISD::ANY_EXTEND:
3848 case ISD::AssertZext: {
3849 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3850 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3851 EVT VT = Op.getOpcode() == ISD::AssertZext ?
3852 cast<VTSDNode>(Op.getOperand(1))->getVT() :
3853 Op.getOperand(0).getValueType();
3855 // We can accept extending nodes if the mask is wider or an equal
3856 // width to the original type.
3857 if (ExtVT.bitsGE(VT))
3864 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3870 // Allow one node which will masked along with any loads found.
3873 NodeToMask = Op.getNode();
3878 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3879 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3883 if (!Mask->getAPIntValue().isMask())
3886 // No need to do anything if the and directly uses a load.
3887 if (isa<LoadSDNode>(N->getOperand(0)))
3890 SmallPtrSet<LoadSDNode*, 8> Loads;
3891 SmallPtrSet<SDNode*, 2> NodesWithConsts;
3892 SDNode *FixupNode = nullptr;
3893 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3894 if (Loads.size() == 0)
3897 SDValue MaskOp = N->getOperand(1);
3899 // If it exists, fixup the single node we allow in the tree that needs
3902 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3903 FixupNode->getValueType(0),
3904 SDValue(FixupNode, 0), MaskOp);
3905 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3906 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3910 // Narrow any constants that need it.
3911 for (auto *LogicN : NodesWithConsts) {
3912 auto *C = cast<ConstantSDNode>(LogicN->getOperand(1));
3913 SDValue And = DAG.getNode(ISD::AND, SDLoc(C), C->getValueType(0),
3914 SDValue(C, 0), MaskOp);
3915 DAG.UpdateNodeOperands(LogicN, LogicN->getOperand(0), And);
3918 // Create narrow loads.
3919 for (auto *Load : Loads) {
3920 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3921 SDValue(Load, 0), MaskOp);
3922 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3923 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3924 SDValue NewLoad = ReduceLoadWidth(And.getNode());
3926 "Shouldn't be masking the load if it can't be narrowed");
3927 CombineTo(Load, NewLoad, NewLoad.getValue(1));
3929 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
3935 SDValue DAGCombiner::visitAND(SDNode *N) {
3936 SDValue N0 = N->getOperand(0);
3937 SDValue N1 = N->getOperand(1);
3938 EVT VT = N1.getValueType();
3945 if (VT.isVector()) {
3946 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3949 // fold (and x, 0) -> 0, vector edition
3950 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3951 // do not return N0, because undef node may exist in N0
3952 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3953 SDLoc(N), N0.getValueType());
3954 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3955 // do not return N1, because undef node may exist in N1
3956 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3957 SDLoc(N), N1.getValueType());
3959 // fold (and x, -1) -> x, vector edition
3960 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3962 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3966 // fold (and c1, c2) -> c1&c2
3967 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3968 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3969 if (N0C && N1C && !N1C->isOpaque())
3970 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3971 // canonicalize constant to RHS
3972 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3973 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3974 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3975 // fold (and x, -1) -> x
3976 if (isAllOnesConstant(N1))
3978 // if (and x, c) is known to be zero, return 0
3979 unsigned BitWidth = VT.getScalarSizeInBits();
3980 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3981 APInt::getAllOnesValue(BitWidth)))
3982 return DAG.getConstant(0, SDLoc(N), VT);
3984 if (SDValue NewSel = foldBinOpIntoSelect(N))
3988 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3990 // fold (and (or x, C), D) -> D if (C & D) == D
3991 if (N1C && N0.getOpcode() == ISD::OR)
3992 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3993 if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3995 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3996 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3997 SDValue N0Op0 = N0.getOperand(0);
3998 APInt Mask = ~N1C->getAPIntValue();
3999 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4000 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4001 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4002 N0.getValueType(), N0Op0);
4004 // Replace uses of the AND with uses of the Zero extend node.
4007 // We actually want to replace all uses of the any_extend with the
4008 // zero_extend, to avoid duplicating things. This will later cause this
4009 // AND to be folded.
4010 CombineTo(N0.getNode(), Zext);
4011 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4014 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4015 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4016 // already be zero by virtue of the width of the base type of the load.
4018 // the 'X' node here can either be nothing or an extract_vector_elt to catch
4020 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4021 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4022 N0.getOperand(0).getOpcode() == ISD::LOAD &&
4023 N0.getOperand(0).getResNo() == 0) ||
4024 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4025 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4026 N0 : N0.getOperand(0) );
4028 // Get the constant (if applicable) the zero'th operand is being ANDed with.
4029 // This can be a pure constant or a vector splat, in which case we treat the
4030 // vector as a scalar and use the splat value.
4031 APInt Constant = APInt::getNullValue(1);
4032 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4033 Constant = C->getAPIntValue();
4034 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4035 APInt SplatValue, SplatUndef;
4036 unsigned SplatBitSize;
4038 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4039 SplatBitSize, HasAnyUndefs);
4041 // Undef bits can contribute to a possible optimisation if set, so
4043 SplatValue |= SplatUndef;
4045 // The splat value may be something like "0x00FFFFFF", which means 0 for
4046 // the first vector value and FF for the rest, repeating. We need a mask
4047 // that will apply equally to all members of the vector, so AND all the
4048 // lanes of the constant together.
4049 EVT VT = Vector->getValueType(0);
4050 unsigned BitWidth = VT.getScalarSizeInBits();
4052 // If the splat value has been compressed to a bitlength lower
4053 // than the size of the vector lane, we need to re-expand it to
4055 if (BitWidth > SplatBitSize)
4056 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4057 SplatBitSize < BitWidth;
4058 SplatBitSize = SplatBitSize * 2)
4059 SplatValue |= SplatValue.shl(SplatBitSize);
4061 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4062 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4063 if (SplatBitSize % BitWidth == 0) {
4064 Constant = APInt::getAllOnesValue(BitWidth);
4065 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4066 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4071 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4072 // actually legal and isn't going to get expanded, else this is a false
4074 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4075 Load->getValueType(0),
4076 Load->getMemoryVT());
4078 // Resize the constant to the same size as the original memory access before
4079 // extension. If it is still the AllOnesValue then this AND is completely
4081 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4084 switch (Load->getExtensionType()) {
4085 default: B = false; break;
4086 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4088 case ISD::NON_EXTLOAD: B = true; break;
4091 if (B && Constant.isAllOnesValue()) {
4092 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4093 // preserve semantics once we get rid of the AND.
4094 SDValue NewLoad(Load, 0);
4096 // Fold the AND away. NewLoad may get replaced immediately.
4097 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4099 if (Load->getExtensionType() == ISD::EXTLOAD) {
4100 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4101 Load->getValueType(0), SDLoc(Load),
4102 Load->getChain(), Load->getBasePtr(),
4103 Load->getOffset(), Load->getMemoryVT(),
4104 Load->getMemOperand());
4105 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4106 if (Load->getNumValues() == 3) {
4107 // PRE/POST_INC loads have 3 values.
4108 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4109 NewLoad.getValue(2) };
4110 CombineTo(Load, To, 3, true);
4112 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4116 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4120 // fold (and (load x), 255) -> (zextload x, i8)
4121 // fold (and (extload x, i16), 255) -> (zextload x, i8)
4122 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4123 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4124 (N0.getOpcode() == ISD::ANY_EXTEND &&
4125 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4126 if (SDValue Res = ReduceLoadWidth(N)) {
4127 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4128 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4131 CombineTo(LN0, Res, Res.getValue(1));
4132 return SDValue(N, 0);
4136 if (Level >= AfterLegalizeTypes) {
4137 // Attempt to propagate the AND back up to the leaves which, if they're
4138 // loads, can be combined to narrow loads and the AND node can be removed.
4139 // Perform after legalization so that extend nodes will already be
4140 // combined into the loads.
4141 if (BackwardsPropagateMask(N, DAG)) {
4142 return SDValue(N, 0);
4146 if (SDValue Combined = visitANDLike(N0, N1, N))
4149 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
4150 if (N0.getOpcode() == N1.getOpcode())
4151 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4154 // Masking the negated extension of a boolean is just the zero-extended
4156 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4157 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4159 // Note: the SimplifyDemandedBits fold below can make an information-losing
4160 // transform, and then we have no way to find this better fold.
4161 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4162 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4163 SDValue SubRHS = N0.getOperand(1);
4164 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4165 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4167 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4168 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4169 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4173 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4174 // fold (and (sra)) -> (and (srl)) when possible.
4175 if (SimplifyDemandedBits(SDValue(N, 0)))
4176 return SDValue(N, 0);
4178 // fold (zext_inreg (extload x)) -> (zextload x)
4179 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4180 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4181 EVT MemVT = LN0->getMemoryVT();
4182 // If we zero all the possible extended bits, then we can turn this into
4183 // a zextload if we are running before legalize or the operation is legal.
4184 unsigned BitWidth = N1.getScalarValueSizeInBits();
4185 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4186 BitWidth - MemVT.getScalarSizeInBits())) &&
4187 ((!LegalOperations && !LN0->isVolatile()) ||
4188 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4189 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4190 LN0->getChain(), LN0->getBasePtr(),
4191 MemVT, LN0->getMemOperand());
4193 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4194 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4197 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4198 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4200 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4201 EVT MemVT = LN0->getMemoryVT();
4202 // If we zero all the possible extended bits, then we can turn this into
4203 // a zextload if we are running before legalize or the operation is legal.
4204 unsigned BitWidth = N1.getScalarValueSizeInBits();
4205 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4206 BitWidth - MemVT.getScalarSizeInBits())) &&
4207 ((!LegalOperations && !LN0->isVolatile()) ||
4208 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4209 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4210 LN0->getChain(), LN0->getBasePtr(),
4211 MemVT, LN0->getMemOperand());
4213 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4214 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4217 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4218 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4219 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4220 N0.getOperand(1), false))
4227 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4228 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4229 bool DemandHighBits) {
4230 if (!LegalOperations)
4233 EVT VT = N->getValueType(0);
4234 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4236 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4239 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4240 bool LookPassAnd0 = false;
4241 bool LookPassAnd1 = false;
4242 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4244 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4246 if (N0.getOpcode() == ISD::AND) {
4247 if (!N0.getNode()->hasOneUse())
4249 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4250 if (!N01C || N01C->getZExtValue() != 0xFF00)
4252 N0 = N0.getOperand(0);
4253 LookPassAnd0 = true;
4256 if (N1.getOpcode() == ISD::AND) {
4257 if (!N1.getNode()->hasOneUse())
4259 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4260 if (!N11C || N11C->getZExtValue() != 0xFF)
4262 N1 = N1.getOperand(0);
4263 LookPassAnd1 = true;
4266 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4268 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4270 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4273 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4274 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4277 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4280 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4281 SDValue N00 = N0->getOperand(0);
4282 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4283 if (!N00.getNode()->hasOneUse())
4285 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4286 if (!N001C || N001C->getZExtValue() != 0xFF)
4288 N00 = N00.getOperand(0);
4289 LookPassAnd0 = true;
4292 SDValue N10 = N1->getOperand(0);
4293 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4294 if (!N10.getNode()->hasOneUse())
4296 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4297 if (!N101C || N101C->getZExtValue() != 0xFF00)
4299 N10 = N10.getOperand(0);
4300 LookPassAnd1 = true;
4306 // Make sure everything beyond the low halfword gets set to zero since the SRL
4307 // 16 will clear the top bits.
4308 unsigned OpSizeInBits = VT.getSizeInBits();
4309 if (DemandHighBits && OpSizeInBits > 16) {
4310 // If the left-shift isn't masked out then the only way this is a bswap is
4311 // if all bits beyond the low 8 are 0. In that case the entire pattern
4312 // reduces to a left shift anyway: leave it for other parts of the combiner.
4316 // However, if the right shift isn't masked out then it might be because
4317 // it's not needed. See if we can spot that too.
4318 if (!LookPassAnd1 &&
4319 !DAG.MaskedValueIsZero(
4320 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4324 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4325 if (OpSizeInBits > 16) {
4327 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4328 DAG.getConstant(OpSizeInBits - 16, DL,
4329 getShiftAmountTy(VT)));
4334 /// Return true if the specified node is an element that makes up a 32-bit
4335 /// packed halfword byteswap.
4336 /// ((x & 0x000000ff) << 8) |
4337 /// ((x & 0x0000ff00) >> 8) |
4338 /// ((x & 0x00ff0000) << 8) |
4339 /// ((x & 0xff000000) >> 8)
4340 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4341 if (!N.getNode()->hasOneUse())
4344 unsigned Opc = N.getOpcode();
4345 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4348 SDValue N0 = N.getOperand(0);
4349 unsigned Opc0 = N0.getOpcode();
4350 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4353 ConstantSDNode *N1C = nullptr;
4354 // SHL or SRL: look upstream for AND mask operand
4355 if (Opc == ISD::AND)
4356 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4357 else if (Opc0 == ISD::AND)
4358 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4362 unsigned MaskByteOffset;
4363 switch (N1C->getZExtValue()) {
4366 case 0xFF: MaskByteOffset = 0; break;
4367 case 0xFF00: MaskByteOffset = 1; break;
4368 case 0xFF0000: MaskByteOffset = 2; break;
4369 case 0xFF000000: MaskByteOffset = 3; break;
4372 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4373 if (Opc == ISD::AND) {
4374 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4376 // (x >> 8) & 0xff0000
4377 if (Opc0 != ISD::SRL)
4379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4380 if (!C || C->getZExtValue() != 8)
4383 // (x << 8) & 0xff00
4384 // (x << 8) & 0xff000000
4385 if (Opc0 != ISD::SHL)
4387 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4388 if (!C || C->getZExtValue() != 8)
4391 } else if (Opc == ISD::SHL) {
4393 // (x & 0xff0000) << 8
4394 if (MaskByteOffset != 0 && MaskByteOffset != 2)
4396 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4397 if (!C || C->getZExtValue() != 8)
4399 } else { // Opc == ISD::SRL
4400 // (x & 0xff00) >> 8
4401 // (x & 0xff000000) >> 8
4402 if (MaskByteOffset != 1 && MaskByteOffset != 3)
4404 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4405 if (!C || C->getZExtValue() != 8)
4409 if (Parts[MaskByteOffset])
4412 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4416 /// Match a 32-bit packed halfword bswap. That is
4417 /// ((x & 0x000000ff) << 8) |
4418 /// ((x & 0x0000ff00) >> 8) |
4419 /// ((x & 0x00ff0000) << 8) |
4420 /// ((x & 0xff000000) >> 8)
4421 /// => (rotl (bswap x), 16)
4422 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4423 if (!LegalOperations)
4426 EVT VT = N->getValueType(0);
4429 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4433 // (or (or (and), (and)), (or (and), (and)))
4434 // (or (or (or (and), (and)), (and)), (and))
4435 if (N0.getOpcode() != ISD::OR)
4437 SDValue N00 = N0.getOperand(0);
4438 SDValue N01 = N0.getOperand(1);
4439 SDNode *Parts[4] = {};
4441 if (N1.getOpcode() == ISD::OR &&
4442 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4443 // (or (or (and), (and)), (or (and), (and)))
4444 if (!isBSwapHWordElement(N00, Parts))
4447 if (!isBSwapHWordElement(N01, Parts))
4449 SDValue N10 = N1.getOperand(0);
4450 if (!isBSwapHWordElement(N10, Parts))
4452 SDValue N11 = N1.getOperand(1);
4453 if (!isBSwapHWordElement(N11, Parts))
4456 // (or (or (or (and), (and)), (and)), (and))
4457 if (!isBSwapHWordElement(N1, Parts))
4459 if (!isBSwapHWordElement(N01, Parts))
4461 if (N00.getOpcode() != ISD::OR)
4463 SDValue N000 = N00.getOperand(0);
4464 if (!isBSwapHWordElement(N000, Parts))
4466 SDValue N001 = N00.getOperand(1);
4467 if (!isBSwapHWordElement(N001, Parts))
4471 // Make sure the parts are all coming from the same node.
4472 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4476 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4477 SDValue(Parts[0], 0));
4479 // Result of the bswap should be rotated by 16. If it's not legal, then
4480 // do (x << 16) | (x >> 16).
4481 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4482 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4483 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4484 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4485 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4486 return DAG.getNode(ISD::OR, DL, VT,
4487 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4488 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4491 /// This contains all DAGCombine rules which reduce two values combined by
4492 /// an Or operation to a single value \see visitANDLike().
4493 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4494 EVT VT = N1.getValueType();
4497 // fold (or x, undef) -> -1
4498 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4499 return DAG.getAllOnesConstant(DL, VT);
4501 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4504 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4505 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4506 // Don't increase # computations.
4507 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4508 // We can only do this xform if we know that bits from X that are set in C2
4509 // but not in C1 are already zero. Likewise for Y.
4510 if (const ConstantSDNode *N0O1C =
4511 getAsNonOpaqueConstant(N0.getOperand(1))) {
4512 if (const ConstantSDNode *N1O1C =
4513 getAsNonOpaqueConstant(N1.getOperand(1))) {
4514 // We can only do this xform if we know that bits from X that are set in
4515 // C2 but not in C1 are already zero. Likewise for Y.
4516 const APInt &LHSMask = N0O1C->getAPIntValue();
4517 const APInt &RHSMask = N1O1C->getAPIntValue();
4519 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4520 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4521 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4522 N0.getOperand(0), N1.getOperand(0));
4523 return DAG.getNode(ISD::AND, DL, VT, X,
4524 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4530 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4531 if (N0.getOpcode() == ISD::AND &&
4532 N1.getOpcode() == ISD::AND &&
4533 N0.getOperand(0) == N1.getOperand(0) &&
4534 // Don't increase # computations.
4535 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4536 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4537 N0.getOperand(1), N1.getOperand(1));
4538 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4544 SDValue DAGCombiner::visitOR(SDNode *N) {
4545 SDValue N0 = N->getOperand(0);
4546 SDValue N1 = N->getOperand(1);
4547 EVT VT = N1.getValueType();
4554 if (VT.isVector()) {
4555 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4558 // fold (or x, 0) -> x, vector edition
4559 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4561 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4564 // fold (or x, -1) -> -1, vector edition
4565 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4566 // do not return N0, because undef node may exist in N0
4567 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4568 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4569 // do not return N1, because undef node may exist in N1
4570 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4572 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4573 // Do this only if the resulting shuffle is legal.
4574 if (isa<ShuffleVectorSDNode>(N0) &&
4575 isa<ShuffleVectorSDNode>(N1) &&
4576 // Avoid folding a node with illegal type.
4577 TLI.isTypeLegal(VT)) {
4578 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4579 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4580 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4581 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4582 // Ensure both shuffles have a zero input.
4583 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4584 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4585 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4586 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4587 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4588 bool CanFold = true;
4589 int NumElts = VT.getVectorNumElements();
4590 SmallVector<int, 4> Mask(NumElts);
4592 for (int i = 0; i != NumElts; ++i) {
4593 int M0 = SV0->getMaskElt(i);
4594 int M1 = SV1->getMaskElt(i);
4596 // Determine if either index is pointing to a zero vector.
4597 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4598 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4600 // If one element is zero and the otherside is undef, keep undef.
4601 // This also handles the case that both are undef.
4602 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4607 // Make sure only one of the elements is zero.
4608 if (M0Zero == M1Zero) {
4613 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4615 // We have a zero and non-zero element. If the non-zero came from
4616 // SV0 make the index a LHS index. If it came from SV1, make it
4617 // a RHS index. We need to mod by NumElts because we don't care
4618 // which operand it came from in the original shuffles.
4619 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4623 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4624 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4626 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4628 std::swap(NewLHS, NewRHS);
4629 ShuffleVectorSDNode::commuteMask(Mask);
4630 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4634 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4640 // fold (or c1, c2) -> c1|c2
4641 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4643 if (N0C && N1C && !N1C->isOpaque())
4644 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4645 // canonicalize constant to RHS
4646 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4647 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4648 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4649 // fold (or x, 0) -> x
4650 if (isNullConstant(N1))
4652 // fold (or x, -1) -> -1
4653 if (isAllOnesConstant(N1))
4656 if (SDValue NewSel = foldBinOpIntoSelect(N))
4659 // fold (or x, c) -> c iff (x & ~c) == 0
4660 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4663 if (SDValue Combined = visitORLike(N0, N1, N))
4666 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4667 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4669 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4673 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4676 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4677 // iff (c1 & c2) != 0.
4678 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4679 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4680 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4682 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4684 ISD::AND, SDLoc(N), VT,
4685 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4691 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4692 if (N0.getOpcode() == N1.getOpcode())
4693 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4696 // See if this is some rotate idiom.
4697 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4698 return SDValue(Rot, 0);
4700 if (SDValue Load = MatchLoadCombine(N))
4703 // Simplify the operands using demanded-bits information.
4704 if (SimplifyDemandedBits(SDValue(N, 0)))
4705 return SDValue(N, 0);
4710 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4711 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4712 if (Op.getOpcode() == ISD::AND) {
4713 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4714 Mask = Op.getOperand(1);
4715 Op = Op.getOperand(0);
4721 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4729 // Return true if we can prove that, whenever Neg and Pos are both in the
4730 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4731 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4733 // (or (shift1 X, Neg), (shift2 X, Pos))
4735 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4736 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4737 // to consider shift amounts with defined behavior.
4738 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4739 // If EltSize is a power of 2 then:
4741 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4742 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4744 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4745 // for the stronger condition:
4747 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4749 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4750 // we can just replace Neg with Neg' for the rest of the function.
4752 // In other cases we check for the even stronger condition:
4754 // Neg == EltSize - Pos [B]
4756 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4757 // behavior if Pos == 0 (and consequently Neg == EltSize).
4759 // We could actually use [A] whenever EltSize is a power of 2, but the
4760 // only extra cases that it would match are those uninteresting ones
4761 // where Neg and Pos are never in range at the same time. E.g. for
4762 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4763 // as well as (sub 32, Pos), but:
4765 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4767 // always invokes undefined behavior for 32-bit X.
4769 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4770 unsigned MaskLoBits = 0;
4771 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4772 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4773 if (NegC->getAPIntValue() == EltSize - 1) {
4774 Neg = Neg.getOperand(0);
4775 MaskLoBits = Log2_64(EltSize);
4780 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4781 if (Neg.getOpcode() != ISD::SUB)
4783 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4786 SDValue NegOp1 = Neg.getOperand(1);
4788 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4789 // Pos'. The truncation is redundant for the purpose of the equality.
4790 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4791 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4792 if (PosC->getAPIntValue() == EltSize - 1)
4793 Pos = Pos.getOperand(0);
4795 // The condition we need is now:
4797 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4799 // If NegOp1 == Pos then we need:
4801 // EltSize & Mask == NegC & Mask
4803 // (because "x & Mask" is a truncation and distributes through subtraction).
4806 Width = NegC->getAPIntValue();
4808 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4809 // Then the condition we want to prove becomes:
4811 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4813 // which, again because "x & Mask" is a truncation, becomes:
4815 // NegC & Mask == (EltSize - PosC) & Mask
4816 // EltSize & Mask == (NegC + PosC) & Mask
4817 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4818 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4819 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4825 // Now we just need to check that EltSize & Mask == Width & Mask.
4827 // EltSize & Mask is 0 since Mask is EltSize - 1.
4828 return Width.getLoBits(MaskLoBits) == 0;
4829 return Width == EltSize;
4832 // A subroutine of MatchRotate used once we have found an OR of two opposite
4833 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4834 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4835 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4836 // Neg with outer conversions stripped away.
4837 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4838 SDValue Neg, SDValue InnerPos,
4839 SDValue InnerNeg, unsigned PosOpcode,
4840 unsigned NegOpcode, const SDLoc &DL) {
4841 // fold (or (shl x, (*ext y)),
4842 // (srl x, (*ext (sub 32, y)))) ->
4843 // (rotl x, y) or (rotr x, (sub 32, y))
4845 // fold (or (shl x, (*ext (sub 32, y))),
4846 // (srl x, (*ext y))) ->
4847 // (rotr x, y) or (rotl x, (sub 32, y))
4848 EVT VT = Shifted.getValueType();
4849 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4850 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4851 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4852 HasPos ? Pos : Neg).getNode();
4858 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4859 // idioms for rotate, and if the target supports rotation instructions, generate
4861 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4862 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4863 EVT VT = LHS.getValueType();
4864 if (!TLI.isTypeLegal(VT)) return nullptr;
4866 // The target must have at least one rotate flavor.
4867 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4868 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4869 if (!HasROTL && !HasROTR) return nullptr;
4871 // Check for truncated rotate.
4872 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4873 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4874 assert(LHS.getValueType() == RHS.getValueType());
4875 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4876 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4877 SDValue(Rot, 0)).getNode();
4881 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4882 SDValue LHSShift; // The shift.
4883 SDValue LHSMask; // AND value if any.
4884 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4885 return nullptr; // Not part of a rotate.
4887 SDValue RHSShift; // The shift.
4888 SDValue RHSMask; // AND value if any.
4889 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4890 return nullptr; // Not part of a rotate.
4892 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4893 return nullptr; // Not shifting the same value.
4895 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4896 return nullptr; // Shifts must disagree.
4898 // Canonicalize shl to left side in a shl/srl pair.
4899 if (RHSShift.getOpcode() == ISD::SHL) {
4900 std::swap(LHS, RHS);
4901 std::swap(LHSShift, RHSShift);
4902 std::swap(LHSMask, RHSMask);
4905 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4906 SDValue LHSShiftArg = LHSShift.getOperand(0);
4907 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4908 SDValue RHSShiftArg = RHSShift.getOperand(0);
4909 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4911 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4912 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4913 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4914 ConstantSDNode *RHS) {
4915 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4917 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4918 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4919 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4921 // If there is an AND of either shifted operand, apply it to the result.
4922 if (LHSMask.getNode() || RHSMask.getNode()) {
4923 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4924 SDValue Mask = AllOnes;
4926 if (LHSMask.getNode()) {
4927 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4928 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4929 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4931 if (RHSMask.getNode()) {
4932 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4933 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4934 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4937 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4940 return Rot.getNode();
4943 // If there is a mask here, and we have a variable shift, we can't be sure
4944 // that we're masking out the right stuff.
4945 if (LHSMask.getNode() || RHSMask.getNode())
4948 // If the shift amount is sign/zext/any-extended just peel it off.
4949 SDValue LExtOp0 = LHSShiftAmt;
4950 SDValue RExtOp0 = RHSShiftAmt;
4951 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4952 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4953 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4954 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4955 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4956 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4957 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4958 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4959 LExtOp0 = LHSShiftAmt.getOperand(0);
4960 RExtOp0 = RHSShiftAmt.getOperand(0);
4963 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4964 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4968 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4969 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4978 /// Represents known origin of an individual byte in load combine pattern. The
4979 /// value of the byte is either constant zero or comes from memory.
4980 struct ByteProvider {
4981 // For constant zero providers Load is set to nullptr. For memory providers
4982 // Load represents the node which loads the byte from memory.
4983 // ByteOffset is the offset of the byte in the value produced by the load.
4984 LoadSDNode *Load = nullptr;
4985 unsigned ByteOffset = 0;
4987 ByteProvider() = default;
4989 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4990 return ByteProvider(Load, ByteOffset);
4993 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4995 bool isConstantZero() const { return !Load; }
4996 bool isMemory() const { return Load; }
4998 bool operator==(const ByteProvider &Other) const {
4999 return Other.Load == Load && Other.ByteOffset == ByteOffset;
5003 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5004 : Load(Load), ByteOffset(ByteOffset) {}
5007 } // end anonymous namespace
5009 /// Recursively traverses the expression calculating the origin of the requested
5010 /// byte of the given value. Returns None if the provider can't be calculated.
5012 /// For all the values except the root of the expression verifies that the value
5013 /// has exactly one use and if it's not true return None. This way if the origin
5014 /// of the byte is returned it's guaranteed that the values which contribute to
5015 /// the byte are not used outside of this expression.
5017 /// Because the parts of the expression are not allowed to have more than one
5018 /// use this function iterates over trees, not DAGs. So it never visits the same
5019 /// node more than once.
5020 static const Optional<ByteProvider>
5021 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5022 bool Root = false) {
5023 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5027 if (!Root && !Op.hasOneUse())
5030 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5031 unsigned BitWidth = Op.getValueSizeInBits();
5032 if (BitWidth % 8 != 0)
5034 unsigned ByteWidth = BitWidth / 8;
5035 assert(Index < ByteWidth && "invalid index requested");
5038 switch (Op.getOpcode()) {
5040 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5043 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5047 if (LHS->isConstantZero())
5049 if (RHS->isConstantZero())
5054 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5058 uint64_t BitShift = ShiftOp->getZExtValue();
5059 if (BitShift % 8 != 0)
5061 uint64_t ByteShift = BitShift / 8;
5063 return Index < ByteShift
5064 ? ByteProvider::getConstantZero()
5065 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5068 case ISD::ANY_EXTEND:
5069 case ISD::SIGN_EXTEND:
5070 case ISD::ZERO_EXTEND: {
5071 SDValue NarrowOp = Op->getOperand(0);
5072 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5073 if (NarrowBitWidth % 8 != 0)
5075 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5077 if (Index >= NarrowByteWidth)
5078 return Op.getOpcode() == ISD::ZERO_EXTEND
5079 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5081 return calculateByteProvider(NarrowOp, Index, Depth + 1);
5084 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5087 auto L = cast<LoadSDNode>(Op.getNode());
5088 if (L->isVolatile() || L->isIndexed())
5091 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5092 if (NarrowBitWidth % 8 != 0)
5094 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5096 if (Index >= NarrowByteWidth)
5097 return L->getExtensionType() == ISD::ZEXTLOAD
5098 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5100 return ByteProvider::getMemory(L, Index);
5107 /// Match a pattern where a wide type scalar value is loaded by several narrow
5108 /// loads and combined by shifts and ors. Fold it into a single load or a load
5109 /// and a BSWAP if the targets supports it.
5111 /// Assuming little endian target:
5113 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5115 /// i32 val = *((i32)a)
5118 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5120 /// i32 val = BSWAP(*((i32)a))
5122 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5123 /// interact well with the worklist mechanism. When a part of the pattern is
5124 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5125 /// but the root node of the pattern which triggers the load combine is not
5126 /// necessarily a direct user of the changed node. For example, once the address
5127 /// of t28 load is reassociated load combine won't be triggered:
5128 /// t25: i32 = add t4, Constant:i32<2>
5129 /// t26: i64 = sign_extend t25
5130 /// t27: i64 = add t2, t26
5131 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5132 /// t29: i32 = zero_extend t28
5133 /// t32: i32 = shl t29, Constant:i8<8>
5134 /// t33: i32 = or t23, t32
5135 /// As a possible fix visitLoad can check if the load can be a part of a load
5136 /// combine pattern and add corresponding OR roots to the worklist.
5137 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5138 assert(N->getOpcode() == ISD::OR &&
5139 "Can only match load combining against OR nodes");
5141 // Handles simple types only
5142 EVT VT = N->getValueType(0);
5143 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5145 unsigned ByteWidth = VT.getSizeInBits() / 8;
5147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5148 // Before legalize we can introduce too wide illegal loads which will be later
5149 // split into legal sized loads. This enables us to combine i64 load by i8
5150 // patterns to a couple of i32 loads on 32 bit targets.
5151 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5154 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5155 unsigned BW, unsigned i) { return i; };
5156 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5157 unsigned BW, unsigned i) { return BW - i - 1; };
5159 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5160 auto MemoryByteOffset = [&] (ByteProvider P) {
5161 assert(P.isMemory() && "Must be a memory byte provider");
5162 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5163 assert(LoadBitWidth % 8 == 0 &&
5164 "can only analyze providers for individual bytes not bit");
5165 unsigned LoadByteWidth = LoadBitWidth / 8;
5166 return IsBigEndianTarget
5167 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5168 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5171 Optional<BaseIndexOffset> Base;
5174 SmallSet<LoadSDNode *, 8> Loads;
5175 Optional<ByteProvider> FirstByteProvider;
5176 int64_t FirstOffset = INT64_MAX;
5178 // Check if all the bytes of the OR we are looking at are loaded from the same
5179 // base address. Collect bytes offsets from Base address in ByteOffsets.
5180 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5181 for (unsigned i = 0; i < ByteWidth; i++) {
5182 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5183 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5186 LoadSDNode *L = P->Load;
5187 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5188 "Must be enforced by calculateByteProvider");
5189 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5191 // All loads must share the same chain
5192 SDValue LChain = L->getChain();
5195 else if (Chain != LChain)
5198 // Loads must share the same base address
5199 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
5200 int64_t ByteOffsetFromBase = 0;
5203 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5206 // Calculate the offset of the current byte from the base address
5207 ByteOffsetFromBase += MemoryByteOffset(*P);
5208 ByteOffsets[i] = ByteOffsetFromBase;
5210 // Remember the first byte load
5211 if (ByteOffsetFromBase < FirstOffset) {
5212 FirstByteProvider = P;
5213 FirstOffset = ByteOffsetFromBase;
5218 assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5219 "memory, so there must be at least one load which produces the value");
5220 assert(Base && "Base address of the accessed memory location must be set");
5221 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5223 // Check if the bytes of the OR we are looking at match with either big or
5224 // little endian value load
5225 bool BigEndian = true, LittleEndian = true;
5226 for (unsigned i = 0; i < ByteWidth; i++) {
5227 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5228 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5229 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5230 if (!BigEndian && !LittleEndian)
5233 assert((BigEndian != LittleEndian) && "should be either or");
5234 assert(FirstByteProvider && "must be set");
5236 // Ensure that the first byte is loaded from zero offset of the first load.
5237 // So the combined value can be loaded from the first load address.
5238 if (MemoryByteOffset(*FirstByteProvider) != 0)
5240 LoadSDNode *FirstLoad = FirstByteProvider->Load;
5242 // The node we are looking at matches with the pattern, check if we can
5243 // replace it with a single load and bswap if needed.
5245 // If the load needs byte swap check if the target supports it
5246 bool NeedsBswap = IsBigEndianTarget != BigEndian;
5248 // Before legalize we can introduce illegal bswaps which will be later
5249 // converted to an explicit bswap sequence. This way we end up with a single
5250 // load and byte shuffling instead of several loads and byte shuffling.
5251 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5254 // Check that a load of the wide type is both allowed and fast on the target
5256 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5257 VT, FirstLoad->getAddressSpace(),
5258 FirstLoad->getAlignment(), &Fast);
5259 if (!Allowed || !Fast)
5263 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5264 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5266 // Transfer chain users from old loads to the new load.
5267 for (LoadSDNode *L : Loads)
5268 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5270 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5273 SDValue DAGCombiner::visitXOR(SDNode *N) {
5274 SDValue N0 = N->getOperand(0);
5275 SDValue N1 = N->getOperand(1);
5276 EVT VT = N0.getValueType();
5279 if (VT.isVector()) {
5280 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5283 // fold (xor x, 0) -> x, vector edition
5284 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5286 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5290 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5291 if (N0.isUndef() && N1.isUndef())
5292 return DAG.getConstant(0, SDLoc(N), VT);
5293 // fold (xor x, undef) -> undef
5298 // fold (xor c1, c2) -> c1^c2
5299 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5300 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5302 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5303 // canonicalize constant to RHS
5304 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5305 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5306 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5307 // fold (xor x, 0) -> x
5308 if (isNullConstant(N1))
5311 if (SDValue NewSel = foldBinOpIntoSelect(N))
5315 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5318 // fold !(x cc y) -> (x !cc y)
5319 SDValue LHS, RHS, CC;
5320 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5321 bool isInt = LHS.getValueType().isInteger();
5322 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5325 if (!LegalOperations ||
5326 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5327 switch (N0.getOpcode()) {
5329 llvm_unreachable("Unhandled SetCC Equivalent!");
5331 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5332 case ISD::SELECT_CC:
5333 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5334 N0.getOperand(3), NotCC);
5339 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5340 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5341 N0.getNode()->hasOneUse() &&
5342 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5343 SDValue V = N0.getOperand(0);
5345 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5346 DAG.getConstant(1, DL, V.getValueType()));
5347 AddToWorklist(V.getNode());
5348 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5351 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5352 if (isOneConstant(N1) && VT == MVT::i1 &&
5353 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5354 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5355 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5356 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5357 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5358 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5359 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5360 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5363 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5364 if (isAllOnesConstant(N1) &&
5365 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5366 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5367 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5368 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5369 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5370 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5371 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5372 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5375 // fold (xor (and x, y), y) -> (and (not x), y)
5376 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5377 N0->getOperand(1) == N1) {
5378 SDValue X = N0->getOperand(0);
5379 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5380 AddToWorklist(NotX.getNode());
5381 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5383 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5384 if (N1C && N0.getOpcode() == ISD::XOR) {
5385 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5387 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5388 DAG.getConstant(N1C->getAPIntValue() ^
5389 N00C->getAPIntValue(), DL, VT));
5391 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5393 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5394 DAG.getConstant(N1C->getAPIntValue() ^
5395 N01C->getAPIntValue(), DL, VT));
5399 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5400 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5401 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5402 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5403 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5404 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5405 if (C->getAPIntValue() == (OpSizeInBits - 1))
5406 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5409 // fold (xor x, x) -> 0
5411 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5413 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5414 // Here is a concrete example of this equivalence:
5416 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5417 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5421 // i16 ~1 == 0b1111111111111110
5422 // i16 rol(~1, 14) == 0b1011111111111111
5424 // Some additional tips to help conceptualize this transform:
5425 // - Try to see the operation as placing a single zero in a value of all ones.
5426 // - There exists no value for x which would allow the result to contain zero.
5427 // - Values of x larger than the bitwidth are undefined and do not require a
5428 // consistent result.
5429 // - Pushing the zero left requires shifting one bits in from the right.
5430 // A rotate left of ~1 is a nice way of achieving the desired result.
5431 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5432 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5434 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5438 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5439 if (N0.getOpcode() == N1.getOpcode())
5440 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5443 // Simplify the expression using non-local knowledge.
5444 if (SimplifyDemandedBits(SDValue(N, 0)))
5445 return SDValue(N, 0);
5450 /// Handle transforms common to the three shifts, when the shift amount is a
5452 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5453 SDNode *LHS = N->getOperand(0).getNode();
5454 if (!LHS->hasOneUse()) return SDValue();
5456 // We want to pull some binops through shifts, so that we have (and (shift))
5457 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5458 // thing happens with address calculations, so it's important to canonicalize
5460 bool HighBitSet = false; // Can we transform this if the high bit is set?
5462 switch (LHS->getOpcode()) {
5463 default: return SDValue();
5466 HighBitSet = false; // We can only transform sra if the high bit is clear.
5469 HighBitSet = true; // We can only transform sra if the high bit is set.
5472 if (N->getOpcode() != ISD::SHL)
5473 return SDValue(); // only shl(add) not sr[al](add).
5474 HighBitSet = false; // We can only transform sra if the high bit is clear.
5478 // We require the RHS of the binop to be a constant and not opaque as well.
5479 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5480 if (!BinOpCst) return SDValue();
5482 // FIXME: disable this unless the input to the binop is a shift by a constant
5483 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5484 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5485 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5486 BinOpLHSVal->getOpcode() == ISD::SRA ||
5487 BinOpLHSVal->getOpcode() == ISD::SRL;
5488 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5489 BinOpLHSVal->getOpcode() == ISD::SELECT;
5491 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5495 if (isCopyOrSelect && N->hasOneUse())
5498 EVT VT = N->getValueType(0);
5500 // If this is a signed shift right, and the high bit is modified by the
5501 // logical operation, do not perform the transformation. The highBitSet
5502 // boolean indicates the value of the high bit of the constant which would
5503 // cause it to be modified for this operation.
5504 if (N->getOpcode() == ISD::SRA) {
5505 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5506 if (BinOpRHSSignSet != HighBitSet)
5510 if (!TLI.isDesirableToCommuteWithShift(LHS))
5513 // Fold the constants, shifting the binop RHS by the shift amount.
5514 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5516 LHS->getOperand(1), N->getOperand(1));
5517 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5519 // Create the new shift.
5520 SDValue NewShift = DAG.getNode(N->getOpcode(),
5521 SDLoc(LHS->getOperand(0)),
5522 VT, LHS->getOperand(0), N->getOperand(1));
5524 // Create the new binop.
5525 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5528 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5529 assert(N->getOpcode() == ISD::TRUNCATE);
5530 assert(N->getOperand(0).getOpcode() == ISD::AND);
5532 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5533 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5534 SDValue N01 = N->getOperand(0).getOperand(1);
5535 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5537 EVT TruncVT = N->getValueType(0);
5538 SDValue N00 = N->getOperand(0).getOperand(0);
5539 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5540 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5541 AddToWorklist(Trunc00.getNode());
5542 AddToWorklist(Trunc01.getNode());
5543 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5550 SDValue DAGCombiner::visitRotate(SDNode *N) {
5552 SDValue N0 = N->getOperand(0);
5553 SDValue N1 = N->getOperand(1);
5554 EVT VT = N->getValueType(0);
5555 unsigned Bitsize = VT.getScalarSizeInBits();
5557 // fold (rot x, 0) -> x
5558 if (isNullConstantOrNullSplatConstant(N1))
5561 // fold (rot x, c) -> (rot x, c % BitSize)
5562 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5563 if (Cst->getAPIntValue().uge(Bitsize)) {
5564 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5565 return DAG.getNode(N->getOpcode(), dl, VT, N0,
5566 DAG.getConstant(RotAmt, dl, N1.getValueType()));
5570 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5571 if (N1.getOpcode() == ISD::TRUNCATE &&
5572 N1.getOperand(0).getOpcode() == ISD::AND) {
5573 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5574 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5577 unsigned NextOp = N0.getOpcode();
5578 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5579 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5580 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5581 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5582 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5583 EVT ShiftVT = C1->getValueType(0);
5584 bool SameSide = (N->getOpcode() == NextOp);
5585 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5586 if (SDValue CombinedShift =
5587 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5588 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5589 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5590 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5591 BitsizeC.getNode());
5592 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5600 SDValue DAGCombiner::visitSHL(SDNode *N) {
5601 SDValue N0 = N->getOperand(0);
5602 SDValue N1 = N->getOperand(1);
5603 EVT VT = N0.getValueType();
5604 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5607 if (VT.isVector()) {
5608 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5611 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5612 // If setcc produces all-one true value then:
5613 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5614 if (N1CV && N1CV->isConstant()) {
5615 if (N0.getOpcode() == ISD::AND) {
5616 SDValue N00 = N0->getOperand(0);
5617 SDValue N01 = N0->getOperand(1);
5618 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5620 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5621 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5622 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5623 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5625 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5631 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5633 // fold (shl c1, c2) -> c1<<c2
5634 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5635 if (N0C && N1C && !N1C->isOpaque())
5636 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5637 // fold (shl 0, x) -> 0
5638 if (isNullConstantOrNullSplatConstant(N0))
5640 // fold (shl x, c >= size(x)) -> undef
5641 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5642 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5643 return Val->getAPIntValue().uge(OpSizeInBits);
5645 if (matchUnaryPredicate(N1, MatchShiftTooBig))
5646 return DAG.getUNDEF(VT);
5647 // fold (shl x, 0) -> x
5648 if (N1C && N1C->isNullValue())
5650 // fold (shl undef, x) -> 0
5652 return DAG.getConstant(0, SDLoc(N), VT);
5654 if (SDValue NewSel = foldBinOpIntoSelect(N))
5657 // if (shl x, c) is known to be zero, return 0
5658 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5659 APInt::getAllOnesValue(OpSizeInBits)))
5660 return DAG.getConstant(0, SDLoc(N), VT);
5661 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5662 if (N1.getOpcode() == ISD::TRUNCATE &&
5663 N1.getOperand(0).getOpcode() == ISD::AND) {
5664 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5665 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5668 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5669 return SDValue(N, 0);
5671 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5672 if (N0.getOpcode() == ISD::SHL) {
5673 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5674 ConstantSDNode *RHS) {
5675 APInt c1 = LHS->getAPIntValue();
5676 APInt c2 = RHS->getAPIntValue();
5677 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5678 return (c1 + c2).uge(OpSizeInBits);
5680 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5681 return DAG.getConstant(0, SDLoc(N), VT);
5683 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5684 ConstantSDNode *RHS) {
5685 APInt c1 = LHS->getAPIntValue();
5686 APInt c2 = RHS->getAPIntValue();
5687 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5688 return (c1 + c2).ult(OpSizeInBits);
5690 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5692 EVT ShiftVT = N1.getValueType();
5693 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5694 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5698 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5699 // For this to be valid, the second form must not preserve any of the bits
5700 // that are shifted out by the inner shift in the first form. This means
5701 // the outer shift size must be >= the number of bits added by the ext.
5702 // As a corollary, we don't care what kind of ext it is.
5703 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5704 N0.getOpcode() == ISD::ANY_EXTEND ||
5705 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5706 N0.getOperand(0).getOpcode() == ISD::SHL) {
5707 SDValue N0Op0 = N0.getOperand(0);
5708 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5709 APInt c1 = N0Op0C1->getAPIntValue();
5710 APInt c2 = N1C->getAPIntValue();
5711 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5713 EVT InnerShiftVT = N0Op0.getValueType();
5714 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5715 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5717 APInt Sum = c1 + c2;
5718 if (Sum.uge(OpSizeInBits))
5719 return DAG.getConstant(0, DL, VT);
5723 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5724 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5729 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5730 // Only fold this if the inner zext has no other uses to avoid increasing
5731 // the total number of instructions.
5732 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5733 N0.getOperand(0).getOpcode() == ISD::SRL) {
5734 SDValue N0Op0 = N0.getOperand(0);
5735 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5736 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5737 uint64_t c1 = N0Op0C1->getZExtValue();
5738 uint64_t c2 = N1C->getZExtValue();
5740 SDValue NewOp0 = N0.getOperand(0);
5741 EVT CountVT = NewOp0.getOperand(1).getValueType();
5743 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5745 DAG.getConstant(c2, DL, CountVT));
5746 AddToWorklist(NewSHL.getNode());
5747 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5753 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5754 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5755 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5756 N0->getFlags().hasExact()) {
5757 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5758 uint64_t C1 = N0C1->getZExtValue();
5759 uint64_t C2 = N1C->getZExtValue();
5762 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5763 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5764 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5765 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5769 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5770 // (and (srl x, (sub c1, c2), MASK)
5771 // Only fold this if the inner shift has no other uses -- if it does, folding
5772 // this will increase the total number of instructions.
5773 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5774 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5775 uint64_t c1 = N0C1->getZExtValue();
5776 if (c1 < OpSizeInBits) {
5777 uint64_t c2 = N1C->getZExtValue();
5778 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5783 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5784 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5786 Mask.lshrInPlace(c1 - c2);
5788 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5789 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5792 return DAG.getNode(ISD::AND, DL, VT, Shift,
5793 DAG.getConstant(Mask, DL, VT));
5798 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5799 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5800 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5802 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5803 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5804 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5807 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5808 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5809 // Variant of version done on multiply, except mul by a power of 2 is turned
5811 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5812 N0.getNode()->hasOneUse() &&
5813 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5814 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5815 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5816 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5817 AddToWorklist(Shl0.getNode());
5818 AddToWorklist(Shl1.getNode());
5819 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5822 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5823 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5824 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5825 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5826 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5827 if (isConstantOrConstantVector(Shl))
5828 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5831 if (N1C && !N1C->isOpaque())
5832 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5838 SDValue DAGCombiner::visitSRA(SDNode *N) {
5839 SDValue N0 = N->getOperand(0);
5840 SDValue N1 = N->getOperand(1);
5841 EVT VT = N0.getValueType();
5842 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5844 // Arithmetic shifting an all-sign-bit value is a no-op.
5845 // fold (sra 0, x) -> 0
5846 // fold (sra -1, x) -> -1
5847 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5852 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5855 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5857 // fold (sra c1, c2) -> (sra c1, c2)
5858 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5859 if (N0C && N1C && !N1C->isOpaque())
5860 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5861 // fold (sra x, c >= size(x)) -> undef
5862 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5863 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5864 return Val->getAPIntValue().uge(OpSizeInBits);
5866 if (matchUnaryPredicate(N1, MatchShiftTooBig))
5867 return DAG.getUNDEF(VT);
5868 // fold (sra x, 0) -> x
5869 if (N1C && N1C->isNullValue())
5872 if (SDValue NewSel = foldBinOpIntoSelect(N))
5875 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5877 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5878 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5879 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5881 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5882 ExtVT, VT.getVectorNumElements());
5883 if ((!LegalOperations ||
5884 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5885 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5886 N0.getOperand(0), DAG.getValueType(ExtVT));
5889 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5890 if (N0.getOpcode() == ISD::SRA) {
5892 EVT ShiftVT = N1.getValueType();
5894 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5895 ConstantSDNode *RHS) {
5896 APInt c1 = LHS->getAPIntValue();
5897 APInt c2 = RHS->getAPIntValue();
5898 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5899 return (c1 + c2).uge(OpSizeInBits);
5901 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5902 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5903 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5905 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5906 ConstantSDNode *RHS) {
5907 APInt c1 = LHS->getAPIntValue();
5908 APInt c2 = RHS->getAPIntValue();
5909 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5910 return (c1 + c2).ult(OpSizeInBits);
5912 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5913 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5914 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5918 // fold (sra (shl X, m), (sub result_size, n))
5919 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5920 // result_size - n != m.
5921 // If truncate is free for the target sext(shl) is likely to result in better
5923 if (N0.getOpcode() == ISD::SHL && N1C) {
5924 // Get the two constanst of the shifts, CN0 = m, CN = n.
5925 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5927 LLVMContext &Ctx = *DAG.getContext();
5928 // Determine what the truncate's result bitsize and type would be.
5929 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5932 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5934 // Determine the residual right-shift amount.
5935 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5937 // If the shift is not a no-op (in which case this should be just a sign
5938 // extend already), the truncated to type is legal, sign_extend is legal
5939 // on that type, and the truncate to that type is both legal and free,
5940 // perform the transform.
5941 if ((ShiftAmt > 0) &&
5942 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5943 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5944 TLI.isTruncateFree(VT, TruncVT)) {
5946 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5947 getShiftAmountTy(N0.getOperand(0).getValueType()));
5948 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5949 N0.getOperand(0), Amt);
5950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5952 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5953 N->getValueType(0), Trunc);
5958 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5959 if (N1.getOpcode() == ISD::TRUNCATE &&
5960 N1.getOperand(0).getOpcode() == ISD::AND) {
5961 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5962 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5965 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5966 // if c1 is equal to the number of bits the trunc removes
5967 if (N0.getOpcode() == ISD::TRUNCATE &&
5968 (N0.getOperand(0).getOpcode() == ISD::SRL ||
5969 N0.getOperand(0).getOpcode() == ISD::SRA) &&
5970 N0.getOperand(0).hasOneUse() &&
5971 N0.getOperand(0).getOperand(1).hasOneUse() &&
5973 SDValue N0Op0 = N0.getOperand(0);
5974 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5975 unsigned LargeShiftVal = LargeShift->getZExtValue();
5976 EVT LargeVT = N0Op0.getValueType();
5978 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5981 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5982 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5983 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5984 N0Op0.getOperand(0), Amt);
5985 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5990 // Simplify, based on bits shifted out of the LHS.
5991 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5992 return SDValue(N, 0);
5994 // If the sign bit is known to be zero, switch this to a SRL.
5995 if (DAG.SignBitIsZero(N0))
5996 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5998 if (N1C && !N1C->isOpaque())
5999 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6005 SDValue DAGCombiner::visitSRL(SDNode *N) {
6006 SDValue N0 = N->getOperand(0);
6007 SDValue N1 = N->getOperand(1);
6008 EVT VT = N0.getValueType();
6009 unsigned OpSizeInBits = VT.getScalarSizeInBits();
6013 if (SDValue FoldedVOp = SimplifyVBinOp(N))
6016 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6018 // fold (srl c1, c2) -> c1 >>u c2
6019 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6020 if (N0C && N1C && !N1C->isOpaque())
6021 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6022 // fold (srl 0, x) -> 0
6023 if (isNullConstantOrNullSplatConstant(N0))
6025 // fold (srl x, c >= size(x)) -> undef
6026 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6027 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6028 return Val->getAPIntValue().uge(OpSizeInBits);
6030 if (matchUnaryPredicate(N1, MatchShiftTooBig))
6031 return DAG.getUNDEF(VT);
6032 // fold (srl x, 0) -> x
6033 if (N1C && N1C->isNullValue())
6036 if (SDValue NewSel = foldBinOpIntoSelect(N))
6039 // if (srl x, c) is known to be zero, return 0
6040 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6041 APInt::getAllOnesValue(OpSizeInBits)))
6042 return DAG.getConstant(0, SDLoc(N), VT);
6044 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6045 if (N0.getOpcode() == ISD::SRL) {
6046 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6047 ConstantSDNode *RHS) {
6048 APInt c1 = LHS->getAPIntValue();
6049 APInt c2 = RHS->getAPIntValue();
6050 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6051 return (c1 + c2).uge(OpSizeInBits);
6053 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6054 return DAG.getConstant(0, SDLoc(N), VT);
6056 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6057 ConstantSDNode *RHS) {
6058 APInt c1 = LHS->getAPIntValue();
6059 APInt c2 = RHS->getAPIntValue();
6060 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6061 return (c1 + c2).ult(OpSizeInBits);
6063 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6065 EVT ShiftVT = N1.getValueType();
6066 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6067 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6071 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6072 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6073 N0.getOperand(0).getOpcode() == ISD::SRL) {
6074 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6075 uint64_t c1 = N001C->getZExtValue();
6076 uint64_t c2 = N1C->getZExtValue();
6077 EVT InnerShiftVT = N0.getOperand(0).getValueType();
6078 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6079 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6080 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6081 if (c1 + OpSizeInBits == InnerShiftSize) {
6083 if (c1 + c2 >= InnerShiftSize)
6084 return DAG.getConstant(0, DL, VT);
6085 return DAG.getNode(ISD::TRUNCATE, DL, VT,
6086 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6087 N0.getOperand(0).getOperand(0),
6088 DAG.getConstant(c1 + c2, DL,
6094 // fold (srl (shl x, c), c) -> (and x, cst2)
6095 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6096 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6099 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6100 AddToWorklist(Mask.getNode());
6101 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6104 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6105 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6106 // Shifting in all undef bits?
6107 EVT SmallVT = N0.getOperand(0).getValueType();
6108 unsigned BitSize = SmallVT.getScalarSizeInBits();
6109 if (N1C->getZExtValue() >= BitSize)
6110 return DAG.getUNDEF(VT);
6112 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6113 uint64_t ShiftAmt = N1C->getZExtValue();
6115 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6117 DAG.getConstant(ShiftAmt, DL0,
6118 getShiftAmountTy(SmallVT)));
6119 AddToWorklist(SmallShift.getNode());
6120 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6122 return DAG.getNode(ISD::AND, DL, VT,
6123 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6124 DAG.getConstant(Mask, DL, VT));
6128 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
6129 // bit, which is unmodified by sra.
6130 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6131 if (N0.getOpcode() == ISD::SRA)
6132 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6135 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
6136 if (N1C && N0.getOpcode() == ISD::CTLZ &&
6137 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6139 DAG.computeKnownBits(N0.getOperand(0), Known);
6141 // If any of the input bits are KnownOne, then the input couldn't be all
6142 // zeros, thus the result of the srl will always be zero.
6143 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6145 // If all of the bits input the to ctlz node are known to be zero, then
6146 // the result of the ctlz is "32" and the result of the shift is one.
6147 APInt UnknownBits = ~Known.Zero;
6148 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6150 // Otherwise, check to see if there is exactly one bit input to the ctlz.
6151 if (UnknownBits.isPowerOf2()) {
6152 // Okay, we know that only that the single bit specified by UnknownBits
6153 // could be set on input to the CTLZ node. If this bit is set, the SRL
6154 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6155 // to an SRL/XOR pair, which is likely to simplify more.
6156 unsigned ShAmt = UnknownBits.countTrailingZeros();
6157 SDValue Op = N0.getOperand(0);
6161 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6162 DAG.getConstant(ShAmt, DL,
6163 getShiftAmountTy(Op.getValueType())));
6164 AddToWorklist(Op.getNode());
6168 return DAG.getNode(ISD::XOR, DL, VT,
6169 Op, DAG.getConstant(1, DL, VT));
6173 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6174 if (N1.getOpcode() == ISD::TRUNCATE &&
6175 N1.getOperand(0).getOpcode() == ISD::AND) {
6176 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6177 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6180 // fold operands of srl based on knowledge that the low bits are not
6182 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6183 return SDValue(N, 0);
6185 if (N1C && !N1C->isOpaque())
6186 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6189 // Attempt to convert a srl of a load into a narrower zero-extending load.
6190 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6193 // Here is a common situation. We want to optimize:
6196 // %b = and i32 %a, 2
6197 // %c = srl i32 %b, 1
6198 // brcond i32 %c ...
6204 // %c = setcc eq %b, 0
6207 // However when after the source operand of SRL is optimized into AND, the SRL
6208 // itself may not be optimized further. Look for it and add the BRCOND into
6210 if (N->hasOneUse()) {
6211 SDNode *Use = *N->use_begin();
6212 if (Use->getOpcode() == ISD::BRCOND)
6214 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6215 // Also look pass the truncate.
6216 Use = *Use->use_begin();
6217 if (Use->getOpcode() == ISD::BRCOND)
6225 SDValue DAGCombiner::visitABS(SDNode *N) {
6226 SDValue N0 = N->getOperand(0);
6227 EVT VT = N->getValueType(0);
6229 // fold (abs c1) -> c2
6230 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6231 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6232 // fold (abs (abs x)) -> (abs x)
6233 if (N0.getOpcode() == ISD::ABS)
6235 // fold (abs x) -> x iff not-negative
6236 if (DAG.SignBitIsZero(N0))
6241 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6242 SDValue N0 = N->getOperand(0);
6243 EVT VT = N->getValueType(0);
6245 // fold (bswap c1) -> c2
6246 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6247 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6248 // fold (bswap (bswap x)) -> x
6249 if (N0.getOpcode() == ISD::BSWAP)
6250 return N0->getOperand(0);
6254 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6255 SDValue N0 = N->getOperand(0);
6256 EVT VT = N->getValueType(0);
6258 // fold (bitreverse c1) -> c2
6259 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6260 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6261 // fold (bitreverse (bitreverse x)) -> x
6262 if (N0.getOpcode() == ISD::BITREVERSE)
6263 return N0.getOperand(0);
6267 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6268 SDValue N0 = N->getOperand(0);
6269 EVT VT = N->getValueType(0);
6271 // fold (ctlz c1) -> c2
6272 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6273 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6277 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6278 SDValue N0 = N->getOperand(0);
6279 EVT VT = N->getValueType(0);
6281 // fold (ctlz_zero_undef c1) -> c2
6282 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6283 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6287 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6288 SDValue N0 = N->getOperand(0);
6289 EVT VT = N->getValueType(0);
6291 // fold (cttz c1) -> c2
6292 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6293 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6297 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6298 SDValue N0 = N->getOperand(0);
6299 EVT VT = N->getValueType(0);
6301 // fold (cttz_zero_undef c1) -> c2
6302 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6303 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6307 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6308 SDValue N0 = N->getOperand(0);
6309 EVT VT = N->getValueType(0);
6311 // fold (ctpop c1) -> c2
6312 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6313 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6317 /// \brief Generate Min/Max node
6318 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6319 SDValue RHS, SDValue True, SDValue False,
6320 ISD::CondCode CC, const TargetLowering &TLI,
6321 SelectionDAG &DAG) {
6322 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6332 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6333 if (TLI.isOperationLegal(Opcode, VT))
6334 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6343 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6344 if (TLI.isOperationLegal(Opcode, VT))
6345 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6353 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6354 SDValue Cond = N->getOperand(0);
6355 SDValue N1 = N->getOperand(1);
6356 SDValue N2 = N->getOperand(2);
6357 EVT VT = N->getValueType(0);
6358 EVT CondVT = Cond.getValueType();
6361 if (!VT.isInteger())
6364 auto *C1 = dyn_cast<ConstantSDNode>(N1);
6365 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6369 // Only do this before legalization to avoid conflicting with target-specific
6370 // transforms in the other direction (create a select from a zext/sext). There
6371 // is also a target-independent combine here in DAGCombiner in the other
6372 // direction for (select Cond, -1, 0) when the condition is not i1.
6373 if (CondVT == MVT::i1 && !LegalOperations) {
6374 if (C1->isNullValue() && C2->isOne()) {
6375 // select Cond, 0, 1 --> zext (!Cond)
6376 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6378 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6381 if (C1->isNullValue() && C2->isAllOnesValue()) {
6382 // select Cond, 0, -1 --> sext (!Cond)
6383 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6385 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6388 if (C1->isOne() && C2->isNullValue()) {
6389 // select Cond, 1, 0 --> zext (Cond)
6391 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6394 if (C1->isAllOnesValue() && C2->isNullValue()) {
6395 // select Cond, -1, 0 --> sext (Cond)
6397 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6401 // For any constants that differ by 1, we can transform the select into an
6402 // extend and add. Use a target hook because some targets may prefer to
6403 // transform in the other direction.
6404 if (TLI.convertSelectOfConstantsToMath(VT)) {
6405 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6406 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6408 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6409 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6411 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6412 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6414 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6415 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6422 // fold (select Cond, 0, 1) -> (xor Cond, 1)
6423 // We can't do this reliably if integer based booleans have different contents
6424 // to floating point based booleans. This is because we can't tell whether we
6425 // have an integer-based boolean or a floating-point-based boolean unless we
6426 // can find the SETCC that produced it and inspect its operands. This is
6427 // fairly easy if C is the SETCC node, but it can potentially be
6428 // undiscoverable (or not reasonably discoverable). For example, it could be
6429 // in another basic block or it could require searching a complicated
6431 if (CondVT.isInteger() &&
6432 TLI.getBooleanContents(false, true) ==
6433 TargetLowering::ZeroOrOneBooleanContent &&
6434 TLI.getBooleanContents(false, false) ==
6435 TargetLowering::ZeroOrOneBooleanContent &&
6436 C1->isNullValue() && C2->isOne()) {
6438 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6439 if (VT.bitsEq(CondVT))
6441 return DAG.getZExtOrTrunc(NotCond, DL, VT);
6447 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6448 SDValue N0 = N->getOperand(0);
6449 SDValue N1 = N->getOperand(1);
6450 SDValue N2 = N->getOperand(2);
6451 EVT VT = N->getValueType(0);
6452 EVT VT0 = N0.getValueType();
6455 // fold (select C, X, X) -> X
6459 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6460 // fold (select true, X, Y) -> X
6461 // fold (select false, X, Y) -> Y
6462 return !N0C->isNullValue() ? N1 : N2;
6465 // fold (select X, X, Y) -> (or X, Y)
6466 // fold (select X, 1, Y) -> (or C, Y)
6467 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6468 return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6470 if (SDValue V = foldSelectOfConstants(N))
6473 // fold (select C, 0, X) -> (and (not C), X)
6474 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6475 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6476 AddToWorklist(NOTNode.getNode());
6477 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6479 // fold (select C, X, 1) -> (or (not C), X)
6480 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6481 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6482 AddToWorklist(NOTNode.getNode());
6483 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6485 // fold (select X, Y, X) -> (and X, Y)
6486 // fold (select X, Y, 0) -> (and X, Y)
6487 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6488 return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6490 // If we can fold this based on the true/false value, do so.
6491 if (SimplifySelectOps(N, N1, N2))
6492 return SDValue(N, 0); // Don't revisit N.
6494 if (VT0 == MVT::i1) {
6495 // The code in this block deals with the following 2 equivalences:
6496 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6497 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6498 // The target can specify its preferred form with the
6499 // shouldNormalizeToSelectSequence() callback. However we always transform
6500 // to the right anyway if we find the inner select exists in the DAG anyway
6501 // and we always transform to the left side if we know that we can further
6502 // optimize the combination of the conditions.
6503 bool normalizeToSequence =
6504 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6505 // select (and Cond0, Cond1), X, Y
6506 // -> select Cond0, (select Cond1, X, Y), Y
6507 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6508 SDValue Cond0 = N0->getOperand(0);
6509 SDValue Cond1 = N0->getOperand(1);
6510 SDValue InnerSelect =
6511 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6512 if (normalizeToSequence || !InnerSelect.use_empty())
6513 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6516 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6517 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6518 SDValue Cond0 = N0->getOperand(0);
6519 SDValue Cond1 = N0->getOperand(1);
6520 SDValue InnerSelect =
6521 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6522 if (normalizeToSequence || !InnerSelect.use_empty())
6523 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6527 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6528 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6529 SDValue N1_0 = N1->getOperand(0);
6530 SDValue N1_1 = N1->getOperand(1);
6531 SDValue N1_2 = N1->getOperand(2);
6532 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6533 // Create the actual and node if we can generate good code for it.
6534 if (!normalizeToSequence) {
6535 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6536 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6538 // Otherwise see if we can optimize the "and" to a better pattern.
6539 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6540 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6544 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6545 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6546 SDValue N2_0 = N2->getOperand(0);
6547 SDValue N2_1 = N2->getOperand(1);
6548 SDValue N2_2 = N2->getOperand(2);
6549 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6550 // Create the actual or node if we can generate good code for it.
6551 if (!normalizeToSequence) {
6552 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6553 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6555 // Otherwise see if we can optimize to a better pattern.
6556 if (SDValue Combined = visitORLike(N0, N2_0, N))
6557 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6563 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6564 if (VT0 == MVT::i1) {
6565 if (N0->getOpcode() == ISD::XOR) {
6566 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6567 SDValue Cond0 = N0->getOperand(0);
6569 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6574 // fold selects based on a setcc into other things, such as min/max/abs
6575 if (N0.getOpcode() == ISD::SETCC) {
6576 // select x, y (fcmp lt x, y) -> fminnum x, y
6577 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6579 // This is OK if we don't care about what happens if either operand is a
6583 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6584 // no signed zeros as well as no nans.
6585 const TargetOptions &Options = DAG.getTarget().Options;
6586 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6587 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6588 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6590 if (SDValue FMinMax = combineMinNumMaxNum(
6591 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6595 if ((!LegalOperations &&
6596 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6597 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6598 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6599 N0.getOperand(1), N1, N2, N0.getOperand(2));
6600 return SimplifySelect(DL, N0, N1, N2);
6607 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6610 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6612 // Split the inputs.
6613 SDValue Lo, Hi, LL, LH, RL, RH;
6614 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6615 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6617 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6618 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6620 return std::make_pair(Lo, Hi);
6623 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6624 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6625 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6627 SDValue Cond = N->getOperand(0);
6628 SDValue LHS = N->getOperand(1);
6629 SDValue RHS = N->getOperand(2);
6630 EVT VT = N->getValueType(0);
6631 int NumElems = VT.getVectorNumElements();
6632 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6633 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6634 Cond.getOpcode() == ISD::BUILD_VECTOR);
6636 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6637 // binary ones here.
6638 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6641 // We're sure we have an even number of elements due to the
6642 // concat_vectors we have as arguments to vselect.
6643 // Skip BV elements until we find one that's not an UNDEF
6644 // After we find an UNDEF element, keep looping until we get to half the
6645 // length of the BV and see if all the non-undef nodes are the same.
6646 ConstantSDNode *BottomHalf = nullptr;
6647 for (int i = 0; i < NumElems / 2; ++i) {
6648 if (Cond->getOperand(i)->isUndef())
6651 if (BottomHalf == nullptr)
6652 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6653 else if (Cond->getOperand(i).getNode() != BottomHalf)
6657 // Do the same for the second half of the BuildVector
6658 ConstantSDNode *TopHalf = nullptr;
6659 for (int i = NumElems / 2; i < NumElems; ++i) {
6660 if (Cond->getOperand(i)->isUndef())
6663 if (TopHalf == nullptr)
6664 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6665 else if (Cond->getOperand(i).getNode() != TopHalf)
6669 assert(TopHalf && BottomHalf &&
6670 "One half of the selector was all UNDEFs and the other was all the "
6671 "same value. This should have been addressed before this function.");
6673 ISD::CONCAT_VECTORS, DL, VT,
6674 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6675 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6678 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6679 if (Level >= AfterLegalizeTypes)
6682 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6683 SDValue Mask = MSC->getMask();
6684 SDValue Data = MSC->getValue();
6687 // If the MSCATTER data type requires splitting and the mask is provided by a
6688 // SETCC, then split both nodes and its operands before legalization. This
6689 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6690 // and enables future optimizations (e.g. min/max pattern matching on X86).
6691 if (Mask.getOpcode() != ISD::SETCC)
6694 // Check if any splitting is required.
6695 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6696 TargetLowering::TypeSplitVector)
6698 SDValue MaskLo, MaskHi, Lo, Hi;
6699 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6702 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6704 SDValue Chain = MSC->getChain();
6706 EVT MemoryVT = MSC->getMemoryVT();
6707 unsigned Alignment = MSC->getOriginalAlignment();
6709 EVT LoMemVT, HiMemVT;
6710 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6712 SDValue DataLo, DataHi;
6713 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6715 SDValue BasePtr = MSC->getBasePtr();
6716 SDValue IndexLo, IndexHi;
6717 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6719 MachineMemOperand *MMO = DAG.getMachineFunction().
6720 getMachineMemOperand(MSC->getPointerInfo(),
6721 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6722 Alignment, MSC->getAAInfo(), MSC->getRanges());
6724 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6725 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6728 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6729 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6732 AddToWorklist(Lo.getNode());
6733 AddToWorklist(Hi.getNode());
6735 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6738 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6739 if (Level >= AfterLegalizeTypes)
6742 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6743 SDValue Mask = MST->getMask();
6744 SDValue Data = MST->getValue();
6745 EVT VT = Data.getValueType();
6748 // If the MSTORE data type requires splitting and the mask is provided by a
6749 // SETCC, then split both nodes and its operands before legalization. This
6750 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6751 // and enables future optimizations (e.g. min/max pattern matching on X86).
6752 if (Mask.getOpcode() == ISD::SETCC) {
6753 // Check if any splitting is required.
6754 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6755 TargetLowering::TypeSplitVector)
6758 SDValue MaskLo, MaskHi, Lo, Hi;
6759 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6761 SDValue Chain = MST->getChain();
6762 SDValue Ptr = MST->getBasePtr();
6764 EVT MemoryVT = MST->getMemoryVT();
6765 unsigned Alignment = MST->getOriginalAlignment();
6767 // if Alignment is equal to the vector size,
6768 // take the half of it for the second part
6769 unsigned SecondHalfAlignment =
6770 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6772 EVT LoMemVT, HiMemVT;
6773 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6775 SDValue DataLo, DataHi;
6776 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6778 MachineMemOperand *MMO = DAG.getMachineFunction().
6779 getMachineMemOperand(MST->getPointerInfo(),
6780 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6781 Alignment, MST->getAAInfo(), MST->getRanges());
6783 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6784 MST->isTruncatingStore(),
6785 MST->isCompressingStore());
6787 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6788 MST->isCompressingStore());
6790 MMO = DAG.getMachineFunction().
6791 getMachineMemOperand(MST->getPointerInfo(),
6792 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6793 SecondHalfAlignment, MST->getAAInfo(),
6796 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6797 MST->isTruncatingStore(),
6798 MST->isCompressingStore());
6800 AddToWorklist(Lo.getNode());
6801 AddToWorklist(Hi.getNode());
6803 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6808 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6809 if (Level >= AfterLegalizeTypes)
6812 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
6813 SDValue Mask = MGT->getMask();
6816 // If the MGATHER result requires splitting and the mask is provided by a
6817 // SETCC, then split both nodes and its operands before legalization. This
6818 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6819 // and enables future optimizations (e.g. min/max pattern matching on X86).
6821 if (Mask.getOpcode() != ISD::SETCC)
6824 EVT VT = N->getValueType(0);
6826 // Check if any splitting is required.
6827 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6828 TargetLowering::TypeSplitVector)
6831 SDValue MaskLo, MaskHi, Lo, Hi;
6832 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6834 SDValue Src0 = MGT->getValue();
6835 SDValue Src0Lo, Src0Hi;
6836 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6839 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6841 SDValue Chain = MGT->getChain();
6842 EVT MemoryVT = MGT->getMemoryVT();
6843 unsigned Alignment = MGT->getOriginalAlignment();
6845 EVT LoMemVT, HiMemVT;
6846 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6848 SDValue BasePtr = MGT->getBasePtr();
6849 SDValue Index = MGT->getIndex();
6850 SDValue IndexLo, IndexHi;
6851 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6853 MachineMemOperand *MMO = DAG.getMachineFunction().
6854 getMachineMemOperand(MGT->getPointerInfo(),
6855 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6856 Alignment, MGT->getAAInfo(), MGT->getRanges());
6858 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6859 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6862 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6863 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6866 AddToWorklist(Lo.getNode());
6867 AddToWorklist(Hi.getNode());
6869 // Build a factor node to remember that this load is independent of the
6871 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6874 // Legalized the chain result - switch anything that used the old chain to
6876 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6878 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6880 SDValue RetOps[] = { GatherRes, Chain };
6881 return DAG.getMergeValues(RetOps, DL);
6884 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6885 if (Level >= AfterLegalizeTypes)
6888 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6889 SDValue Mask = MLD->getMask();
6892 // If the MLOAD result requires splitting and the mask is provided by a
6893 // SETCC, then split both nodes and its operands before legalization. This
6894 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6895 // and enables future optimizations (e.g. min/max pattern matching on X86).
6896 if (Mask.getOpcode() == ISD::SETCC) {
6897 EVT VT = N->getValueType(0);
6899 // Check if any splitting is required.
6900 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6901 TargetLowering::TypeSplitVector)
6904 SDValue MaskLo, MaskHi, Lo, Hi;
6905 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6907 SDValue Src0 = MLD->getSrc0();
6908 SDValue Src0Lo, Src0Hi;
6909 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6912 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6914 SDValue Chain = MLD->getChain();
6915 SDValue Ptr = MLD->getBasePtr();
6916 EVT MemoryVT = MLD->getMemoryVT();
6917 unsigned Alignment = MLD->getOriginalAlignment();
6919 // if Alignment is equal to the vector size,
6920 // take the half of it for the second part
6921 unsigned SecondHalfAlignment =
6922 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6923 Alignment/2 : Alignment;
6925 EVT LoMemVT, HiMemVT;
6926 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6928 MachineMemOperand *MMO = DAG.getMachineFunction().
6929 getMachineMemOperand(MLD->getPointerInfo(),
6930 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6931 Alignment, MLD->getAAInfo(), MLD->getRanges());
6933 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6934 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6936 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6937 MLD->isExpandingLoad());
6939 MMO = DAG.getMachineFunction().
6940 getMachineMemOperand(MLD->getPointerInfo(),
6941 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6942 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6944 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6945 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6947 AddToWorklist(Lo.getNode());
6948 AddToWorklist(Hi.getNode());
6950 // Build a factor node to remember that this load is independent of the
6952 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6955 // Legalized the chain result - switch anything that used the old chain to
6957 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6959 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6961 SDValue RetOps[] = { LoadRes, Chain };
6962 return DAG.getMergeValues(RetOps, DL);
6967 /// A vector select of 2 constant vectors can be simplified to math/logic to
6968 /// avoid a variable select instruction and possibly avoid constant loads.
6969 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
6970 SDValue Cond = N->getOperand(0);
6971 SDValue N1 = N->getOperand(1);
6972 SDValue N2 = N->getOperand(2);
6973 EVT VT = N->getValueType(0);
6974 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
6975 !TLI.convertSelectOfConstantsToMath(VT) ||
6976 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
6977 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
6980 // Check if we can use the condition value to increment/decrement a single
6981 // constant value. This simplifies a select to an add and removes a constant
6982 // load/materialization from the general case.
6983 bool AllAddOne = true;
6984 bool AllSubOne = true;
6985 unsigned Elts = VT.getVectorNumElements();
6986 for (unsigned i = 0; i != Elts; ++i) {
6987 SDValue N1Elt = N1.getOperand(i);
6988 SDValue N2Elt = N2.getOperand(i);
6989 if (N1Elt.isUndef() || N2Elt.isUndef())
6992 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
6993 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7000 // Further simplifications for the extra-special cases where the constants are
7001 // all 0 or all -1 should be implemented as folds of these patterns.
7003 if (AllAddOne || AllSubOne) {
7004 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7005 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7006 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7007 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7008 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7011 // The general case for select-of-constants:
7012 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7013 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7014 // leave that to a machine-specific pass.
7018 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7019 SDValue N0 = N->getOperand(0);
7020 SDValue N1 = N->getOperand(1);
7021 SDValue N2 = N->getOperand(2);
7024 // fold (vselect C, X, X) -> X
7028 // Canonicalize integer abs.
7029 // vselect (setg[te] X, 0), X, -X ->
7030 // vselect (setgt X, -1), X, -X ->
7031 // vselect (setl[te] X, 0), -X, X ->
7032 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7033 if (N0.getOpcode() == ISD::SETCC) {
7034 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7035 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7037 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7039 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7040 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7041 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7042 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7043 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7044 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7045 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7048 EVT VT = LHS.getValueType();
7049 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7050 return DAG.getNode(ISD::ABS, DL, VT, LHS);
7052 SDValue Shift = DAG.getNode(
7053 ISD::SRA, DL, VT, LHS,
7054 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7055 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7056 AddToWorklist(Shift.getNode());
7057 AddToWorklist(Add.getNode());
7058 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7062 if (SimplifySelectOps(N, N1, N2))
7063 return SDValue(N, 0); // Don't revisit N.
7065 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7066 if (ISD::isBuildVectorAllOnes(N0.getNode()))
7068 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7069 if (ISD::isBuildVectorAllZeros(N0.getNode()))
7072 // The ConvertSelectToConcatVector function is assuming both the above
7073 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7075 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7076 N2.getOpcode() == ISD::CONCAT_VECTORS &&
7077 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7078 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7082 if (SDValue V = foldVSelectOfConstants(N))
7088 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7089 SDValue N0 = N->getOperand(0);
7090 SDValue N1 = N->getOperand(1);
7091 SDValue N2 = N->getOperand(2);
7092 SDValue N3 = N->getOperand(3);
7093 SDValue N4 = N->getOperand(4);
7094 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7096 // fold select_cc lhs, rhs, x, x, cc -> x
7100 // Determine if the condition we're dealing with is constant
7101 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7102 CC, SDLoc(N), false)) {
7103 AddToWorklist(SCC.getNode());
7105 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7106 if (!SCCC->isNullValue())
7107 return N2; // cond always true -> true val
7109 return N3; // cond always false -> false val
7110 } else if (SCC->isUndef()) {
7111 // When the condition is UNDEF, just return the first operand. This is
7112 // coherent the DAG creation, no setcc node is created in this case
7114 } else if (SCC.getOpcode() == ISD::SETCC) {
7115 // Fold to a simpler select_cc
7116 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7117 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7122 // If we can fold this based on the true/false value, do so.
7123 if (SimplifySelectOps(N, N2, N3))
7124 return SDValue(N, 0); // Don't revisit N.
7126 // fold select_cc into other things, such as min/max/abs
7127 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7130 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7131 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
7132 cast<CondCodeSDNode>(N->getOperand(2))->get(),
7136 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7137 SDValue LHS = N->getOperand(0);
7138 SDValue RHS = N->getOperand(1);
7139 SDValue Carry = N->getOperand(2);
7140 SDValue Cond = N->getOperand(3);
7142 // If Carry is false, fold to a regular SETCC.
7143 if (Carry.getOpcode() == ISD::CARRY_FALSE)
7144 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7149 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7150 SDValue LHS = N->getOperand(0);
7151 SDValue RHS = N->getOperand(1);
7152 SDValue Carry = N->getOperand(2);
7153 SDValue Cond = N->getOperand(3);
7155 // If Carry is false, fold to a regular SETCC.
7156 if (isNullConstant(Carry))
7157 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7162 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7163 /// a build_vector of constants.
7164 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7165 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7166 /// Vector extends are not folded if operations are legal; this is to
7167 /// avoid introducing illegal build_vector dag nodes.
7168 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7169 SelectionDAG &DAG, bool LegalTypes,
7170 bool LegalOperations) {
7171 unsigned Opcode = N->getOpcode();
7172 SDValue N0 = N->getOperand(0);
7173 EVT VT = N->getValueType(0);
7175 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7176 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7177 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7178 && "Expected EXTEND dag node in input!");
7180 // fold (sext c1) -> c1
7181 // fold (zext c1) -> c1
7182 // fold (aext c1) -> c1
7183 if (isa<ConstantSDNode>(N0))
7184 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7186 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7187 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7188 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7189 EVT SVT = VT.getScalarType();
7190 if (!(VT.isVector() &&
7191 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7192 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7195 // We can fold this node into a build_vector.
7196 unsigned VTBits = SVT.getSizeInBits();
7197 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7198 SmallVector<SDValue, 8> Elts;
7199 unsigned NumElts = VT.getVectorNumElements();
7202 for (unsigned i=0; i != NumElts; ++i) {
7203 SDValue Op = N0->getOperand(i);
7204 if (Op->isUndef()) {
7205 Elts.push_back(DAG.getUNDEF(SVT));
7210 // Get the constant value and if needed trunc it to the size of the type.
7211 // Nodes like build_vector might have constants wider than the scalar type.
7212 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7213 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7214 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7216 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7219 return DAG.getBuildVector(VT, DL, Elts).getNode();
7222 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7223 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7224 // transformation. Returns true if extension are possible and the above
7225 // mentioned transformation is profitable.
7226 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7228 SmallVectorImpl<SDNode *> &ExtendNodes,
7229 const TargetLowering &TLI) {
7230 bool HasCopyToRegUses = false;
7231 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7232 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7233 UE = N0.getNode()->use_end();
7238 if (UI.getUse().getResNo() != N0.getResNo())
7240 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7241 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7242 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7243 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7244 // Sign bits will be lost after a zext.
7247 for (unsigned i = 0; i != 2; ++i) {
7248 SDValue UseOp = User->getOperand(i);
7251 if (!isa<ConstantSDNode>(UseOp))
7256 ExtendNodes.push_back(User);
7259 // If truncates aren't free and there are users we can't
7260 // extend, it isn't worthwhile.
7263 // Remember if this value is live-out.
7264 if (User->getOpcode() == ISD::CopyToReg)
7265 HasCopyToRegUses = true;
7268 if (HasCopyToRegUses) {
7269 bool BothLiveOut = false;
7270 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7272 SDUse &Use = UI.getUse();
7273 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7279 // Both unextended and extended values are live out. There had better be
7280 // a good reason for the transformation.
7281 return ExtendNodes.size();
7286 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7287 SDValue Trunc, SDValue ExtLoad,
7288 const SDLoc &DL, ISD::NodeType ExtType) {
7289 // Extend SetCC uses if necessary.
7290 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7291 SDNode *SetCC = SetCCs[i];
7292 SmallVector<SDValue, 4> Ops;
7294 for (unsigned j = 0; j != 2; ++j) {
7295 SDValue SOp = SetCC->getOperand(j);
7297 Ops.push_back(ExtLoad);
7299 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7302 Ops.push_back(SetCC->getOperand(2));
7303 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7307 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7308 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7309 SDValue N0 = N->getOperand(0);
7310 EVT DstVT = N->getValueType(0);
7311 EVT SrcVT = N0.getValueType();
7313 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7314 N->getOpcode() == ISD::ZERO_EXTEND) &&
7315 "Unexpected node type (not an extend)!");
7317 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7318 // For example, on a target with legal v4i32, but illegal v8i32, turn:
7319 // (v8i32 (sext (v8i16 (load x))))
7321 // (v8i32 (concat_vectors (v4i32 (sextload x)),
7322 // (v4i32 (sextload (x + 16)))))
7323 // Where uses of the original load, i.e.:
7325 // are replaced with:
7327 // (v8i32 (concat_vectors (v4i32 (sextload x)),
7328 // (v4i32 (sextload (x + 16)))))))
7330 // This combine is only applicable to illegal, but splittable, vectors.
7331 // All legal types, and illegal non-vector types, are handled elsewhere.
7332 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7334 if (N0->getOpcode() != ISD::LOAD)
7337 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7339 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7340 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7341 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7344 SmallVector<SDNode *, 4> SetCCs;
7345 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7348 ISD::LoadExtType ExtType =
7349 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7351 // Try to split the vector types to get down to legal types.
7352 EVT SplitSrcVT = SrcVT;
7353 EVT SplitDstVT = DstVT;
7354 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7355 SplitSrcVT.getVectorNumElements() > 1) {
7356 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7357 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7360 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7364 const unsigned NumSplits =
7365 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7366 const unsigned Stride = SplitSrcVT.getStoreSize();
7367 SmallVector<SDValue, 4> Loads;
7368 SmallVector<SDValue, 4> Chains;
7370 SDValue BasePtr = LN0->getBasePtr();
7371 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7372 const unsigned Offset = Idx * Stride;
7373 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7375 SDValue SplitLoad = DAG.getExtLoad(
7376 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7377 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7378 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7380 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7381 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7383 Loads.push_back(SplitLoad.getValue(0));
7384 Chains.push_back(SplitLoad.getValue(1));
7387 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7388 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7391 AddToWorklist(NewChain.getNode());
7393 CombineTo(N, NewValue);
7395 // Replace uses of the original load (before extension)
7396 // with a truncate of the concatenated sextloaded vectors.
7398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7399 CombineTo(N0.getNode(), Trunc, NewChain);
7400 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7401 (ISD::NodeType)N->getOpcode());
7402 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7405 /// If we're narrowing or widening the result of a vector select and the final
7406 /// size is the same size as a setcc (compare) feeding the select, then try to
7407 /// apply the cast operation to the select's operands because matching vector
7408 /// sizes for a select condition and other operands should be more efficient.
7409 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7410 unsigned CastOpcode = Cast->getOpcode();
7411 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7412 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7413 CastOpcode == ISD::FP_ROUND) &&
7414 "Unexpected opcode for vector select narrowing/widening");
7416 // We only do this transform before legal ops because the pattern may be
7417 // obfuscated by target-specific operations after legalization. Do not create
7418 // an illegal select op, however, because that may be difficult to lower.
7419 EVT VT = Cast->getValueType(0);
7420 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7423 SDValue VSel = Cast->getOperand(0);
7424 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7425 VSel.getOperand(0).getOpcode() != ISD::SETCC)
7428 // Does the setcc have the same vector size as the casted select?
7429 SDValue SetCC = VSel.getOperand(0);
7430 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7431 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7434 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7435 SDValue A = VSel.getOperand(1);
7436 SDValue B = VSel.getOperand(2);
7437 SDValue CastA, CastB;
7439 if (CastOpcode == ISD::FP_ROUND) {
7440 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7441 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7442 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7444 CastA = DAG.getNode(CastOpcode, DL, VT, A);
7445 CastB = DAG.getNode(CastOpcode, DL, VT, B);
7447 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7450 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7451 SDValue N0 = N->getOperand(0);
7452 EVT VT = N->getValueType(0);
7455 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7457 return SDValue(Res, 0);
7459 // fold (sext (sext x)) -> (sext x)
7460 // fold (sext (aext x)) -> (sext x)
7461 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7462 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7464 if (N0.getOpcode() == ISD::TRUNCATE) {
7465 // fold (sext (truncate (load x))) -> (sext (smaller load x))
7466 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7467 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7468 SDNode *oye = N0.getOperand(0).getNode();
7469 if (NarrowLoad.getNode() != N0.getNode()) {
7470 CombineTo(N0.getNode(), NarrowLoad);
7471 // CombineTo deleted the truncate, if needed, but not what's under it.
7474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7477 // See if the value being truncated is already sign extended. If so, just
7478 // eliminate the trunc/sext pair.
7479 SDValue Op = N0.getOperand(0);
7480 unsigned OpBits = Op.getScalarValueSizeInBits();
7481 unsigned MidBits = N0.getScalarValueSizeInBits();
7482 unsigned DestBits = VT.getScalarSizeInBits();
7483 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7485 if (OpBits == DestBits) {
7486 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7487 // bits, it is already ready.
7488 if (NumSignBits > DestBits-MidBits)
7490 } else if (OpBits < DestBits) {
7491 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7492 // bits, just sext from i32.
7493 if (NumSignBits > OpBits-MidBits)
7494 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7496 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7497 // bits, just truncate to i32.
7498 if (NumSignBits > OpBits-MidBits)
7499 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7502 // fold (sext (truncate x)) -> (sextinreg x).
7503 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7504 N0.getValueType())) {
7505 if (OpBits < DestBits)
7506 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7507 else if (OpBits > DestBits)
7508 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7509 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7510 DAG.getValueType(N0.getValueType()));
7514 // fold (sext (load x)) -> (sext (truncate (sextload x)))
7515 // Only generate vector extloads when 1) they're legal, and 2) they are
7516 // deemed desirable by the target.
7517 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7518 ((!LegalOperations && !VT.isVector() &&
7519 !cast<LoadSDNode>(N0)->isVolatile()) ||
7520 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7521 bool DoXform = true;
7522 SmallVector<SDNode*, 4> SetCCs;
7523 if (!N0.hasOneUse())
7524 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7526 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7528 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7529 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7530 LN0->getBasePtr(), N0.getValueType(),
7531 LN0->getMemOperand());
7532 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7533 N0.getValueType(), ExtLoad);
7534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7535 // If the load value is used only by N, replace it via CombineTo N.
7536 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7537 CombineTo(N, ExtLoad);
7539 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7541 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7542 return SDValue(N, 0);
7546 // fold (sext (load x)) to multiple smaller sextloads.
7547 // Only on illegal but splittable vectors.
7548 if (SDValue ExtLoad = CombineExtLoad(N))
7551 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7552 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7553 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7554 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7556 EVT MemVT = LN0->getMemoryVT();
7557 if ((!LegalOperations && !LN0->isVolatile()) ||
7558 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7559 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7560 LN0->getBasePtr(), MemVT,
7561 LN0->getMemOperand());
7562 CombineTo(N, ExtLoad);
7563 CombineTo(N0.getNode(),
7564 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7565 N0.getValueType(), ExtLoad),
7566 ExtLoad.getValue(1));
7567 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7571 // fold (sext (and/or/xor (load x), cst)) ->
7572 // (and/or/xor (sextload x), (sext cst))
7573 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7574 N0.getOpcode() == ISD::XOR) &&
7575 isa<LoadSDNode>(N0.getOperand(0)) &&
7576 N0.getOperand(1).getOpcode() == ISD::Constant &&
7577 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7578 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7579 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7580 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7581 bool DoXform = true;
7582 SmallVector<SDNode*, 4> SetCCs;
7583 if (!N0.hasOneUse())
7584 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7587 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7588 LN0->getChain(), LN0->getBasePtr(),
7590 LN0->getMemOperand());
7591 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7592 Mask = Mask.sext(VT.getSizeInBits());
7593 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7594 ExtLoad, DAG.getConstant(Mask, DL, VT));
7595 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7596 SDLoc(N0.getOperand(0)),
7597 N0.getOperand(0).getValueType(), ExtLoad);
7598 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7599 bool NoReplaceTruncAnd = !N0.hasOneUse();
7600 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7602 // If N0 has multiple uses, change other uses as well.
7603 if (NoReplaceTruncAnd) {
7605 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7606 CombineTo(N0.getNode(), TruncAnd);
7609 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7611 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7612 return SDValue(N,0); // Return N so it doesn't get rechecked!
7617 if (N0.getOpcode() == ISD::SETCC) {
7618 SDValue N00 = N0.getOperand(0);
7619 SDValue N01 = N0.getOperand(1);
7620 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7621 EVT N00VT = N0.getOperand(0).getValueType();
7623 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7624 // Only do this before legalize for now.
7625 if (VT.isVector() && !LegalOperations &&
7626 TLI.getBooleanContents(N00VT) ==
7627 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7628 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7629 // of the same size as the compared operands. Only optimize sext(setcc())
7630 // if this is the case.
7631 EVT SVT = getSetCCResultType(N00VT);
7633 // We know that the # elements of the results is the same as the
7634 // # elements of the compare (and the # elements of the compare result
7635 // for that matter). Check to see that they are the same size. If so,
7636 // we know that the element size of the sext'd result matches the
7637 // element size of the compare operands.
7638 if (VT.getSizeInBits() == SVT.getSizeInBits())
7639 return DAG.getSetCC(DL, VT, N00, N01, CC);
7641 // If the desired elements are smaller or larger than the source
7642 // elements, we can use a matching integer vector type and then
7643 // truncate/sign extend.
7644 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7645 if (SVT == MatchingVecType) {
7646 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7647 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7651 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7652 // Here, T can be 1 or -1, depending on the type of the setcc and
7653 // getBooleanContents().
7654 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7656 // To determine the "true" side of the select, we need to know the high bit
7657 // of the value returned by the setcc if it evaluates to true.
7658 // If the type of the setcc is i1, then the true case of the select is just
7659 // sext(i1 1), that is, -1.
7660 // If the type of the setcc is larger (say, i8) then the value of the high
7661 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7662 // of the appropriate width.
7663 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7664 : TLI.getConstTrueVal(DAG, VT, DL);
7665 SDValue Zero = DAG.getConstant(0, DL, VT);
7667 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7670 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7671 EVT SetCCVT = getSetCCResultType(N00VT);
7672 // Don't do this transform for i1 because there's a select transform
7673 // that would reverse it.
7674 // TODO: We should not do this transform at all without a target hook
7675 // because a sext is likely cheaper than a select?
7676 if (SetCCVT.getScalarSizeInBits() != 1 &&
7677 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7678 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7679 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7684 // fold (sext x) -> (zext x) if the sign bit is known zero.
7685 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7686 DAG.SignBitIsZero(N0))
7687 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7689 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7695 // isTruncateOf - If N is a truncate of some other value, return true, record
7696 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7697 // This function computes KnownBits to avoid a duplicated call to
7698 // computeKnownBits in the caller.
7699 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7701 if (N->getOpcode() == ISD::TRUNCATE) {
7702 Op = N->getOperand(0);
7703 DAG.computeKnownBits(Op, Known);
7707 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7708 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7711 SDValue Op0 = N->getOperand(0);
7712 SDValue Op1 = N->getOperand(1);
7713 assert(Op0.getValueType() == Op1.getValueType());
7715 if (isNullConstant(Op0))
7717 else if (isNullConstant(Op1))
7722 DAG.computeKnownBits(Op, Known);
7724 if (!(Known.Zero | 1).isAllOnesValue())
7730 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7731 SDValue N0 = N->getOperand(0);
7732 EVT VT = N->getValueType(0);
7734 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7736 return SDValue(Res, 0);
7738 // fold (zext (zext x)) -> (zext x)
7739 // fold (zext (aext x)) -> (zext x)
7740 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7741 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7744 // fold (zext (truncate x)) -> (zext x) or
7745 // (zext (truncate x)) -> (truncate x)
7746 // This is valid when the truncated bits of x are already zero.
7747 // FIXME: We should extend this to work for vectors too.
7750 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7751 APInt TruncatedBits =
7752 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7753 APInt(Op.getValueSizeInBits(), 0) :
7754 APInt::getBitsSet(Op.getValueSizeInBits(),
7755 N0.getValueSizeInBits(),
7756 std::min(Op.getValueSizeInBits(),
7757 VT.getSizeInBits()));
7758 if (TruncatedBits.isSubsetOf(Known.Zero))
7759 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7762 // fold (zext (truncate x)) -> (and x, mask)
7763 if (N0.getOpcode() == ISD::TRUNCATE) {
7764 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7765 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7766 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7767 SDNode *oye = N0.getOperand(0).getNode();
7768 if (NarrowLoad.getNode() != N0.getNode()) {
7769 CombineTo(N0.getNode(), NarrowLoad);
7770 // CombineTo deleted the truncate, if needed, but not what's under it.
7773 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7776 EVT SrcVT = N0.getOperand(0).getValueType();
7777 EVT MinVT = N0.getValueType();
7779 // Try to mask before the extension to avoid having to generate a larger mask,
7780 // possibly over several sub-vectors.
7781 if (SrcVT.bitsLT(VT)) {
7782 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7783 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7784 SDValue Op = N0.getOperand(0);
7785 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7786 AddToWorklist(Op.getNode());
7787 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7791 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7792 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7793 AddToWorklist(Op.getNode());
7794 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7795 // We may safely transfer the debug info describing the truncate node over
7796 // to the equivalent and operation.
7797 DAG.transferDbgValues(N0, And);
7802 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7803 // if either of the casts is not free.
7804 if (N0.getOpcode() == ISD::AND &&
7805 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7806 N0.getOperand(1).getOpcode() == ISD::Constant &&
7807 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7808 N0.getValueType()) ||
7809 !TLI.isZExtFree(N0.getValueType(), VT))) {
7810 SDValue X = N0.getOperand(0).getOperand(0);
7811 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7812 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7813 Mask = Mask.zext(VT.getSizeInBits());
7815 return DAG.getNode(ISD::AND, DL, VT,
7816 X, DAG.getConstant(Mask, DL, VT));
7819 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7820 // Only generate vector extloads when 1) they're legal, and 2) they are
7821 // deemed desirable by the target.
7822 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7823 ((!LegalOperations && !VT.isVector() &&
7824 !cast<LoadSDNode>(N0)->isVolatile()) ||
7825 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7826 bool DoXform = true;
7827 SmallVector<SDNode*, 4> SetCCs;
7828 if (!N0.hasOneUse())
7829 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7831 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7834 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7836 LN0->getBasePtr(), N0.getValueType(),
7837 LN0->getMemOperand());
7839 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7840 N0.getValueType(), ExtLoad);
7841 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7842 // If the load value is used only by N, replace it via CombineTo N.
7843 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7844 CombineTo(N, ExtLoad);
7846 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7848 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7849 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7853 // fold (zext (load x)) to multiple smaller zextloads.
7854 // Only on illegal but splittable vectors.
7855 if (SDValue ExtLoad = CombineExtLoad(N))
7858 // fold (zext (and/or/xor (load x), cst)) ->
7859 // (and/or/xor (zextload x), (zext cst))
7860 // Unless (and (load x) cst) will match as a zextload already and has
7861 // additional users.
7862 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7863 N0.getOpcode() == ISD::XOR) &&
7864 isa<LoadSDNode>(N0.getOperand(0)) &&
7865 N0.getOperand(1).getOpcode() == ISD::Constant &&
7866 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7867 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7868 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7869 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7870 bool DoXform = true;
7871 SmallVector<SDNode*, 4> SetCCs;
7872 if (!N0.hasOneUse()) {
7873 if (N0.getOpcode() == ISD::AND) {
7874 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7875 EVT LoadResultTy = AndC->getValueType(0);
7877 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT))
7881 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7882 ISD::ZERO_EXTEND, SetCCs, TLI);
7885 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7886 LN0->getChain(), LN0->getBasePtr(),
7888 LN0->getMemOperand());
7889 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7890 Mask = Mask.zext(VT.getSizeInBits());
7892 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7893 ExtLoad, DAG.getConstant(Mask, DL, VT));
7894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7895 SDLoc(N0.getOperand(0)),
7896 N0.getOperand(0).getValueType(), ExtLoad);
7897 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7898 bool NoReplaceTruncAnd = !N0.hasOneUse();
7899 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7901 // If N0 has multiple uses, change other uses as well.
7902 if (NoReplaceTruncAnd) {
7904 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7905 CombineTo(N0.getNode(), TruncAnd);
7908 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7910 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7911 return SDValue(N,0); // Return N so it doesn't get rechecked!
7916 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7917 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7918 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7919 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7920 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7921 EVT MemVT = LN0->getMemoryVT();
7922 if ((!LegalOperations && !LN0->isVolatile()) ||
7923 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7924 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7926 LN0->getBasePtr(), MemVT,
7927 LN0->getMemOperand());
7928 CombineTo(N, ExtLoad);
7929 CombineTo(N0.getNode(),
7930 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7932 ExtLoad.getValue(1));
7933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7937 if (N0.getOpcode() == ISD::SETCC) {
7938 // Only do this before legalize for now.
7939 if (!LegalOperations && VT.isVector() &&
7940 N0.getValueType().getVectorElementType() == MVT::i1) {
7941 EVT N00VT = N0.getOperand(0).getValueType();
7942 if (getSetCCResultType(N00VT) == N0.getValueType())
7945 // We know that the # elements of the results is the same as the #
7946 // elements of the compare (and the # elements of the compare result for
7947 // that matter). Check to see that they are the same size. If so, we know
7948 // that the element size of the sext'd result matches the element size of
7949 // the compare operands.
7951 SDValue VecOnes = DAG.getConstant(1, DL, VT);
7952 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7953 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7954 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7955 N0.getOperand(1), N0.getOperand(2));
7956 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7959 // If the desired elements are smaller or larger than the source
7960 // elements we can use a matching integer vector type and then
7961 // truncate/sign extend.
7962 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
7964 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7965 N0.getOperand(1), N0.getOperand(2));
7966 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7970 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7972 if (SDValue SCC = SimplifySelectCC(
7973 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7974 DAG.getConstant(0, DL, VT),
7975 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7979 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7980 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7981 isa<ConstantSDNode>(N0.getOperand(1)) &&
7982 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7984 SDValue ShAmt = N0.getOperand(1);
7985 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7986 if (N0.getOpcode() == ISD::SHL) {
7987 SDValue InnerZExt = N0.getOperand(0);
7988 // If the original shl may be shifting out bits, do not perform this
7990 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7991 InnerZExt.getOperand(0).getValueSizeInBits();
7992 if (ShAmtVal > KnownZeroBits)
7998 // Ensure that the shift amount is wide enough for the shifted value.
7999 if (VT.getSizeInBits() >= 256)
8000 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8002 return DAG.getNode(N0.getOpcode(), DL, VT,
8003 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8007 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8013 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8014 SDValue N0 = N->getOperand(0);
8015 EVT VT = N->getValueType(0);
8017 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8019 return SDValue(Res, 0);
8021 // fold (aext (aext x)) -> (aext x)
8022 // fold (aext (zext x)) -> (zext x)
8023 // fold (aext (sext x)) -> (sext x)
8024 if (N0.getOpcode() == ISD::ANY_EXTEND ||
8025 N0.getOpcode() == ISD::ZERO_EXTEND ||
8026 N0.getOpcode() == ISD::SIGN_EXTEND)
8027 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8029 // fold (aext (truncate (load x))) -> (aext (smaller load x))
8030 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8031 if (N0.getOpcode() == ISD::TRUNCATE) {
8032 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8033 SDNode *oye = N0.getOperand(0).getNode();
8034 if (NarrowLoad.getNode() != N0.getNode()) {
8035 CombineTo(N0.getNode(), NarrowLoad);
8036 // CombineTo deleted the truncate, if needed, but not what's under it.
8039 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8043 // fold (aext (truncate x))
8044 if (N0.getOpcode() == ISD::TRUNCATE)
8045 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8047 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8048 // if the trunc is not free.
8049 if (N0.getOpcode() == ISD::AND &&
8050 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8051 N0.getOperand(1).getOpcode() == ISD::Constant &&
8052 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8053 N0.getValueType())) {
8055 SDValue X = N0.getOperand(0).getOperand(0);
8056 X = DAG.getAnyExtOrTrunc(X, DL, VT);
8057 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8058 Mask = Mask.zext(VT.getSizeInBits());
8059 return DAG.getNode(ISD::AND, DL, VT,
8060 X, DAG.getConstant(Mask, DL, VT));
8063 // fold (aext (load x)) -> (aext (truncate (extload x)))
8064 // None of the supported targets knows how to perform load and any_ext
8065 // on vectors in one instruction. We only perform this transformation on
8067 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8068 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8069 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8070 bool DoXform = true;
8071 SmallVector<SDNode*, 4> SetCCs;
8072 if (!N0.hasOneUse())
8073 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
8075 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8076 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8078 LN0->getBasePtr(), N0.getValueType(),
8079 LN0->getMemOperand());
8080 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8081 N0.getValueType(), ExtLoad);
8082 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
8084 // If the load value is used only by N, replace it via CombineTo N.
8085 bool NoReplaceTrunc = N0.hasOneUse();
8086 CombineTo(N, ExtLoad);
8088 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8090 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8091 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8095 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8096 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8097 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
8098 if (N0.getOpcode() == ISD::LOAD &&
8099 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8101 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8102 ISD::LoadExtType ExtType = LN0->getExtensionType();
8103 EVT MemVT = LN0->getMemoryVT();
8104 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8105 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8106 VT, LN0->getChain(), LN0->getBasePtr(),
8107 MemVT, LN0->getMemOperand());
8108 CombineTo(N, ExtLoad);
8109 CombineTo(N0.getNode(),
8110 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8111 N0.getValueType(), ExtLoad),
8112 ExtLoad.getValue(1));
8113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8117 if (N0.getOpcode() == ISD::SETCC) {
8119 // aext(setcc) -> vsetcc
8120 // aext(setcc) -> truncate(vsetcc)
8121 // aext(setcc) -> aext(vsetcc)
8122 // Only do this before legalize for now.
8123 if (VT.isVector() && !LegalOperations) {
8124 EVT N00VT = N0.getOperand(0).getValueType();
8125 if (getSetCCResultType(N00VT) == N0.getValueType())
8128 // We know that the # elements of the results is the same as the
8129 // # elements of the compare (and the # elements of the compare result
8130 // for that matter). Check to see that they are the same size. If so,
8131 // we know that the element size of the sext'd result matches the
8132 // element size of the compare operands.
8133 if (VT.getSizeInBits() == N00VT.getSizeInBits())
8134 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8136 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8137 // If the desired elements are smaller or larger than the source
8138 // elements we can use a matching integer vector type and then
8139 // truncate/any extend
8141 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8143 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8145 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8146 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8150 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8152 if (SDValue SCC = SimplifySelectCC(
8153 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8154 DAG.getConstant(0, DL, VT),
8155 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8162 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8163 unsigned Opcode = N->getOpcode();
8164 SDValue N0 = N->getOperand(0);
8165 SDValue N1 = N->getOperand(1);
8166 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8168 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8169 if (N0.getOpcode() == Opcode &&
8170 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8173 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8174 N0.getOperand(0).getOpcode() == Opcode) {
8175 // We have an assert, truncate, assert sandwich. Make one stronger assert
8176 // by asserting on the smallest asserted type to the larger source type.
8177 // This eliminates the later assert:
8178 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8179 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8180 SDValue BigA = N0.getOperand(0);
8181 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8182 assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8183 "Asserting zero/sign-extended bits to a type larger than the "
8184 "truncated destination does not provide information");
8187 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8188 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8189 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8190 BigA.getOperand(0), MinAssertVTVal);
8191 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8197 /// If the result of a wider load is shifted to right of N bits and then
8198 /// truncated to a narrower type and where N is a multiple of number of bits of
8199 /// the narrower type, transform it to a narrower load from address + N / num of
8200 /// bits of new type. Also narrow the load if the result is masked with an AND
8201 /// to effectively produce a smaller type. If the result is to be extended, also
8202 /// fold the extension to form a extending load.
8203 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8204 unsigned Opc = N->getOpcode();
8206 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8207 SDValue N0 = N->getOperand(0);
8208 EVT VT = N->getValueType(0);
8211 // This transformation isn't valid for vector loads.
8215 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8217 if (Opc == ISD::SIGN_EXTEND_INREG) {
8218 ExtType = ISD::SEXTLOAD;
8219 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8220 } else if (Opc == ISD::SRL) {
8221 // Another special-case: SRL is basically zero-extending a narrower value,
8222 // or it maybe shifting a higher subword, half or byte into the lowest
8224 ExtType = ISD::ZEXTLOAD;
8227 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8228 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8232 uint64_t ShiftAmt = N01->getZExtValue();
8233 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8234 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8235 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8237 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8238 VT.getSizeInBits() - ShiftAmt);
8239 } else if (Opc == ISD::AND) {
8240 // An AND with a constant mask is the same as a truncate + zero-extend.
8241 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8242 if (!AndC || !AndC->getAPIntValue().isMask())
8245 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8246 ExtType = ISD::ZEXTLOAD;
8247 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8251 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8252 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8253 ShAmt = N01->getZExtValue();
8254 unsigned EVTBits = ExtVT.getSizeInBits();
8255 // Is the shift amount a multiple of size of VT?
8256 if ((ShAmt & (EVTBits-1)) == 0) {
8257 N0 = N0.getOperand(0);
8258 // Is the load width a multiple of size of VT?
8259 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8263 // At this point, we must have a load or else we can't do the transform.
8264 if (!isa<LoadSDNode>(N0)) return SDValue();
8266 // Because a SRL must be assumed to *need* to zero-extend the high bits
8267 // (as opposed to anyext the high bits), we can't combine the zextload
8268 // lowering of SRL and an sextload.
8269 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8272 // If the shift amount is larger than the input type then we're not
8273 // accessing any of the loaded bytes. If the load was a zextload/extload
8274 // then the result of the shift+trunc is zero/undef (handled elsewhere).
8275 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8280 // If the load is shifted left (and the result isn't shifted back right),
8281 // we can fold the truncate through the shift.
8282 unsigned ShLeftAmt = 0;
8283 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8284 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8285 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8286 ShLeftAmt = N01->getZExtValue();
8287 N0 = N0.getOperand(0);
8291 // If we haven't found a load, we can't narrow it.
8292 if (!isa<LoadSDNode>(N0))
8295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8296 if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8299 // For big endian targets, we need to adjust the offset to the pointer to
8300 // load the correct bytes.
8301 if (DAG.getDataLayout().isBigEndian()) {
8302 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8303 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8304 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8307 EVT PtrType = N0.getOperand(1).getValueType();
8308 uint64_t PtrOff = ShAmt / 8;
8309 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8311 // The original load itself didn't wrap, so an offset within it doesn't.
8313 Flags.setNoUnsignedWrap(true);
8314 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8315 PtrType, LN0->getBasePtr(),
8316 DAG.getConstant(PtrOff, DL, PtrType),
8318 AddToWorklist(NewPtr.getNode());
8321 if (ExtType == ISD::NON_EXTLOAD)
8322 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8323 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8324 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8326 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8327 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8328 NewAlign, LN0->getMemOperand()->getFlags(),
8331 // Replace the old load's chain with the new load's chain.
8332 WorklistRemover DeadNodes(*this);
8333 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8335 // Shift the result left, if we've swallowed a left shift.
8336 SDValue Result = Load;
8337 if (ShLeftAmt != 0) {
8338 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8339 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8341 // If the shift amount is as large as the result size (but, presumably,
8342 // no larger than the source) then the useful bits of the result are
8343 // zero; we can't simply return the shortened shift, because the result
8344 // of that operation is undefined.
8346 if (ShLeftAmt >= VT.getSizeInBits())
8347 Result = DAG.getConstant(0, DL, VT);
8349 Result = DAG.getNode(ISD::SHL, DL, VT,
8350 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8353 // Return the new loaded value.
8357 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8358 SDValue N0 = N->getOperand(0);
8359 SDValue N1 = N->getOperand(1);
8360 EVT VT = N->getValueType(0);
8361 EVT EVT = cast<VTSDNode>(N1)->getVT();
8362 unsigned VTBits = VT.getScalarSizeInBits();
8363 unsigned EVTBits = EVT.getScalarSizeInBits();
8366 return DAG.getUNDEF(VT);
8368 // fold (sext_in_reg c1) -> c1
8369 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8370 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8372 // If the input is already sign extended, just drop the extension.
8373 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8376 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8377 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8378 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8379 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8380 N0.getOperand(0), N1);
8382 // fold (sext_in_reg (sext x)) -> (sext x)
8383 // fold (sext_in_reg (aext x)) -> (sext x)
8384 // if x is small enough.
8385 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8386 SDValue N00 = N0.getOperand(0);
8387 if (N00.getScalarValueSizeInBits() <= EVTBits &&
8388 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8389 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8392 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8393 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8394 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8395 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8396 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8397 if (!LegalOperations ||
8398 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8399 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8402 // fold (sext_in_reg (zext x)) -> (sext x)
8403 // iff we are extending the source sign bit.
8404 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8405 SDValue N00 = N0.getOperand(0);
8406 if (N00.getScalarValueSizeInBits() == EVTBits &&
8407 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8408 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8411 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8412 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8413 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8415 // fold operands of sext_in_reg based on knowledge that the top bits are not
8417 if (SimplifyDemandedBits(SDValue(N, 0)))
8418 return SDValue(N, 0);
8420 // fold (sext_in_reg (load x)) -> (smaller sextload x)
8421 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8422 if (SDValue NarrowLoad = ReduceLoadWidth(N))
8425 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8426 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8427 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8428 if (N0.getOpcode() == ISD::SRL) {
8429 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8430 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8431 // We can turn this into an SRA iff the input to the SRL is already sign
8433 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8434 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8435 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8436 N0.getOperand(0), N0.getOperand(1));
8440 // fold (sext_inreg (extload x)) -> (sextload x)
8441 // If sextload is not supported by target, we can only do the combine when
8442 // load has one use. Doing otherwise can block folding the extload with other
8443 // extends that the target does support.
8444 if (ISD::isEXTLoad(N0.getNode()) &&
8445 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8446 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8447 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8449 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8450 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8451 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8453 LN0->getBasePtr(), EVT,
8454 LN0->getMemOperand());
8455 CombineTo(N, ExtLoad);
8456 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8457 AddToWorklist(ExtLoad.getNode());
8458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8460 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8461 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8463 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8464 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8465 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8466 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8467 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8469 LN0->getBasePtr(), EVT,
8470 LN0->getMemOperand());
8471 CombineTo(N, ExtLoad);
8472 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8473 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8476 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8477 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8478 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8479 N0.getOperand(1), false))
8480 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8487 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8488 SDValue N0 = N->getOperand(0);
8489 EVT VT = N->getValueType(0);
8492 return DAG.getUNDEF(VT);
8494 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8496 return SDValue(Res, 0);
8501 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8502 SDValue N0 = N->getOperand(0);
8503 EVT VT = N->getValueType(0);
8506 return DAG.getUNDEF(VT);
8508 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8510 return SDValue(Res, 0);
8515 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8516 SDValue N0 = N->getOperand(0);
8517 EVT VT = N->getValueType(0);
8518 bool isLE = DAG.getDataLayout().isLittleEndian();
8521 if (N0.getValueType() == N->getValueType(0))
8524 // fold (truncate (truncate x)) -> (truncate x)
8525 if (N0.getOpcode() == ISD::TRUNCATE)
8526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8528 // fold (truncate c1) -> c1
8529 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8530 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8531 if (C.getNode() != N)
8535 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8536 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8537 N0.getOpcode() == ISD::SIGN_EXTEND ||
8538 N0.getOpcode() == ISD::ANY_EXTEND) {
8539 // if the source is smaller than the dest, we still need an extend.
8540 if (N0.getOperand(0).getValueType().bitsLT(VT))
8541 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8542 // if the source is larger than the dest, than we just need the truncate.
8543 if (N0.getOperand(0).getValueType().bitsGT(VT))
8544 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8545 // if the source and dest are the same type, we can drop both the extend
8546 // and the truncate.
8547 return N0.getOperand(0);
8550 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8551 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8554 // Fold extract-and-trunc into a narrow extract. For example:
8555 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8556 // i32 y = TRUNCATE(i64 x)
8558 // v16i8 b = BITCAST (v2i64 val)
8559 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8561 // Note: We only run this optimization after type legalization (which often
8562 // creates this pattern) and before operation legalization after which
8563 // we need to be more careful about the vector instructions that we generate.
8564 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8565 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8566 EVT VecTy = N0.getOperand(0).getValueType();
8567 EVT ExTy = N0.getValueType();
8568 EVT TrTy = N->getValueType(0);
8570 unsigned NumElem = VecTy.getVectorNumElements();
8571 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8573 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8574 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8576 SDValue EltNo = N0->getOperand(1);
8577 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8578 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8579 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8580 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8583 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8584 DAG.getBitcast(NVT, N0.getOperand(0)),
8585 DAG.getConstant(Index, DL, IndexTy));
8589 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8590 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8591 EVT SrcVT = N0.getValueType();
8592 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8593 TLI.isTruncateFree(SrcVT, VT)) {
8595 SDValue Cond = N0.getOperand(0);
8596 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8597 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8598 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8602 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8603 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8604 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8605 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8606 SDValue Amt = N0.getOperand(1);
8608 DAG.computeKnownBits(Amt, Known);
8609 unsigned Size = VT.getScalarSizeInBits();
8610 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8612 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8614 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8615 if (AmtVT != Amt.getValueType()) {
8616 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8617 AddToWorklist(Amt.getNode());
8619 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8623 // Fold a series of buildvector, bitcast, and truncate if possible.
8625 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8626 // (2xi32 (buildvector x, y)).
8627 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8628 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8629 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8630 N0.getOperand(0).hasOneUse()) {
8631 SDValue BuildVect = N0.getOperand(0);
8632 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8633 EVT TruncVecEltTy = VT.getVectorElementType();
8635 // Check that the element types match.
8636 if (BuildVectEltTy == TruncVecEltTy) {
8637 // Now we only need to compute the offset of the truncated elements.
8638 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8639 unsigned TruncVecNumElts = VT.getVectorNumElements();
8640 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8642 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8643 "Invalid number of elements");
8645 SmallVector<SDValue, 8> Opnds;
8646 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8647 Opnds.push_back(BuildVect.getOperand(i));
8649 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8653 // See if we can simplify the input to this truncate through knowledge that
8654 // only the low bits are being used.
8655 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8656 // Currently we only perform this optimization on scalars because vectors
8657 // may have different active low bits.
8658 if (!VT.isVector()) {
8660 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8661 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8662 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8665 // fold (truncate (load x)) -> (smaller load x)
8666 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8667 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8668 if (SDValue Reduced = ReduceLoadWidth(N))
8671 // Handle the case where the load remains an extending load even
8672 // after truncation.
8673 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8674 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8675 if (!LN0->isVolatile() &&
8676 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8677 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8678 VT, LN0->getChain(), LN0->getBasePtr(),
8680 LN0->getMemOperand());
8681 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8687 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8688 // where ... are all 'undef'.
8689 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8690 SmallVector<EVT, 8> VTs;
8693 unsigned NumDefs = 0;
8695 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8696 SDValue X = N0.getOperand(i);
8702 // Stop if more than one members are non-undef.
8705 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8706 VT.getVectorElementType(),
8707 X.getValueType().getVectorNumElements()));
8711 return DAG.getUNDEF(VT);
8714 assert(V.getNode() && "The single defined operand is empty!");
8715 SmallVector<SDValue, 8> Opnds;
8716 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8718 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8721 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8722 AddToWorklist(NV.getNode());
8723 Opnds.push_back(NV);
8725 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8729 // Fold truncate of a bitcast of a vector to an extract of the low vector
8732 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8733 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8734 SDValue VecSrc = N0.getOperand(0);
8735 EVT SrcVT = VecSrc.getValueType();
8736 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8737 (!LegalOperations ||
8738 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8741 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8742 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8743 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8744 VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8748 // Simplify the operands using demanded-bits information.
8749 if (!VT.isVector() &&
8750 SimplifyDemandedBits(SDValue(N, 0)))
8751 return SDValue(N, 0);
8753 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8754 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8755 // When the adde's carry is not used.
8756 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8757 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8758 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8760 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8761 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8762 auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8763 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8766 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8772 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8773 SDValue Elt = N->getOperand(i);
8774 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8775 return Elt.getNode();
8776 return Elt.getOperand(Elt.getResNo()).getNode();
8779 /// build_pair (load, load) -> load
8780 /// if load locations are consecutive.
8781 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8782 assert(N->getOpcode() == ISD::BUILD_PAIR);
8784 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8785 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8787 // A BUILD_PAIR is always having the least significant part in elt 0 and the
8788 // most significant part in elt 1. So when combining into one large load, we
8789 // need to consider the endianness.
8790 if (DAG.getDataLayout().isBigEndian())
8791 std::swap(LD1, LD2);
8793 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8794 LD1->getAddressSpace() != LD2->getAddressSpace())
8796 EVT LD1VT = LD1->getValueType(0);
8797 unsigned LD1Bytes = LD1VT.getStoreSize();
8798 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8799 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8800 unsigned Align = LD1->getAlignment();
8801 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8802 VT.getTypeForEVT(*DAG.getContext()));
8804 if (NewAlign <= Align &&
8805 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8806 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8807 LD1->getPointerInfo(), Align);
8813 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8814 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8815 // and Lo parts; on big-endian machines it doesn't.
8816 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8819 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8820 const TargetLowering &TLI) {
8821 // If this is not a bitcast to an FP type or if the target doesn't have
8822 // IEEE754-compliant FP logic, we're done.
8823 EVT VT = N->getValueType(0);
8824 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8827 // TODO: Use splat values for the constant-checking below and remove this
8829 SDValue N0 = N->getOperand(0);
8830 EVT SourceVT = N0.getValueType();
8831 if (SourceVT.isVector())
8836 switch (N0.getOpcode()) {
8838 FPOpcode = ISD::FABS;
8839 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8842 FPOpcode = ISD::FNEG;
8843 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8845 // TODO: ISD::OR --> ISD::FNABS?
8850 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8851 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8852 SDValue LogicOp0 = N0.getOperand(0);
8853 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8854 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8855 LogicOp0.getOpcode() == ISD::BITCAST &&
8856 LogicOp0->getOperand(0).getValueType() == VT)
8857 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8862 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8863 SDValue N0 = N->getOperand(0);
8864 EVT VT = N->getValueType(0);
8867 return DAG.getUNDEF(VT);
8869 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8870 // Only do this before legalize, since afterward the target may be depending
8871 // on the bitconvert.
8872 // First check to see if this is all constant.
8874 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8876 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8878 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8879 assert(!DestEltVT.isVector() &&
8880 "Element type of vector ValueType must not be vector!");
8882 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8885 // If the input is a constant, let getNode fold it.
8886 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8887 // If we can't allow illegal operations, we need to check that this is just
8888 // a fp -> int or int -> conversion and that the resulting operation will
8890 if (!LegalOperations ||
8891 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8892 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8893 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8894 TLI.isOperationLegal(ISD::Constant, VT)))
8895 return DAG.getBitcast(VT, N0);
8898 // (conv (conv x, t1), t2) -> (conv x, t2)
8899 if (N0.getOpcode() == ISD::BITCAST)
8900 return DAG.getBitcast(VT, N0.getOperand(0));
8902 // fold (conv (load x)) -> (load (conv*)x)
8903 // If the resultant load doesn't need a higher alignment than the original!
8904 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8905 // Do not change the width of a volatile load.
8906 !cast<LoadSDNode>(N0)->isVolatile() &&
8907 // Do not remove the cast if the types differ in endian layout.
8908 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8909 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8910 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8911 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8913 unsigned OrigAlign = LN0->getAlignment();
8916 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8917 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8920 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8921 LN0->getPointerInfo(), OrigAlign,
8922 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8923 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8928 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8931 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8932 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8935 // fold (bitcast (fneg x)) ->
8936 // flipbit = signbit
8937 // (xor (bitcast x) (build_pair flipbit, flipbit))
8939 // fold (bitcast (fabs x)) ->
8940 // flipbit = (and (extract_element (bitcast x), 0), signbit)
8941 // (xor (bitcast x) (build_pair flipbit, flipbit))
8942 // This often reduces constant pool loads.
8943 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8944 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8945 N0.getNode()->hasOneUse() && VT.isInteger() &&
8946 !VT.isVector() && !N0.getValueType().isVector()) {
8947 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8948 AddToWorklist(NewConv.getNode());
8951 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8952 assert(VT.getSizeInBits() == 128);
8953 SDValue SignBit = DAG.getConstant(
8954 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8956 if (N0.getOpcode() == ISD::FNEG) {
8958 AddToWorklist(FlipBit.getNode());
8960 assert(N0.getOpcode() == ISD::FABS);
8962 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8963 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8965 AddToWorklist(Hi.getNode());
8966 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8967 AddToWorklist(FlipBit.getNode());
8970 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8971 AddToWorklist(FlipBits.getNode());
8972 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8974 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8975 if (N0.getOpcode() == ISD::FNEG)
8976 return DAG.getNode(ISD::XOR, DL, VT,
8977 NewConv, DAG.getConstant(SignBit, DL, VT));
8978 assert(N0.getOpcode() == ISD::FABS);
8979 return DAG.getNode(ISD::AND, DL, VT,
8980 NewConv, DAG.getConstant(~SignBit, DL, VT));
8983 // fold (bitconvert (fcopysign cst, x)) ->
8984 // (or (and (bitconvert x), sign), (and cst, (not sign)))
8985 // Note that we don't handle (copysign x, cst) because this can always be
8986 // folded to an fneg or fabs.
8989 // fold (bitcast (fcopysign cst, x)) ->
8990 // flipbit = (and (extract_element
8991 // (xor (bitcast cst), (bitcast x)), 0),
8993 // (xor (bitcast cst) (build_pair flipbit, flipbit))
8994 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8995 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8996 VT.isInteger() && !VT.isVector()) {
8997 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8998 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8999 if (isTypeLegal(IntXVT)) {
9000 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9001 AddToWorklist(X.getNode());
9003 // If X has a different width than the result/lhs, sext it or truncate it.
9004 unsigned VTWidth = VT.getSizeInBits();
9005 if (OrigXWidth < VTWidth) {
9006 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9007 AddToWorklist(X.getNode());
9008 } else if (OrigXWidth > VTWidth) {
9009 // To get the sign bit in the right place, we have to shift it right
9010 // before truncating.
9012 X = DAG.getNode(ISD::SRL, DL,
9013 X.getValueType(), X,
9014 DAG.getConstant(OrigXWidth-VTWidth, DL,
9016 AddToWorklist(X.getNode());
9017 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9018 AddToWorklist(X.getNode());
9021 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9022 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9023 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9024 AddToWorklist(Cst.getNode());
9025 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9026 AddToWorklist(X.getNode());
9027 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9028 AddToWorklist(XorResult.getNode());
9029 SDValue XorResult64 = DAG.getNode(
9030 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9031 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9033 AddToWorklist(XorResult64.getNode());
9035 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9036 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9037 AddToWorklist(FlipBit.getNode());
9039 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9040 AddToWorklist(FlipBits.getNode());
9041 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9043 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9044 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9045 X, DAG.getConstant(SignBit, SDLoc(X), VT));
9046 AddToWorklist(X.getNode());
9048 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9049 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9050 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9051 AddToWorklist(Cst.getNode());
9053 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9057 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9058 if (N0.getOpcode() == ISD::BUILD_PAIR)
9059 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9062 // Remove double bitcasts from shuffles - this is often a legacy of
9063 // XformToShuffleWithZero being used to combine bitmaskings (of
9064 // float vectors bitcast to integer vectors) into shuffles.
9065 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9066 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9067 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9068 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9069 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9070 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9072 // If operands are a bitcast, peek through if it casts the original VT.
9073 // If operands are a constant, just bitcast back to original VT.
9074 auto PeekThroughBitcast = [&](SDValue Op) {
9075 if (Op.getOpcode() == ISD::BITCAST &&
9076 Op.getOperand(0).getValueType() == VT)
9077 return SDValue(Op.getOperand(0));
9078 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9079 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9080 return DAG.getBitcast(VT, Op);
9084 // FIXME: If either input vector is bitcast, try to convert the shuffle to
9085 // the result type of this bitcast. This would eliminate at least one
9086 // bitcast. See the transform in InstCombine.
9087 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9088 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9093 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9094 SmallVector<int, 8> NewMask;
9095 for (int M : SVN->getMask())
9096 for (int i = 0; i != MaskScale; ++i)
9097 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9099 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9101 std::swap(SV0, SV1);
9102 ShuffleVectorSDNode::commuteMask(NewMask);
9103 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9107 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9113 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9114 EVT VT = N->getValueType(0);
9115 return CombineConsecutiveLoads(N, VT);
9118 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9119 /// operands. DstEltVT indicates the destination element value type.
9120 SDValue DAGCombiner::
9121 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9122 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9124 // If this is already the right type, we're done.
9125 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9127 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9128 unsigned DstBitSize = DstEltVT.getSizeInBits();
9130 // If this is a conversion of N elements of one type to N elements of another
9131 // type, convert each element. This handles FP<->INT cases.
9132 if (SrcBitSize == DstBitSize) {
9133 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9134 BV->getValueType(0).getVectorNumElements());
9136 // Due to the FP element handling below calling this routine recursively,
9137 // we can end up with a scalar-to-vector node here.
9138 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9139 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9140 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9142 SmallVector<SDValue, 8> Ops;
9143 for (SDValue Op : BV->op_values()) {
9144 // If the vector element type is not legal, the BUILD_VECTOR operands
9145 // are promoted and implicitly truncated. Make that explicit here.
9146 if (Op.getValueType() != SrcEltVT)
9147 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9148 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9149 AddToWorklist(Ops.back().getNode());
9151 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9154 // Otherwise, we're growing or shrinking the elements. To avoid having to
9155 // handle annoying details of growing/shrinking FP values, we convert them to
9157 if (SrcEltVT.isFloatingPoint()) {
9158 // Convert the input float vector to a int vector where the elements are the
9160 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9161 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9165 // Now we know the input is an integer vector. If the output is a FP type,
9166 // convert to integer first, then to FP of the right size.
9167 if (DstEltVT.isFloatingPoint()) {
9168 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9169 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9171 // Next, convert to FP elements of the same size.
9172 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9177 // Okay, we know the src/dst types are both integers of differing types.
9178 // Handling growing first.
9179 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9180 if (SrcBitSize < DstBitSize) {
9181 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9183 SmallVector<SDValue, 8> Ops;
9184 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9185 i += NumInputsPerOutput) {
9186 bool isLE = DAG.getDataLayout().isLittleEndian();
9187 APInt NewBits = APInt(DstBitSize, 0);
9188 bool EltIsUndef = true;
9189 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9190 // Shift the previously computed bits over.
9191 NewBits <<= SrcBitSize;
9192 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9193 if (Op.isUndef()) continue;
9196 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9197 zextOrTrunc(SrcBitSize).zext(DstBitSize);
9201 Ops.push_back(DAG.getUNDEF(DstEltVT));
9203 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9206 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9207 return DAG.getBuildVector(VT, DL, Ops);
9210 // Finally, this must be the case where we are shrinking elements: each input
9211 // turns into multiple outputs.
9212 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9213 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9214 NumOutputsPerInput*BV->getNumOperands());
9215 SmallVector<SDValue, 8> Ops;
9217 for (const SDValue &Op : BV->op_values()) {
9219 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9223 APInt OpVal = cast<ConstantSDNode>(Op)->
9224 getAPIntValue().zextOrTrunc(SrcBitSize);
9226 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9227 APInt ThisVal = OpVal.trunc(DstBitSize);
9228 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9229 OpVal.lshrInPlace(DstBitSize);
9232 // For big endian targets, swap the order of the pieces of each element.
9233 if (DAG.getDataLayout().isBigEndian())
9234 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9237 return DAG.getBuildVector(VT, DL, Ops);
9240 static bool isContractable(SDNode *N) {
9241 SDNodeFlags F = N->getFlags();
9242 return F.hasAllowContract() || F.hasUnsafeAlgebra();
9245 /// Try to perform FMA combining on a given FADD node.
9246 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9247 SDValue N0 = N->getOperand(0);
9248 SDValue N1 = N->getOperand(1);
9249 EVT VT = N->getValueType(0);
9252 const TargetOptions &Options = DAG.getTarget().Options;
9254 // Floating-point multiply-add with intermediate rounding.
9255 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9257 // Floating-point multiply-add without intermediate rounding.
9259 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9260 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9262 // No valid opcode, do not combine.
9263 if (!HasFMAD && !HasFMA)
9266 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9267 Options.UnsafeFPMath || HasFMAD);
9268 // If the addition is not contractable, do not combine.
9269 if (!AllowFusionGlobally && !isContractable(N))
9272 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9273 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9276 // Always prefer FMAD to FMA for precision.
9277 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9278 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9280 // Is the node an FMUL and contractable either due to global flags or
9282 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9283 if (N.getOpcode() != ISD::FMUL)
9285 return AllowFusionGlobally || isContractable(N.getNode());
9287 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9288 // prefer to fold the multiply with fewer uses.
9289 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9290 if (N0.getNode()->use_size() > N1.getNode()->use_size())
9294 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9295 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9296 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9297 N0.getOperand(0), N0.getOperand(1), N1);
9300 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9301 // Note: Commutes FADD operands.
9302 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9303 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9304 N1.getOperand(0), N1.getOperand(1), N0);
9307 // Look through FP_EXTEND nodes to do more combining.
9309 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9310 if (N0.getOpcode() == ISD::FP_EXTEND) {
9311 SDValue N00 = N0.getOperand(0);
9312 if (isContractableFMUL(N00) &&
9313 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9314 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9315 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9317 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9318 N00.getOperand(1)), N1);
9322 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9323 // Note: Commutes FADD operands.
9324 if (N1.getOpcode() == ISD::FP_EXTEND) {
9325 SDValue N10 = N1.getOperand(0);
9326 if (isContractableFMUL(N10) &&
9327 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9328 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9329 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9331 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9332 N10.getOperand(1)), N0);
9336 // More folding opportunities when target permits.
9338 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9339 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9340 // are currently only supported on binary nodes.
9341 if (Options.UnsafeFPMath &&
9342 N0.getOpcode() == PreferredFusedOpcode &&
9343 N0.getOperand(2).getOpcode() == ISD::FMUL &&
9344 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9345 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9346 N0.getOperand(0), N0.getOperand(1),
9347 DAG.getNode(PreferredFusedOpcode, SL, VT,
9348 N0.getOperand(2).getOperand(0),
9349 N0.getOperand(2).getOperand(1),
9353 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9354 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9355 // are currently only supported on binary nodes.
9356 if (Options.UnsafeFPMath &&
9357 N1->getOpcode() == PreferredFusedOpcode &&
9358 N1.getOperand(2).getOpcode() == ISD::FMUL &&
9359 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9360 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9361 N1.getOperand(0), N1.getOperand(1),
9362 DAG.getNode(PreferredFusedOpcode, SL, VT,
9363 N1.getOperand(2).getOperand(0),
9364 N1.getOperand(2).getOperand(1),
9369 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9370 // -> (fma x, y, (fma (fpext u), (fpext v), z))
9371 auto FoldFAddFMAFPExtFMul = [&] (
9372 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9373 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9374 DAG.getNode(PreferredFusedOpcode, SL, VT,
9375 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9376 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9379 if (N0.getOpcode() == PreferredFusedOpcode) {
9380 SDValue N02 = N0.getOperand(2);
9381 if (N02.getOpcode() == ISD::FP_EXTEND) {
9382 SDValue N020 = N02.getOperand(0);
9383 if (isContractableFMUL(N020) &&
9384 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9385 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9386 N020.getOperand(0), N020.getOperand(1),
9392 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9393 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9394 // FIXME: This turns two single-precision and one double-precision
9395 // operation into two double-precision operations, which might not be
9396 // interesting for all targets, especially GPUs.
9397 auto FoldFAddFPExtFMAFMul = [&] (
9398 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9399 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9400 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9401 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9402 DAG.getNode(PreferredFusedOpcode, SL, VT,
9403 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9404 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9407 if (N0.getOpcode() == ISD::FP_EXTEND) {
9408 SDValue N00 = N0.getOperand(0);
9409 if (N00.getOpcode() == PreferredFusedOpcode) {
9410 SDValue N002 = N00.getOperand(2);
9411 if (isContractableFMUL(N002) &&
9412 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9413 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9414 N002.getOperand(0), N002.getOperand(1),
9420 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9421 // -> (fma y, z, (fma (fpext u), (fpext v), x))
9422 if (N1.getOpcode() == PreferredFusedOpcode) {
9423 SDValue N12 = N1.getOperand(2);
9424 if (N12.getOpcode() == ISD::FP_EXTEND) {
9425 SDValue N120 = N12.getOperand(0);
9426 if (isContractableFMUL(N120) &&
9427 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9428 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9429 N120.getOperand(0), N120.getOperand(1),
9435 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9436 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9437 // FIXME: This turns two single-precision and one double-precision
9438 // operation into two double-precision operations, which might not be
9439 // interesting for all targets, especially GPUs.
9440 if (N1.getOpcode() == ISD::FP_EXTEND) {
9441 SDValue N10 = N1.getOperand(0);
9442 if (N10.getOpcode() == PreferredFusedOpcode) {
9443 SDValue N102 = N10.getOperand(2);
9444 if (isContractableFMUL(N102) &&
9445 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9446 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9447 N102.getOperand(0), N102.getOperand(1),
9457 /// Try to perform FMA combining on a given FSUB node.
9458 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9459 SDValue N0 = N->getOperand(0);
9460 SDValue N1 = N->getOperand(1);
9461 EVT VT = N->getValueType(0);
9464 const TargetOptions &Options = DAG.getTarget().Options;
9465 // Floating-point multiply-add with intermediate rounding.
9466 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9468 // Floating-point multiply-add without intermediate rounding.
9470 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9471 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9473 // No valid opcode, do not combine.
9474 if (!HasFMAD && !HasFMA)
9477 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9478 Options.UnsafeFPMath || HasFMAD);
9479 // If the subtraction is not contractable, do not combine.
9480 if (!AllowFusionGlobally && !isContractable(N))
9483 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9484 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9487 // Always prefer FMAD to FMA for precision.
9488 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9489 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9491 // Is the node an FMUL and contractable either due to global flags or
9493 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9494 if (N.getOpcode() != ISD::FMUL)
9496 return AllowFusionGlobally || isContractable(N.getNode());
9499 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9500 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9501 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9502 N0.getOperand(0), N0.getOperand(1),
9503 DAG.getNode(ISD::FNEG, SL, VT, N1));
9506 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9507 // Note: Commutes FSUB operands.
9508 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9509 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9510 DAG.getNode(ISD::FNEG, SL, VT,
9512 N1.getOperand(1), N0);
9514 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9515 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9516 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9517 SDValue N00 = N0.getOperand(0).getOperand(0);
9518 SDValue N01 = N0.getOperand(0).getOperand(1);
9519 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9520 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9521 DAG.getNode(ISD::FNEG, SL, VT, N1));
9524 // Look through FP_EXTEND nodes to do more combining.
9526 // fold (fsub (fpext (fmul x, y)), z)
9527 // -> (fma (fpext x), (fpext y), (fneg z))
9528 if (N0.getOpcode() == ISD::FP_EXTEND) {
9529 SDValue N00 = N0.getOperand(0);
9530 if (isContractableFMUL(N00) &&
9531 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9532 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9533 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9535 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9537 DAG.getNode(ISD::FNEG, SL, VT, N1));
9541 // fold (fsub x, (fpext (fmul y, z)))
9542 // -> (fma (fneg (fpext y)), (fpext z), x)
9543 // Note: Commutes FSUB operands.
9544 if (N1.getOpcode() == ISD::FP_EXTEND) {
9545 SDValue N10 = N1.getOperand(0);
9546 if (isContractableFMUL(N10) &&
9547 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9548 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9549 DAG.getNode(ISD::FNEG, SL, VT,
9550 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9551 N10.getOperand(0))),
9552 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9558 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9559 // -> (fneg (fma (fpext x), (fpext y), z))
9560 // Note: This could be removed with appropriate canonicalization of the
9561 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9562 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9563 // from implementing the canonicalization in visitFSUB.
9564 if (N0.getOpcode() == ISD::FP_EXTEND) {
9565 SDValue N00 = N0.getOperand(0);
9566 if (N00.getOpcode() == ISD::FNEG) {
9567 SDValue N000 = N00.getOperand(0);
9568 if (isContractableFMUL(N000) &&
9569 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9570 return DAG.getNode(ISD::FNEG, SL, VT,
9571 DAG.getNode(PreferredFusedOpcode, SL, VT,
9572 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9573 N000.getOperand(0)),
9574 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9575 N000.getOperand(1)),
9581 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9582 // -> (fneg (fma (fpext x)), (fpext y), z)
9583 // Note: This could be removed with appropriate canonicalization of the
9584 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9585 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9586 // from implementing the canonicalization in visitFSUB.
9587 if (N0.getOpcode() == ISD::FNEG) {
9588 SDValue N00 = N0.getOperand(0);
9589 if (N00.getOpcode() == ISD::FP_EXTEND) {
9590 SDValue N000 = N00.getOperand(0);
9591 if (isContractableFMUL(N000) &&
9592 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9593 return DAG.getNode(ISD::FNEG, SL, VT,
9594 DAG.getNode(PreferredFusedOpcode, SL, VT,
9595 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9596 N000.getOperand(0)),
9597 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9598 N000.getOperand(1)),
9604 // More folding opportunities when target permits.
9606 // fold (fsub (fma x, y, (fmul u, v)), z)
9607 // -> (fma x, y (fma u, v, (fneg z)))
9608 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9609 // are currently only supported on binary nodes.
9610 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9611 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9612 N0.getOperand(2)->hasOneUse()) {
9613 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9614 N0.getOperand(0), N0.getOperand(1),
9615 DAG.getNode(PreferredFusedOpcode, SL, VT,
9616 N0.getOperand(2).getOperand(0),
9617 N0.getOperand(2).getOperand(1),
9618 DAG.getNode(ISD::FNEG, SL, VT,
9622 // fold (fsub x, (fma y, z, (fmul u, v)))
9623 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9624 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9625 // are currently only supported on binary nodes.
9626 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9627 isContractableFMUL(N1.getOperand(2))) {
9628 SDValue N20 = N1.getOperand(2).getOperand(0);
9629 SDValue N21 = N1.getOperand(2).getOperand(1);
9630 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9631 DAG.getNode(ISD::FNEG, SL, VT,
9634 DAG.getNode(PreferredFusedOpcode, SL, VT,
9635 DAG.getNode(ISD::FNEG, SL, VT, N20),
9641 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9642 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9643 if (N0.getOpcode() == PreferredFusedOpcode) {
9644 SDValue N02 = N0.getOperand(2);
9645 if (N02.getOpcode() == ISD::FP_EXTEND) {
9646 SDValue N020 = N02.getOperand(0);
9647 if (isContractableFMUL(N020) &&
9648 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9649 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9650 N0.getOperand(0), N0.getOperand(1),
9651 DAG.getNode(PreferredFusedOpcode, SL, VT,
9652 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9653 N020.getOperand(0)),
9654 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9655 N020.getOperand(1)),
9656 DAG.getNode(ISD::FNEG, SL, VT,
9662 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9663 // -> (fma (fpext x), (fpext y),
9664 // (fma (fpext u), (fpext v), (fneg z)))
9665 // FIXME: This turns two single-precision and one double-precision
9666 // operation into two double-precision operations, which might not be
9667 // interesting for all targets, especially GPUs.
9668 if (N0.getOpcode() == ISD::FP_EXTEND) {
9669 SDValue N00 = N0.getOperand(0);
9670 if (N00.getOpcode() == PreferredFusedOpcode) {
9671 SDValue N002 = N00.getOperand(2);
9672 if (isContractableFMUL(N002) &&
9673 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9674 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9675 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9677 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9679 DAG.getNode(PreferredFusedOpcode, SL, VT,
9680 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9681 N002.getOperand(0)),
9682 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9683 N002.getOperand(1)),
9684 DAG.getNode(ISD::FNEG, SL, VT,
9690 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9691 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9692 if (N1.getOpcode() == PreferredFusedOpcode &&
9693 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9694 SDValue N120 = N1.getOperand(2).getOperand(0);
9695 if (isContractableFMUL(N120) &&
9696 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9697 SDValue N1200 = N120.getOperand(0);
9698 SDValue N1201 = N120.getOperand(1);
9699 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9700 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9702 DAG.getNode(PreferredFusedOpcode, SL, VT,
9703 DAG.getNode(ISD::FNEG, SL, VT,
9704 DAG.getNode(ISD::FP_EXTEND, SL,
9706 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9712 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9713 // -> (fma (fneg (fpext y)), (fpext z),
9714 // (fma (fneg (fpext u)), (fpext v), x))
9715 // FIXME: This turns two single-precision and one double-precision
9716 // operation into two double-precision operations, which might not be
9717 // interesting for all targets, especially GPUs.
9718 if (N1.getOpcode() == ISD::FP_EXTEND &&
9719 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9720 SDValue CvtSrc = N1.getOperand(0);
9721 SDValue N100 = CvtSrc.getOperand(0);
9722 SDValue N101 = CvtSrc.getOperand(1);
9723 SDValue N102 = CvtSrc.getOperand(2);
9724 if (isContractableFMUL(N102) &&
9725 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
9726 SDValue N1020 = N102.getOperand(0);
9727 SDValue N1021 = N102.getOperand(1);
9728 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9729 DAG.getNode(ISD::FNEG, SL, VT,
9730 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9732 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9733 DAG.getNode(PreferredFusedOpcode, SL, VT,
9734 DAG.getNode(ISD::FNEG, SL, VT,
9735 DAG.getNode(ISD::FP_EXTEND, SL,
9737 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9747 /// Try to perform FMA combining on a given FMUL node based on the distributive
9748 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9749 /// subtraction instead of addition).
9750 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9751 SDValue N0 = N->getOperand(0);
9752 SDValue N1 = N->getOperand(1);
9753 EVT VT = N->getValueType(0);
9756 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9758 const TargetOptions &Options = DAG.getTarget().Options;
9760 // The transforms below are incorrect when x == 0 and y == inf, because the
9761 // intermediate multiplication produces a nan.
9762 if (!Options.NoInfsFPMath)
9765 // Floating-point multiply-add without intermediate rounding.
9767 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9768 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9769 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9771 // Floating-point multiply-add with intermediate rounding. This can result
9772 // in a less precise result due to the changed rounding order.
9773 bool HasFMAD = Options.UnsafeFPMath &&
9774 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9776 // No valid opcode, do not combine.
9777 if (!HasFMAD && !HasFMA)
9780 // Always prefer FMAD to FMA for precision.
9781 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9782 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9784 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9785 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9786 auto FuseFADD = [&](SDValue X, SDValue Y) {
9787 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9788 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9789 if (XC1 && XC1->isExactlyValue(+1.0))
9790 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9791 if (XC1 && XC1->isExactlyValue(-1.0))
9792 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9793 DAG.getNode(ISD::FNEG, SL, VT, Y));
9798 if (SDValue FMA = FuseFADD(N0, N1))
9800 if (SDValue FMA = FuseFADD(N1, N0))
9803 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9804 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9805 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9806 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9807 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9808 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9809 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9810 if (XC0 && XC0->isExactlyValue(+1.0))
9811 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9812 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9814 if (XC0 && XC0->isExactlyValue(-1.0))
9815 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9816 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9817 DAG.getNode(ISD::FNEG, SL, VT, Y));
9819 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9820 if (XC1 && XC1->isExactlyValue(+1.0))
9821 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9822 DAG.getNode(ISD::FNEG, SL, VT, Y));
9823 if (XC1 && XC1->isExactlyValue(-1.0))
9824 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9829 if (SDValue FMA = FuseFSUB(N0, N1))
9831 if (SDValue FMA = FuseFSUB(N1, N0))
9837 static bool isFMulNegTwo(SDValue &N) {
9838 if (N.getOpcode() != ISD::FMUL)
9840 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9841 return CFP->isExactlyValue(-2.0);
9845 SDValue DAGCombiner::visitFADD(SDNode *N) {
9846 SDValue N0 = N->getOperand(0);
9847 SDValue N1 = N->getOperand(1);
9848 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9849 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9850 EVT VT = N->getValueType(0);
9852 const TargetOptions &Options = DAG.getTarget().Options;
9853 const SDNodeFlags Flags = N->getFlags();
9857 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9860 // fold (fadd c1, c2) -> c1 + c2
9862 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9864 // canonicalize constant to RHS
9865 if (N0CFP && !N1CFP)
9866 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9868 if (SDValue NewSel = foldBinOpIntoSelect(N))
9871 // fold (fadd A, (fneg B)) -> (fsub A, B)
9872 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9873 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9874 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9875 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9877 // fold (fadd (fneg A), B) -> (fsub B, A)
9878 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9879 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9880 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9881 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9883 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9884 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9885 if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9886 (isFMulNegTwo(N1) && N1.hasOneUse())) {
9887 bool N1IsFMul = isFMulNegTwo(N1);
9888 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9889 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9890 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9893 // FIXME: Auto-upgrade the target/function-level option.
9894 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9895 // fold (fadd A, 0) -> A
9896 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9901 // If 'unsafe math' is enabled, fold lots of things.
9902 if (Options.UnsafeFPMath) {
9903 // No FP constant should be created after legalization as Instruction
9904 // Selection pass has a hard time dealing with FP constants.
9905 bool AllowNewConst = (Level < AfterLegalizeDAG);
9907 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9908 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9909 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9910 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9911 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9915 // If allowed, fold (fadd (fneg x), x) -> 0.0
9916 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9917 return DAG.getConstantFP(0.0, DL, VT);
9919 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9920 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9921 return DAG.getConstantFP(0.0, DL, VT);
9923 // We can fold chains of FADD's of the same value into multiplications.
9924 // This transform is not safe in general because we are reducing the number
9925 // of rounding steps.
9926 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9927 if (N0.getOpcode() == ISD::FMUL) {
9928 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9929 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9931 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9932 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9933 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9934 DAG.getConstantFP(1.0, DL, VT), Flags);
9935 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9938 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9939 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9940 N1.getOperand(0) == N1.getOperand(1) &&
9941 N0.getOperand(0) == N1.getOperand(0)) {
9942 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9943 DAG.getConstantFP(2.0, DL, VT), Flags);
9944 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9948 if (N1.getOpcode() == ISD::FMUL) {
9949 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9950 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9952 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9953 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9954 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9955 DAG.getConstantFP(1.0, DL, VT), Flags);
9956 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9959 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9960 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9961 N0.getOperand(0) == N0.getOperand(1) &&
9962 N1.getOperand(0) == N0.getOperand(0)) {
9963 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9964 DAG.getConstantFP(2.0, DL, VT), Flags);
9965 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9969 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9970 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9971 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9972 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9973 (N0.getOperand(0) == N1)) {
9974 return DAG.getNode(ISD::FMUL, DL, VT,
9975 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9979 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9980 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9981 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9982 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9983 N1.getOperand(0) == N0) {
9984 return DAG.getNode(ISD::FMUL, DL, VT,
9985 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9989 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9990 if (AllowNewConst &&
9991 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9992 N0.getOperand(0) == N0.getOperand(1) &&
9993 N1.getOperand(0) == N1.getOperand(1) &&
9994 N0.getOperand(0) == N1.getOperand(0)) {
9995 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9996 DAG.getConstantFP(4.0, DL, VT), Flags);
9999 } // enable-unsafe-fp-math
10001 // FADD -> FMA combines:
10002 if (SDValue Fused = visitFADDForFMACombine(N)) {
10003 AddToWorklist(Fused.getNode());
10009 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10010 SDValue N0 = N->getOperand(0);
10011 SDValue N1 = N->getOperand(1);
10012 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10013 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10014 EVT VT = N->getValueType(0);
10016 const TargetOptions &Options = DAG.getTarget().Options;
10017 const SDNodeFlags Flags = N->getFlags();
10021 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10024 // fold (fsub c1, c2) -> c1-c2
10025 if (N0CFP && N1CFP)
10026 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10028 if (SDValue NewSel = foldBinOpIntoSelect(N))
10031 // fold (fsub A, (fneg B)) -> (fadd A, B)
10032 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10033 return DAG.getNode(ISD::FADD, DL, VT, N0,
10034 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10036 // FIXME: Auto-upgrade the target/function-level option.
10037 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
10038 // (fsub 0, B) -> -B
10039 if (N0CFP && N0CFP->isZero()) {
10040 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10041 return GetNegatedExpression(N1, DAG, LegalOperations);
10042 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10043 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10047 // If 'unsafe math' is enabled, fold lots of things.
10048 if (Options.UnsafeFPMath) {
10049 // (fsub A, 0) -> A
10050 if (N1CFP && N1CFP->isZero())
10053 // (fsub x, x) -> 0.0
10055 return DAG.getConstantFP(0.0f, DL, VT);
10057 // (fsub x, (fadd x, y)) -> (fneg y)
10058 // (fsub x, (fadd y, x)) -> (fneg y)
10059 if (N1.getOpcode() == ISD::FADD) {
10060 SDValue N10 = N1->getOperand(0);
10061 SDValue N11 = N1->getOperand(1);
10063 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10064 return GetNegatedExpression(N11, DAG, LegalOperations);
10066 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10067 return GetNegatedExpression(N10, DAG, LegalOperations);
10071 // FSUB -> FMA combines:
10072 if (SDValue Fused = visitFSUBForFMACombine(N)) {
10073 AddToWorklist(Fused.getNode());
10080 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10081 SDValue N0 = N->getOperand(0);
10082 SDValue N1 = N->getOperand(1);
10083 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10084 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10085 EVT VT = N->getValueType(0);
10087 const TargetOptions &Options = DAG.getTarget().Options;
10088 const SDNodeFlags Flags = N->getFlags();
10091 if (VT.isVector()) {
10092 // This just handles C1 * C2 for vectors. Other vector folds are below.
10093 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10097 // fold (fmul c1, c2) -> c1*c2
10098 if (N0CFP && N1CFP)
10099 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10101 // canonicalize constant to RHS
10102 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10103 !isConstantFPBuildVectorOrConstantFP(N1))
10104 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10106 // fold (fmul A, 1.0) -> A
10107 if (N1CFP && N1CFP->isExactlyValue(1.0))
10110 if (SDValue NewSel = foldBinOpIntoSelect(N))
10113 if (Options.UnsafeFPMath) {
10114 // fold (fmul A, 0) -> 0
10115 if (N1CFP && N1CFP->isZero())
10118 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10119 if (N0.getOpcode() == ISD::FMUL) {
10120 // Fold scalars or any vector constants (not just splats).
10121 // This fold is done in general by InstCombine, but extra fmul insts
10122 // may have been generated during lowering.
10123 SDValue N00 = N0.getOperand(0);
10124 SDValue N01 = N0.getOperand(1);
10125 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10126 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10127 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10129 // Check 1: Make sure that the first operand of the inner multiply is NOT
10130 // a constant. Otherwise, we may induce infinite looping.
10131 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10132 // Check 2: Make sure that the second operand of the inner multiply and
10133 // the second operand of the outer multiply are constants.
10134 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10135 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10136 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10137 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10142 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10143 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10144 // during an early run of DAGCombiner can prevent folding with fmuls
10145 // inserted during lowering.
10146 if (N0.getOpcode() == ISD::FADD &&
10147 (N0.getOperand(0) == N0.getOperand(1)) &&
10149 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10150 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10151 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10155 // fold (fmul X, 2.0) -> (fadd X, X)
10156 if (N1CFP && N1CFP->isExactlyValue(+2.0))
10157 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10159 // fold (fmul X, -1.0) -> (fneg X)
10160 if (N1CFP && N1CFP->isExactlyValue(-1.0))
10161 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10162 return DAG.getNode(ISD::FNEG, DL, VT, N0);
10164 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10165 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10166 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10167 // Both can be negated for free, check to see if at least one is cheaper
10169 if (LHSNeg == 2 || RHSNeg == 2)
10170 return DAG.getNode(ISD::FMUL, DL, VT,
10171 GetNegatedExpression(N0, DAG, LegalOperations),
10172 GetNegatedExpression(N1, DAG, LegalOperations),
10177 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10178 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10179 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10180 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10181 TLI.isOperationLegal(ISD::FABS, VT)) {
10182 SDValue Select = N0, X = N1;
10183 if (Select.getOpcode() != ISD::SELECT)
10184 std::swap(Select, X);
10186 SDValue Cond = Select.getOperand(0);
10187 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10188 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10190 if (TrueOpnd && FalseOpnd &&
10191 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10192 isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10193 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10194 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10203 std::swap(TrueOpnd, FalseOpnd);
10211 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10212 TLI.isOperationLegal(ISD::FNEG, VT))
10213 return DAG.getNode(ISD::FNEG, DL, VT,
10214 DAG.getNode(ISD::FABS, DL, VT, X));
10215 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10216 return DAG.getNode(ISD::FABS, DL, VT, X);
10223 // FMUL -> FMA combines:
10224 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10225 AddToWorklist(Fused.getNode());
10232 SDValue DAGCombiner::visitFMA(SDNode *N) {
10233 SDValue N0 = N->getOperand(0);
10234 SDValue N1 = N->getOperand(1);
10235 SDValue N2 = N->getOperand(2);
10236 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10237 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10238 EVT VT = N->getValueType(0);
10240 const TargetOptions &Options = DAG.getTarget().Options;
10242 // Constant fold FMA.
10243 if (isa<ConstantFPSDNode>(N0) &&
10244 isa<ConstantFPSDNode>(N1) &&
10245 isa<ConstantFPSDNode>(N2)) {
10246 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10249 if (Options.UnsafeFPMath) {
10250 if (N0CFP && N0CFP->isZero())
10252 if (N1CFP && N1CFP->isZero())
10255 // TODO: The FMA node should have flags that propagate to these nodes.
10256 if (N0CFP && N0CFP->isExactlyValue(1.0))
10257 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10258 if (N1CFP && N1CFP->isExactlyValue(1.0))
10259 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10261 // Canonicalize (fma c, x, y) -> (fma x, c, y)
10262 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10263 !isConstantFPBuildVectorOrConstantFP(N1))
10264 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10266 // TODO: FMA nodes should have flags that propagate to the created nodes.
10267 // For now, create a Flags object for use with all unsafe math transforms.
10269 Flags.setUnsafeAlgebra(true);
10271 if (Options.UnsafeFPMath) {
10272 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10273 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10274 isConstantFPBuildVectorOrConstantFP(N1) &&
10275 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10276 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10277 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10281 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10282 if (N0.getOpcode() == ISD::FMUL &&
10283 isConstantFPBuildVectorOrConstantFP(N1) &&
10284 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10285 return DAG.getNode(ISD::FMA, DL, VT,
10287 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10293 // (fma x, 1, y) -> (fadd x, y)
10294 // (fma x, -1, y) -> (fadd (fneg x), y)
10296 if (N1CFP->isExactlyValue(1.0))
10297 // TODO: The FMA node should have flags that propagate to this node.
10298 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10300 if (N1CFP->isExactlyValue(-1.0) &&
10301 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10302 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10303 AddToWorklist(RHSNeg.getNode());
10304 // TODO: The FMA node should have flags that propagate to this node.
10305 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10308 // fma (fneg x), K, y -> fma x -K, y
10309 if (N0.getOpcode() == ISD::FNEG &&
10310 (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10311 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10312 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10313 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10317 if (Options.UnsafeFPMath) {
10318 // (fma x, c, x) -> (fmul x, (c+1))
10319 if (N1CFP && N0 == N2) {
10320 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10321 DAG.getNode(ISD::FADD, DL, VT, N1,
10322 DAG.getConstantFP(1.0, DL, VT), Flags),
10326 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10327 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10328 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10329 DAG.getNode(ISD::FADD, DL, VT, N1,
10330 DAG.getConstantFP(-1.0, DL, VT), Flags),
10338 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10340 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10341 // Notice that this is not always beneficial. One reason is different targets
10342 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10343 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10344 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10345 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10346 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10347 const SDNodeFlags Flags = N->getFlags();
10348 if (!UnsafeMath && !Flags.hasAllowReciprocal())
10351 // Skip if current node is a reciprocal.
10352 SDValue N0 = N->getOperand(0);
10353 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10354 if (N0CFP && N0CFP->isExactlyValue(1.0))
10357 // Exit early if the target does not want this transform or if there can't
10358 // possibly be enough uses of the divisor to make the transform worthwhile.
10359 SDValue N1 = N->getOperand(1);
10360 unsigned MinUses = TLI.combineRepeatedFPDivisors();
10361 if (!MinUses || N1->use_size() < MinUses)
10364 // Find all FDIV users of the same divisor.
10365 // Use a set because duplicates may be present in the user list.
10366 SetVector<SDNode *> Users;
10367 for (auto *U : N1->uses()) {
10368 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10369 // This division is eligible for optimization only if global unsafe math
10370 // is enabled or if this division allows reciprocal formation.
10371 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10376 // Now that we have the actual number of divisor uses, make sure it meets
10377 // the minimum threshold specified by the target.
10378 if (Users.size() < MinUses)
10381 EVT VT = N->getValueType(0);
10383 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10384 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10386 // Dividend / Divisor -> Dividend * Reciprocal
10387 for (auto *U : Users) {
10388 SDValue Dividend = U->getOperand(0);
10389 if (Dividend != FPOne) {
10390 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10391 Reciprocal, Flags);
10392 CombineTo(U, NewNode);
10393 } else if (U != Reciprocal.getNode()) {
10394 // In the absence of fast-math-flags, this user node is always the
10395 // same node as Reciprocal, but with FMF they may be different nodes.
10396 CombineTo(U, Reciprocal);
10399 return SDValue(N, 0); // N was replaced.
10402 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10403 SDValue N0 = N->getOperand(0);
10404 SDValue N1 = N->getOperand(1);
10405 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10406 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10407 EVT VT = N->getValueType(0);
10409 const TargetOptions &Options = DAG.getTarget().Options;
10410 SDNodeFlags Flags = N->getFlags();
10414 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10417 // fold (fdiv c1, c2) -> c1/c2
10418 if (N0CFP && N1CFP)
10419 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10421 if (SDValue NewSel = foldBinOpIntoSelect(N))
10424 if (Options.UnsafeFPMath) {
10425 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10427 // Compute the reciprocal 1.0 / c2.
10428 const APFloat &N1APF = N1CFP->getValueAPF();
10429 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10430 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10431 // Only do the transform if the reciprocal is a legal fp immediate that
10432 // isn't too nasty (eg NaN, denormal, ...).
10433 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10434 (!LegalOperations ||
10435 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10436 // backend)... we should handle this gracefully after Legalize.
10437 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10438 TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10439 TLI.isFPImmLegal(Recip, VT)))
10440 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10441 DAG.getConstantFP(Recip, DL, VT), Flags);
10444 // If this FDIV is part of a reciprocal square root, it may be folded
10445 // into a target-specific square root estimate instruction.
10446 if (N1.getOpcode() == ISD::FSQRT) {
10447 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10448 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10450 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10451 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10452 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10454 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10455 AddToWorklist(RV.getNode());
10456 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10458 } else if (N1.getOpcode() == ISD::FP_ROUND &&
10459 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10460 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10462 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10463 AddToWorklist(RV.getNode());
10464 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10466 } else if (N1.getOpcode() == ISD::FMUL) {
10467 // Look through an FMUL. Even though this won't remove the FDIV directly,
10468 // it's still worthwhile to get rid of the FSQRT if possible.
10471 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10472 SqrtOp = N1.getOperand(0);
10473 OtherOp = N1.getOperand(1);
10474 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10475 SqrtOp = N1.getOperand(1);
10476 OtherOp = N1.getOperand(0);
10478 if (SqrtOp.getNode()) {
10479 // We found a FSQRT, so try to make this fold:
10480 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10481 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10482 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10483 AddToWorklist(RV.getNode());
10484 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10489 // Fold into a reciprocal estimate and multiply instead of a real divide.
10490 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10491 AddToWorklist(RV.getNode());
10492 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10496 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10497 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10498 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10499 // Both can be negated for free, check to see if at least one is cheaper
10501 if (LHSNeg == 2 || RHSNeg == 2)
10502 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10503 GetNegatedExpression(N0, DAG, LegalOperations),
10504 GetNegatedExpression(N1, DAG, LegalOperations),
10509 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10510 return CombineRepeatedDivisors;
10515 SDValue DAGCombiner::visitFREM(SDNode *N) {
10516 SDValue N0 = N->getOperand(0);
10517 SDValue N1 = N->getOperand(1);
10518 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10519 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10520 EVT VT = N->getValueType(0);
10522 // fold (frem c1, c2) -> fmod(c1,c2)
10523 if (N0CFP && N1CFP)
10524 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10526 if (SDValue NewSel = foldBinOpIntoSelect(N))
10532 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10533 if (!DAG.getTarget().Options.UnsafeFPMath)
10536 SDValue N0 = N->getOperand(0);
10537 if (TLI.isFsqrtCheap(N0, DAG))
10540 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10541 // For now, create a Flags object for use with all unsafe math transforms.
10543 Flags.setUnsafeAlgebra(true);
10544 return buildSqrtEstimate(N0, Flags);
10547 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10548 /// copysign(x, fp_round(y)) -> copysign(x, y)
10549 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10550 SDValue N1 = N->getOperand(1);
10551 if ((N1.getOpcode() == ISD::FP_EXTEND ||
10552 N1.getOpcode() == ISD::FP_ROUND)) {
10553 // Do not optimize out type conversion of f128 type yet.
10554 // For some targets like x86_64, configuration is changed to keep one f128
10555 // value in one SSE register, but instruction selection cannot handle
10556 // FCOPYSIGN on SSE registers yet.
10557 EVT N1VT = N1->getValueType(0);
10558 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10559 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10564 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10565 SDValue N0 = N->getOperand(0);
10566 SDValue N1 = N->getOperand(1);
10567 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10568 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10569 EVT VT = N->getValueType(0);
10571 if (N0CFP && N1CFP) // Constant fold
10572 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10575 const APFloat &V = N1CFP->getValueAPF();
10576 // copysign(x, c1) -> fabs(x) iff ispos(c1)
10577 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10578 if (!V.isNegative()) {
10579 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10580 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10582 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10583 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10584 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10588 // copysign(fabs(x), y) -> copysign(x, y)
10589 // copysign(fneg(x), y) -> copysign(x, y)
10590 // copysign(copysign(x,z), y) -> copysign(x, y)
10591 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10592 N0.getOpcode() == ISD::FCOPYSIGN)
10593 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10595 // copysign(x, abs(y)) -> abs(x)
10596 if (N1.getOpcode() == ISD::FABS)
10597 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10599 // copysign(x, copysign(y,z)) -> copysign(x, z)
10600 if (N1.getOpcode() == ISD::FCOPYSIGN)
10601 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10603 // copysign(x, fp_extend(y)) -> copysign(x, y)
10604 // copysign(x, fp_round(y)) -> copysign(x, y)
10605 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10606 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10611 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10612 SDValue N0 = N->getOperand(0);
10613 EVT VT = N->getValueType(0);
10614 EVT OpVT = N0.getValueType();
10616 // fold (sint_to_fp c1) -> c1fp
10617 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10618 // ...but only if the target supports immediate floating-point values
10619 (!LegalOperations ||
10620 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10621 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10623 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10624 // but UINT_TO_FP is legal on this target, try to convert.
10625 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10626 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10627 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10628 if (DAG.SignBitIsZero(N0))
10629 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10632 // The next optimizations are desirable only if SELECT_CC can be lowered.
10633 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10634 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10635 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10637 (!LegalOperations ||
10638 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10641 { N0.getOperand(0), N0.getOperand(1),
10642 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10643 N0.getOperand(2) };
10644 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10647 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10648 // (select_cc x, y, 1.0, 0.0,, cc)
10649 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10650 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10651 (!LegalOperations ||
10652 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10655 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10656 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10657 N0.getOperand(0).getOperand(2) };
10658 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10665 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10666 SDValue N0 = N->getOperand(0);
10667 EVT VT = N->getValueType(0);
10668 EVT OpVT = N0.getValueType();
10670 // fold (uint_to_fp c1) -> c1fp
10671 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10672 // ...but only if the target supports immediate floating-point values
10673 (!LegalOperations ||
10674 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10675 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10677 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10678 // but SINT_TO_FP is legal on this target, try to convert.
10679 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10680 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10681 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10682 if (DAG.SignBitIsZero(N0))
10683 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10686 // The next optimizations are desirable only if SELECT_CC can be lowered.
10687 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10688 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10689 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10690 (!LegalOperations ||
10691 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10694 { N0.getOperand(0), N0.getOperand(1),
10695 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10696 N0.getOperand(2) };
10697 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10704 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10705 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10706 SDValue N0 = N->getOperand(0);
10707 EVT VT = N->getValueType(0);
10709 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10712 SDValue Src = N0.getOperand(0);
10713 EVT SrcVT = Src.getValueType();
10714 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10715 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10717 // We can safely assume the conversion won't overflow the output range,
10718 // because (for example) (uint8_t)18293.f is undefined behavior.
10720 // Since we can assume the conversion won't overflow, our decision as to
10721 // whether the input will fit in the float should depend on the minimum
10722 // of the input range and output range.
10724 // This means this is also safe for a signed input and unsigned output, since
10725 // a negative input would lead to undefined behavior.
10726 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10727 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10728 unsigned ActualSize = std::min(InputSize, OutputSize);
10729 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10731 // We can only fold away the float conversion if the input range can be
10732 // represented exactly in the float range.
10733 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10734 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10735 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10736 : ISD::ZERO_EXTEND;
10737 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10739 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10740 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10741 return DAG.getBitcast(VT, Src);
10746 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10747 SDValue N0 = N->getOperand(0);
10748 EVT VT = N->getValueType(0);
10750 // fold (fp_to_sint c1fp) -> c1
10751 if (isConstantFPBuildVectorOrConstantFP(N0))
10752 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10754 return FoldIntToFPToInt(N, DAG);
10757 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10758 SDValue N0 = N->getOperand(0);
10759 EVT VT = N->getValueType(0);
10761 // fold (fp_to_uint c1fp) -> c1
10762 if (isConstantFPBuildVectorOrConstantFP(N0))
10763 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10765 return FoldIntToFPToInt(N, DAG);
10768 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10769 SDValue N0 = N->getOperand(0);
10770 SDValue N1 = N->getOperand(1);
10771 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10772 EVT VT = N->getValueType(0);
10774 // fold (fp_round c1fp) -> c1fp
10776 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10778 // fold (fp_round (fp_extend x)) -> x
10779 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10780 return N0.getOperand(0);
10782 // fold (fp_round (fp_round x)) -> (fp_round x)
10783 if (N0.getOpcode() == ISD::FP_ROUND) {
10784 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10785 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10787 // Skip this folding if it results in an fp_round from f80 to f16.
10789 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10790 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10791 // instructions from f32 or f64. Moreover, the first (value-preserving)
10792 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10794 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10797 // If the first fp_round isn't a value preserving truncation, it might
10798 // introduce a tie in the second fp_round, that wouldn't occur in the
10799 // single-step fp_round we want to fold to.
10800 // In other words, double rounding isn't the same as rounding.
10801 // Also, this is a value preserving truncation iff both fp_round's are.
10802 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10804 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10805 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10809 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10810 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10811 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10812 N0.getOperand(0), N1);
10813 AddToWorklist(Tmp.getNode());
10814 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10815 Tmp, N0.getOperand(1));
10818 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10824 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10825 SDValue N0 = N->getOperand(0);
10826 EVT VT = N->getValueType(0);
10827 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10828 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10830 // fold (fp_round_inreg c1fp) -> c1fp
10831 if (N0CFP && isTypeLegal(EVT)) {
10833 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10834 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10840 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10841 SDValue N0 = N->getOperand(0);
10842 EVT VT = N->getValueType(0);
10844 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10845 if (N->hasOneUse() &&
10846 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10849 // fold (fp_extend c1fp) -> c1fp
10850 if (isConstantFPBuildVectorOrConstantFP(N0))
10851 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10853 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10854 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10855 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10856 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10858 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10860 if (N0.getOpcode() == ISD::FP_ROUND
10861 && N0.getConstantOperandVal(1) == 1) {
10862 SDValue In = N0.getOperand(0);
10863 if (In.getValueType() == VT) return In;
10864 if (VT.bitsLT(In.getValueType()))
10865 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10866 In, N0.getOperand(1));
10867 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10870 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10871 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10872 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10873 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10874 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10876 LN0->getBasePtr(), N0.getValueType(),
10877 LN0->getMemOperand());
10878 CombineTo(N, ExtLoad);
10879 CombineTo(N0.getNode(),
10880 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10881 N0.getValueType(), ExtLoad,
10882 DAG.getIntPtrConstant(1, SDLoc(N0))),
10883 ExtLoad.getValue(1));
10884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10887 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10893 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10894 SDValue N0 = N->getOperand(0);
10895 EVT VT = N->getValueType(0);
10897 // fold (fceil c1) -> fceil(c1)
10898 if (isConstantFPBuildVectorOrConstantFP(N0))
10899 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10904 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10905 SDValue N0 = N->getOperand(0);
10906 EVT VT = N->getValueType(0);
10908 // fold (ftrunc c1) -> ftrunc(c1)
10909 if (isConstantFPBuildVectorOrConstantFP(N0))
10910 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10912 // fold ftrunc (known rounded int x) -> x
10913 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
10914 // likely to be generated to extract integer from a rounded floating value.
10915 switch (N0.getOpcode()) {
10919 case ISD::FNEARBYINT:
10928 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10929 SDValue N0 = N->getOperand(0);
10930 EVT VT = N->getValueType(0);
10932 // fold (ffloor c1) -> ffloor(c1)
10933 if (isConstantFPBuildVectorOrConstantFP(N0))
10934 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10939 // FIXME: FNEG and FABS have a lot in common; refactor.
10940 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10941 SDValue N0 = N->getOperand(0);
10942 EVT VT = N->getValueType(0);
10944 // Constant fold FNEG.
10945 if (isConstantFPBuildVectorOrConstantFP(N0))
10946 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10948 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10949 &DAG.getTarget().Options))
10950 return GetNegatedExpression(N0, DAG, LegalOperations);
10952 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10953 // constant pool values.
10954 if (!TLI.isFNegFree(VT) &&
10955 N0.getOpcode() == ISD::BITCAST &&
10956 N0.getNode()->hasOneUse()) {
10957 SDValue Int = N0.getOperand(0);
10958 EVT IntVT = Int.getValueType();
10959 if (IntVT.isInteger() && !IntVT.isVector()) {
10961 if (N0.getValueType().isVector()) {
10962 // For a vector, get a mask such as 0x80... per scalar element
10964 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10965 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10967 // For a scalar, just generate 0x80...
10968 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10971 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10972 DAG.getConstant(SignMask, DL0, IntVT));
10973 AddToWorklist(Int.getNode());
10974 return DAG.getBitcast(VT, Int);
10978 // (fneg (fmul c, x)) -> (fmul -c, x)
10979 if (N0.getOpcode() == ISD::FMUL &&
10980 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10981 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10983 APFloat CVal = CFP1->getValueAPF();
10985 if (Level >= AfterLegalizeDAG &&
10986 (TLI.isFPImmLegal(CVal, VT) ||
10987 TLI.isOperationLegal(ISD::ConstantFP, VT)))
10988 return DAG.getNode(
10989 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10990 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10998 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10999 SDValue N0 = N->getOperand(0);
11000 SDValue N1 = N->getOperand(1);
11001 EVT VT = N->getValueType(0);
11002 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11003 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11005 if (N0CFP && N1CFP) {
11006 const APFloat &C0 = N0CFP->getValueAPF();
11007 const APFloat &C1 = N1CFP->getValueAPF();
11008 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11011 // Canonicalize to constant on RHS.
11012 if (isConstantFPBuildVectorOrConstantFP(N0) &&
11013 !isConstantFPBuildVectorOrConstantFP(N1))
11014 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11019 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11020 SDValue N0 = N->getOperand(0);
11021 SDValue N1 = N->getOperand(1);
11022 EVT VT = N->getValueType(0);
11023 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11024 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11026 if (N0CFP && N1CFP) {
11027 const APFloat &C0 = N0CFP->getValueAPF();
11028 const APFloat &C1 = N1CFP->getValueAPF();
11029 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11032 // Canonicalize to constant on RHS.
11033 if (isConstantFPBuildVectorOrConstantFP(N0) &&
11034 !isConstantFPBuildVectorOrConstantFP(N1))
11035 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11040 SDValue DAGCombiner::visitFABS(SDNode *N) {
11041 SDValue N0 = N->getOperand(0);
11042 EVT VT = N->getValueType(0);
11044 // fold (fabs c1) -> fabs(c1)
11045 if (isConstantFPBuildVectorOrConstantFP(N0))
11046 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11048 // fold (fabs (fabs x)) -> (fabs x)
11049 if (N0.getOpcode() == ISD::FABS)
11050 return N->getOperand(0);
11052 // fold (fabs (fneg x)) -> (fabs x)
11053 // fold (fabs (fcopysign x, y)) -> (fabs x)
11054 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11055 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11057 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11058 // constant pool values.
11059 if (!TLI.isFAbsFree(VT) &&
11060 N0.getOpcode() == ISD::BITCAST &&
11061 N0.getNode()->hasOneUse()) {
11062 SDValue Int = N0.getOperand(0);
11063 EVT IntVT = Int.getValueType();
11064 if (IntVT.isInteger() && !IntVT.isVector()) {
11066 if (N0.getValueType().isVector()) {
11067 // For a vector, get a mask such as 0x7f... per scalar element
11069 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11070 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11072 // For a scalar, just generate 0x7f...
11073 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11076 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11077 DAG.getConstant(SignMask, DL, IntVT));
11078 AddToWorklist(Int.getNode());
11079 return DAG.getBitcast(N->getValueType(0), Int);
11086 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11087 SDValue Chain = N->getOperand(0);
11088 SDValue N1 = N->getOperand(1);
11089 SDValue N2 = N->getOperand(2);
11091 // If N is a constant we could fold this into a fallthrough or unconditional
11092 // branch. However that doesn't happen very often in normal code, because
11093 // Instcombine/SimplifyCFG should have handled the available opportunities.
11094 // If we did this folding here, it would be necessary to update the
11095 // MachineBasicBlock CFG, which is awkward.
11097 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11099 if (N1.getOpcode() == ISD::SETCC &&
11100 TLI.isOperationLegalOrCustom(ISD::BR_CC,
11101 N1.getOperand(0).getValueType())) {
11102 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11103 Chain, N1.getOperand(2),
11104 N1.getOperand(0), N1.getOperand(1), N2);
11107 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
11108 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
11109 (N1.getOperand(0).hasOneUse() &&
11110 N1.getOperand(0).getOpcode() == ISD::SRL))) {
11111 SDNode *Trunc = nullptr;
11112 if (N1.getOpcode() == ISD::TRUNCATE) {
11113 // Look pass the truncate.
11114 Trunc = N1.getNode();
11115 N1 = N1.getOperand(0);
11118 // Match this pattern so that we can generate simpler code:
11121 // %b = and i32 %a, 2
11122 // %c = srl i32 %b, 1
11123 // brcond i32 %c ...
11128 // %b = and i32 %a, 2
11129 // %c = setcc eq %b, 0
11132 // This applies only when the AND constant value has one bit set and the
11133 // SRL constant is equal to the log2 of the AND constant. The back-end is
11134 // smart enough to convert the result into a TEST/JMP sequence.
11135 SDValue Op0 = N1.getOperand(0);
11136 SDValue Op1 = N1.getOperand(1);
11138 if (Op0.getOpcode() == ISD::AND &&
11139 Op1.getOpcode() == ISD::Constant) {
11140 SDValue AndOp1 = Op0.getOperand(1);
11142 if (AndOp1.getOpcode() == ISD::Constant) {
11143 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11145 if (AndConst.isPowerOf2() &&
11146 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
11150 getSetCCResultType(Op0.getValueType()),
11151 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11154 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
11155 MVT::Other, Chain, SetCC, N2);
11156 // Don't add the new BRCond into the worklist or else SimplifySelectCC
11157 // will convert it back to (X & C1) >> C2.
11158 CombineTo(N, NewBRCond, false);
11159 // Truncate is dead.
11161 deleteAndRecombine(Trunc);
11162 // Replace the uses of SRL with SETCC
11163 WorklistRemover DeadNodes(*this);
11164 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11165 deleteAndRecombine(N1.getNode());
11166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11172 // Restore N1 if the above transformation doesn't match.
11173 N1 = N->getOperand(1);
11176 // Transform br(xor(x, y)) -> br(x != y)
11177 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11178 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
11179 SDNode *TheXor = N1.getNode();
11180 SDValue Op0 = TheXor->getOperand(0);
11181 SDValue Op1 = TheXor->getOperand(1);
11182 if (Op0.getOpcode() == Op1.getOpcode()) {
11183 // Avoid missing important xor optimizations.
11184 if (SDValue Tmp = visitXOR(TheXor)) {
11185 if (Tmp.getNode() != TheXor) {
11186 DEBUG(dbgs() << "\nReplacing.8 ";
11187 TheXor->dump(&DAG);
11188 dbgs() << "\nWith: ";
11189 Tmp.getNode()->dump(&DAG);
11191 WorklistRemover DeadNodes(*this);
11192 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
11193 deleteAndRecombine(TheXor);
11194 return DAG.getNode(ISD::BRCOND, SDLoc(N),
11195 MVT::Other, Chain, Tmp, N2);
11198 // visitXOR has changed XOR's operands or replaced the XOR completely,
11200 return SDValue(N, 0);
11204 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11205 bool Equal = false;
11206 if (isOneConstant(Op0) && Op0.hasOneUse() &&
11207 Op0.getOpcode() == ISD::XOR) {
11208 TheXor = Op0.getNode();
11212 EVT SetCCVT = N1.getValueType();
11214 SetCCVT = getSetCCResultType(SetCCVT);
11215 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
11218 Equal ? ISD::SETEQ : ISD::SETNE);
11219 // Replace the uses of XOR with SETCC
11220 WorklistRemover DeadNodes(*this);
11221 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11222 deleteAndRecombine(N1.getNode());
11223 return DAG.getNode(ISD::BRCOND, SDLoc(N),
11224 MVT::Other, Chain, SetCC, N2);
11231 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11233 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11234 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11235 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11237 // If N is a constant we could fold this into a fallthrough or unconditional
11238 // branch. However that doesn't happen very often in normal code, because
11239 // Instcombine/SimplifyCFG should have handled the available opportunities.
11240 // If we did this folding here, it would be necessary to update the
11241 // MachineBasicBlock CFG, which is awkward.
11243 // Use SimplifySetCC to simplify SETCC's.
11244 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11245 CondLHS, CondRHS, CC->get(), SDLoc(N),
11247 if (Simp.getNode()) AddToWorklist(Simp.getNode());
11249 // fold to a simpler setcc
11250 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11251 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11252 N->getOperand(0), Simp.getOperand(2),
11253 Simp.getOperand(0), Simp.getOperand(1),
11259 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11260 /// and that N may be folded in the load / store addressing mode.
11261 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11263 const TargetLowering &TLI) {
11267 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
11268 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11270 VT = LD->getMemoryVT();
11271 AS = LD->getAddressSpace();
11272 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
11273 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11275 VT = ST->getMemoryVT();
11276 AS = ST->getAddressSpace();
11280 TargetLowering::AddrMode AM;
11281 if (N->getOpcode() == ISD::ADD) {
11282 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11285 AM.BaseOffs = Offset->getSExtValue();
11289 } else if (N->getOpcode() == ISD::SUB) {
11290 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11293 AM.BaseOffs = -Offset->getSExtValue();
11300 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11301 VT.getTypeForEVT(*DAG.getContext()), AS);
11304 /// Try turning a load/store into a pre-indexed load/store when the base
11305 /// pointer is an add or subtract and it has other uses besides the load/store.
11306 /// After the transformation, the new indexed load/store has effectively folded
11307 /// the add/subtract in and all of its other uses are redirected to the
11308 /// new load/store.
11309 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11310 if (Level < AfterLegalizeDAG)
11313 bool isLoad = true;
11316 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11317 if (LD->isIndexed())
11319 VT = LD->getMemoryVT();
11320 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11321 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11323 Ptr = LD->getBasePtr();
11324 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11325 if (ST->isIndexed())
11327 VT = ST->getMemoryVT();
11328 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11329 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11331 Ptr = ST->getBasePtr();
11337 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11338 // out. There is no reason to make this a preinc/predec.
11339 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11340 Ptr.getNode()->hasOneUse())
11343 // Ask the target to do addressing mode selection.
11346 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11347 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11350 // Backends without true r+i pre-indexed forms may need to pass a
11351 // constant base with a variable offset so that constant coercion
11352 // will work with the patterns in canonical form.
11353 bool Swapped = false;
11354 if (isa<ConstantSDNode>(BasePtr)) {
11355 std::swap(BasePtr, Offset);
11359 // Don't create a indexed load / store with zero offset.
11360 if (isNullConstant(Offset))
11363 // Try turning it into a pre-indexed load / store except when:
11364 // 1) The new base ptr is a frame index.
11365 // 2) If N is a store and the new base ptr is either the same as or is a
11366 // predecessor of the value being stored.
11367 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11368 // that would create a cycle.
11369 // 4) All uses are load / store ops that use it as old base ptr.
11371 // Check #1. Preinc'ing a frame index would require copying the stack pointer
11372 // (plus the implicit offset) to a register to preinc anyway.
11373 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11378 SDValue Val = cast<StoreSDNode>(N)->getValue();
11379 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11383 // Caches for hasPredecessorHelper.
11384 SmallPtrSet<const SDNode *, 32> Visited;
11385 SmallVector<const SDNode *, 16> Worklist;
11386 Worklist.push_back(N);
11388 // If the offset is a constant, there may be other adds of constants that
11389 // can be folded with this one. We should do this to avoid having to keep
11390 // a copy of the original base pointer.
11391 SmallVector<SDNode *, 16> OtherUses;
11392 if (isa<ConstantSDNode>(Offset))
11393 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11394 UE = BasePtr.getNode()->use_end();
11396 SDUse &Use = UI.getUse();
11397 // Skip the use that is Ptr and uses of other results from BasePtr's
11398 // node (important for nodes that return multiple results).
11399 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11402 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11405 if (Use.getUser()->getOpcode() != ISD::ADD &&
11406 Use.getUser()->getOpcode() != ISD::SUB) {
11411 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11412 if (!isa<ConstantSDNode>(Op1)) {
11417 // FIXME: In some cases, we can be smarter about this.
11418 if (Op1.getValueType() != Offset.getValueType()) {
11423 OtherUses.push_back(Use.getUser());
11427 std::swap(BasePtr, Offset);
11429 // Now check for #3 and #4.
11430 bool RealUse = false;
11432 for (SDNode *Use : Ptr.getNode()->uses()) {
11435 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11438 // If Ptr may be folded in addressing mode of other use, then it's
11439 // not profitable to do this transformation.
11440 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11449 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11450 BasePtr, Offset, AM);
11452 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11453 BasePtr, Offset, AM);
11456 DEBUG(dbgs() << "\nReplacing.4 ";
11458 dbgs() << "\nWith: ";
11459 Result.getNode()->dump(&DAG);
11461 WorklistRemover DeadNodes(*this);
11463 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11469 // Finally, since the node is now dead, remove it from the graph.
11470 deleteAndRecombine(N);
11473 std::swap(BasePtr, Offset);
11475 // Replace other uses of BasePtr that can be updated to use Ptr
11476 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11477 unsigned OffsetIdx = 1;
11478 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11480 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11481 BasePtr.getNode() && "Expected BasePtr operand");
11483 // We need to replace ptr0 in the following expression:
11484 // x0 * offset0 + y0 * ptr0 = t0
11486 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11488 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11489 // indexed load/store and the expression that needs to be re-written.
11491 // Therefore, we have:
11492 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11494 ConstantSDNode *CN =
11495 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11496 int X0, X1, Y0, Y1;
11497 const APInt &Offset0 = CN->getAPIntValue();
11498 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11500 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11501 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11502 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11503 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11505 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11507 APInt CNV = Offset0;
11508 if (X0 < 0) CNV = -CNV;
11509 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11510 else CNV = CNV - Offset1;
11512 SDLoc DL(OtherUses[i]);
11514 // We can now generate the new expression.
11515 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11516 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11518 SDValue NewUse = DAG.getNode(Opcode,
11520 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11521 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11522 deleteAndRecombine(OtherUses[i]);
11525 // Replace the uses of Ptr with uses of the updated base value.
11526 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11527 deleteAndRecombine(Ptr.getNode());
11528 AddToWorklist(Result.getNode());
11533 /// Try to combine a load/store with a add/sub of the base pointer node into a
11534 /// post-indexed load/store. The transformation folded the add/subtract into the
11535 /// new indexed load/store effectively and all of its uses are redirected to the
11536 /// new load/store.
11537 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11538 if (Level < AfterLegalizeDAG)
11541 bool isLoad = true;
11544 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11545 if (LD->isIndexed())
11547 VT = LD->getMemoryVT();
11548 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11549 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11551 Ptr = LD->getBasePtr();
11552 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11553 if (ST->isIndexed())
11555 VT = ST->getMemoryVT();
11556 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11557 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11559 Ptr = ST->getBasePtr();
11565 if (Ptr.getNode()->hasOneUse())
11568 for (SDNode *Op : Ptr.getNode()->uses()) {
11570 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11575 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11576 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11577 // Don't create a indexed load / store with zero offset.
11578 if (isNullConstant(Offset))
11581 // Try turning it into a post-indexed load / store except when
11582 // 1) All uses are load / store ops that use it as base ptr (and
11583 // it may be folded as addressing mmode).
11584 // 2) Op must be independent of N, i.e. Op is neither a predecessor
11585 // nor a successor of N. Otherwise, if Op is folded that would
11588 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11592 bool TryNext = false;
11593 for (SDNode *Use : BasePtr.getNode()->uses()) {
11594 if (Use == Ptr.getNode())
11597 // If all the uses are load / store addresses, then don't do the
11599 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11600 bool RealUse = false;
11601 for (SDNode *UseUse : Use->uses()) {
11602 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11617 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11618 SDValue Result = isLoad
11619 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11620 BasePtr, Offset, AM)
11621 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11622 BasePtr, Offset, AM);
11623 ++PostIndexedNodes;
11625 DEBUG(dbgs() << "\nReplacing.5 ";
11627 dbgs() << "\nWith: ";
11628 Result.getNode()->dump(&DAG);
11630 WorklistRemover DeadNodes(*this);
11632 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11633 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11635 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11638 // Finally, since the node is now dead, remove it from the graph.
11639 deleteAndRecombine(N);
11641 // Replace the uses of Use with uses of the updated base value.
11642 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11643 Result.getValue(isLoad ? 1 : 0));
11644 deleteAndRecombine(Op);
11653 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11654 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11655 ISD::MemIndexedMode AM = LD->getAddressingMode();
11656 assert(AM != ISD::UNINDEXED);
11657 SDValue BP = LD->getOperand(1);
11658 SDValue Inc = LD->getOperand(2);
11660 // Some backends use TargetConstants for load offsets, but don't expect
11661 // TargetConstants in general ADD nodes. We can convert these constants into
11662 // regular Constants (if the constant is not opaque).
11663 assert((Inc.getOpcode() != ISD::TargetConstant ||
11664 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11665 "Cannot split out indexing using opaque target constants");
11666 if (Inc.getOpcode() == ISD::TargetConstant) {
11667 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11668 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11669 ConstInc->getValueType(0));
11673 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11674 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11677 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11678 LoadSDNode *LD = cast<LoadSDNode>(N);
11679 SDValue Chain = LD->getChain();
11680 SDValue Ptr = LD->getBasePtr();
11682 // If load is not volatile and there are no uses of the loaded value (and
11683 // the updated indexed value in case of indexed loads), change uses of the
11684 // chain value into uses of the chain input (i.e. delete the dead load).
11685 if (!LD->isVolatile()) {
11686 if (N->getValueType(1) == MVT::Other) {
11687 // Unindexed loads.
11688 if (!N->hasAnyUseOfValue(0)) {
11689 // It's not safe to use the two value CombineTo variant here. e.g.
11690 // v1, chain2 = load chain1, loc
11691 // v2, chain3 = load chain2, loc
11693 // Now we replace use of chain2 with chain1. This makes the second load
11694 // isomorphic to the one we are deleting, and thus makes this load live.
11695 DEBUG(dbgs() << "\nReplacing.6 ";
11697 dbgs() << "\nWith chain: ";
11698 Chain.getNode()->dump(&DAG);
11700 WorklistRemover DeadNodes(*this);
11701 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11702 AddUsersToWorklist(Chain.getNode());
11703 if (N->use_empty())
11704 deleteAndRecombine(N);
11706 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11710 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11712 // If this load has an opaque TargetConstant offset, then we cannot split
11713 // the indexing into an add/sub directly (that TargetConstant may not be
11714 // valid for a different type of node, and we cannot convert an opaque
11715 // target constant into a regular constant).
11716 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11717 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11719 if (!N->hasAnyUseOfValue(0) &&
11720 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11721 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11723 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11724 Index = SplitIndexingFromLoad(LD);
11725 // Try to fold the base pointer arithmetic into subsequent loads and
11727 AddUsersToWorklist(N);
11729 Index = DAG.getUNDEF(N->getValueType(1));
11730 DEBUG(dbgs() << "\nReplacing.7 ";
11732 dbgs() << "\nWith: ";
11733 Undef.getNode()->dump(&DAG);
11734 dbgs() << " and 2 other values\n");
11735 WorklistRemover DeadNodes(*this);
11736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11737 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11738 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11739 deleteAndRecombine(N);
11740 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11745 // If this load is directly stored, replace the load value with the stored
11747 // TODO: Handle store large -> read small portion.
11748 // TODO: Handle TRUNCSTORE/LOADEXT
11749 if (OptLevel != CodeGenOpt::None &&
11750 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11751 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11752 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11753 if (PrevST->getBasePtr() == Ptr &&
11754 PrevST->getValue().getValueType() == N->getValueType(0))
11755 return CombineTo(N, PrevST->getOperand(1), Chain);
11759 // Try to infer better alignment information than the load already has.
11760 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11761 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11762 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11763 SDValue NewLoad = DAG.getExtLoad(
11764 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11765 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11766 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11767 if (NewLoad.getNode() != N)
11768 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11773 if (LD->isUnindexed()) {
11774 // Walk up chain skipping non-aliasing memory nodes.
11775 SDValue BetterChain = FindBetterChain(N, Chain);
11777 // If there is a better chain.
11778 if (Chain != BetterChain) {
11781 // Replace the chain to void dependency.
11782 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11783 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11784 BetterChain, Ptr, LD->getMemOperand());
11786 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11787 LD->getValueType(0),
11788 BetterChain, Ptr, LD->getMemoryVT(),
11789 LD->getMemOperand());
11792 // Create token factor to keep old chain connected.
11793 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11794 MVT::Other, Chain, ReplLoad.getValue(1));
11796 // Replace uses with load result and token factor
11797 return CombineTo(N, ReplLoad.getValue(0), Token);
11801 // Try transforming N to an indexed load.
11802 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11803 return SDValue(N, 0);
11805 // Try to slice up N to more direct loads if the slices are mapped to
11806 // different register banks or pairing can take place.
11807 if (SliceUpLoad(N))
11808 return SDValue(N, 0);
11815 /// \brief Helper structure used to slice a load in smaller loads.
11816 /// Basically a slice is obtained from the following sequence:
11817 /// Origin = load Ty1, Base
11818 /// Shift = srl Ty1 Origin, CstTy Amount
11819 /// Inst = trunc Shift to Ty2
11821 /// Then, it will be rewritten into:
11822 /// Slice = load SliceTy, Base + SliceOffset
11823 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11825 /// SliceTy is deduced from the number of bits that are actually used to
11827 struct LoadedSlice {
11828 /// \brief Helper structure used to compute the cost of a slice.
11830 /// Are we optimizing for code size.
11834 unsigned Loads = 0;
11835 unsigned Truncates = 0;
11836 unsigned CrossRegisterBanksCopies = 0;
11837 unsigned ZExts = 0;
11838 unsigned Shift = 0;
11840 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
11842 /// \brief Get the cost of one isolated slice.
11843 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11844 : ForCodeSize(ForCodeSize), Loads(1) {
11845 EVT TruncType = LS.Inst->getValueType(0);
11846 EVT LoadedType = LS.getLoadedType();
11847 if (TruncType != LoadedType &&
11848 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11852 /// \brief Account for slicing gain in the current cost.
11853 /// Slicing provide a few gains like removing a shift or a
11854 /// truncate. This method allows to grow the cost of the original
11855 /// load with the gain from this slice.
11856 void addSliceGain(const LoadedSlice &LS) {
11857 // Each slice saves a truncate.
11858 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11859 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11860 LS.Inst->getValueType(0)))
11862 // If there is a shift amount, this slice gets rid of it.
11865 // If this slice can merge a cross register bank copy, account for it.
11866 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11867 ++CrossRegisterBanksCopies;
11870 Cost &operator+=(const Cost &RHS) {
11871 Loads += RHS.Loads;
11872 Truncates += RHS.Truncates;
11873 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11874 ZExts += RHS.ZExts;
11875 Shift += RHS.Shift;
11879 bool operator==(const Cost &RHS) const {
11880 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11881 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11882 ZExts == RHS.ZExts && Shift == RHS.Shift;
11885 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11887 bool operator<(const Cost &RHS) const {
11888 // Assume cross register banks copies are as expensive as loads.
11889 // FIXME: Do we want some more target hooks?
11890 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11891 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11892 // Unless we are optimizing for code size, consider the
11893 // expensive operation first.
11894 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11895 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11896 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11897 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11900 bool operator>(const Cost &RHS) const { return RHS < *this; }
11902 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11904 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11907 // The last instruction that represent the slice. This should be a
11908 // truncate instruction.
11911 // The original load instruction.
11912 LoadSDNode *Origin;
11914 // The right shift amount in bits from the original load.
11917 // The DAG from which Origin came from.
11918 // This is used to get some contextual information about legal types, etc.
11921 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11922 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11923 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11925 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11926 /// \return Result is \p BitWidth and has used bits set to 1 and
11927 /// not used bits set to 0.
11928 APInt getUsedBits() const {
11929 // Reproduce the trunc(lshr) sequence:
11930 // - Start from the truncated value.
11931 // - Zero extend to the desired bit width.
11933 assert(Origin && "No original load to compare against.");
11934 unsigned BitWidth = Origin->getValueSizeInBits(0);
11935 assert(Inst && "This slice is not bound to an instruction");
11936 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11937 "Extracted slice is bigger than the whole type!");
11938 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11939 UsedBits.setAllBits();
11940 UsedBits = UsedBits.zext(BitWidth);
11941 UsedBits <<= Shift;
11945 /// \brief Get the size of the slice to be loaded in bytes.
11946 unsigned getLoadedSize() const {
11947 unsigned SliceSize = getUsedBits().countPopulation();
11948 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11949 return SliceSize / 8;
11952 /// \brief Get the type that will be loaded for this slice.
11953 /// Note: This may not be the final type for the slice.
11954 EVT getLoadedType() const {
11955 assert(DAG && "Missing context");
11956 LLVMContext &Ctxt = *DAG->getContext();
11957 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11960 /// \brief Get the alignment of the load used for this slice.
11961 unsigned getAlignment() const {
11962 unsigned Alignment = Origin->getAlignment();
11963 unsigned Offset = getOffsetFromBase();
11965 Alignment = MinAlign(Alignment, Alignment + Offset);
11969 /// \brief Check if this slice can be rewritten with legal operations.
11970 bool isLegal() const {
11971 // An invalid slice is not legal.
11972 if (!Origin || !Inst || !DAG)
11975 // Offsets are for indexed load only, we do not handle that.
11976 if (!Origin->getOffset().isUndef())
11979 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11981 // Check that the type is legal.
11982 EVT SliceType = getLoadedType();
11983 if (!TLI.isTypeLegal(SliceType))
11986 // Check that the load is legal for this type.
11987 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11990 // Check that the offset can be computed.
11991 // 1. Check its type.
11992 EVT PtrType = Origin->getBasePtr().getValueType();
11993 if (PtrType == MVT::Untyped || PtrType.isExtended())
11996 // 2. Check that it fits in the immediate.
11997 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12000 // 3. Check that the computation is legal.
12001 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12004 // Check that the zext is legal if it needs one.
12005 EVT TruncateType = Inst->getValueType(0);
12006 if (TruncateType != SliceType &&
12007 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12013 /// \brief Get the offset in bytes of this slice in the original chunk of
12015 /// \pre DAG != nullptr.
12016 uint64_t getOffsetFromBase() const {
12017 assert(DAG && "Missing context.");
12018 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12019 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12020 uint64_t Offset = Shift / 8;
12021 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12022 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12023 "The size of the original loaded type is not a multiple of a"
12025 // If Offset is bigger than TySizeInBytes, it means we are loading all
12026 // zeros. This should have been optimized before in the process.
12027 assert(TySizeInBytes > Offset &&
12028 "Invalid shift amount for given loaded size");
12030 Offset = TySizeInBytes - Offset - getLoadedSize();
12034 /// \brief Generate the sequence of instructions to load the slice
12035 /// represented by this object and redirect the uses of this slice to
12036 /// this new sequence of instructions.
12037 /// \pre this->Inst && this->Origin are valid Instructions and this
12038 /// object passed the legal check: LoadedSlice::isLegal returned true.
12039 /// \return The last instruction of the sequence used to load the slice.
12040 SDValue loadSlice() const {
12041 assert(Inst && Origin && "Unable to replace a non-existing slice.");
12042 const SDValue &OldBaseAddr = Origin->getBasePtr();
12043 SDValue BaseAddr = OldBaseAddr;
12044 // Get the offset in that chunk of bytes w.r.t. the endianness.
12045 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12046 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12048 // BaseAddr = BaseAddr + Offset.
12049 EVT ArithType = BaseAddr.getValueType();
12051 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12052 DAG->getConstant(Offset, DL, ArithType));
12055 // Create the type of the loaded slice according to its size.
12056 EVT SliceType = getLoadedType();
12058 // Create the load for the slice.
12060 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12061 Origin->getPointerInfo().getWithOffset(Offset),
12062 getAlignment(), Origin->getMemOperand()->getFlags());
12063 // If the final type is not the same as the loaded type, this means that
12064 // we have to pad with zero. Create a zero extend for that.
12065 EVT FinalType = Inst->getValueType(0);
12066 if (SliceType != FinalType)
12068 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12072 /// \brief Check if this slice can be merged with an expensive cross register
12073 /// bank copy. E.g.,
12075 /// f = bitcast i32 i to float
12076 bool canMergeExpensiveCrossRegisterBankCopy() const {
12077 if (!Inst || !Inst->hasOneUse())
12079 SDNode *Use = *Inst->use_begin();
12080 if (Use->getOpcode() != ISD::BITCAST)
12082 assert(DAG && "Missing context");
12083 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12084 EVT ResVT = Use->getValueType(0);
12085 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12086 const TargetRegisterClass *ArgRC =
12087 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12088 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12091 // At this point, we know that we perform a cross-register-bank copy.
12092 // Check if it is expensive.
12093 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12094 // Assume bitcasts are cheap, unless both register classes do not
12095 // explicitly share a common sub class.
12096 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12099 // Check if it will be merged with the load.
12100 // 1. Check the alignment constraint.
12101 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12102 ResVT.getTypeForEVT(*DAG->getContext()));
12104 if (RequiredAlignment > getAlignment())
12107 // 2. Check that the load is a legal operation for that type.
12108 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12111 // 3. Check that we do not have a zext in the way.
12112 if (Inst->getValueType(0) != getLoadedType())
12119 } // end anonymous namespace
12121 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
12122 /// \p UsedBits looks like 0..0 1..1 0..0.
12123 static bool areUsedBitsDense(const APInt &UsedBits) {
12124 // If all the bits are one, this is dense!
12125 if (UsedBits.isAllOnesValue())
12128 // Get rid of the unused bits on the right.
12129 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12130 // Get rid of the unused bits on the left.
12131 if (NarrowedUsedBits.countLeadingZeros())
12132 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12133 // Check that the chunk of bits is completely used.
12134 return NarrowedUsedBits.isAllOnesValue();
12137 /// \brief Check whether or not \p First and \p Second are next to each other
12138 /// in memory. This means that there is no hole between the bits loaded
12139 /// by \p First and the bits loaded by \p Second.
12140 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12141 const LoadedSlice &Second) {
12142 assert(First.Origin == Second.Origin && First.Origin &&
12143 "Unable to match different memory origins.");
12144 APInt UsedBits = First.getUsedBits();
12145 assert((UsedBits & Second.getUsedBits()) == 0 &&
12146 "Slices are not supposed to overlap.");
12147 UsedBits |= Second.getUsedBits();
12148 return areUsedBitsDense(UsedBits);
12151 /// \brief Adjust the \p GlobalLSCost according to the target
12152 /// paring capabilities and the layout of the slices.
12153 /// \pre \p GlobalLSCost should account for at least as many loads as
12154 /// there is in the slices in \p LoadedSlices.
12155 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12156 LoadedSlice::Cost &GlobalLSCost) {
12157 unsigned NumberOfSlices = LoadedSlices.size();
12158 // If there is less than 2 elements, no pairing is possible.
12159 if (NumberOfSlices < 2)
12162 // Sort the slices so that elements that are likely to be next to each
12163 // other in memory are next to each other in the list.
12164 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
12165 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12166 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12167 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12169 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12170 // First (resp. Second) is the first (resp. Second) potentially candidate
12171 // to be placed in a paired load.
12172 const LoadedSlice *First = nullptr;
12173 const LoadedSlice *Second = nullptr;
12174 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12175 // Set the beginning of the pair.
12177 Second = &LoadedSlices[CurrSlice];
12179 // If First is NULL, it means we start a new pair.
12180 // Get to the next slice.
12184 EVT LoadedType = First->getLoadedType();
12186 // If the types of the slices are different, we cannot pair them.
12187 if (LoadedType != Second->getLoadedType())
12190 // Check if the target supplies paired loads for this type.
12191 unsigned RequiredAlignment = 0;
12192 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12193 // move to the next pair, this type is hopeless.
12197 // Check if we meet the alignment requirement.
12198 if (RequiredAlignment > First->getAlignment())
12201 // Check that both loads are next to each other in memory.
12202 if (!areSlicesNextToEachOther(*First, *Second))
12205 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12206 --GlobalLSCost.Loads;
12207 // Move to the next pair.
12212 /// \brief Check the profitability of all involved LoadedSlice.
12213 /// Currently, it is considered profitable if there is exactly two
12214 /// involved slices (1) which are (2) next to each other in memory, and
12215 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12217 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12218 /// the elements themselves.
12220 /// FIXME: When the cost model will be mature enough, we can relax
12221 /// constraints (1) and (2).
12222 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12223 const APInt &UsedBits, bool ForCodeSize) {
12224 unsigned NumberOfSlices = LoadedSlices.size();
12225 if (StressLoadSlicing)
12226 return NumberOfSlices > 1;
12229 if (NumberOfSlices != 2)
12233 if (!areUsedBitsDense(UsedBits))
12237 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12238 // The original code has one big load.
12239 OrigCost.Loads = 1;
12240 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12241 const LoadedSlice &LS = LoadedSlices[CurrSlice];
12242 // Accumulate the cost of all the slices.
12243 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12244 GlobalSlicingCost += SliceCost;
12246 // Account as cost in the original configuration the gain obtained
12247 // with the current slices.
12248 OrigCost.addSliceGain(LS);
12251 // If the target supports paired load, adjust the cost accordingly.
12252 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12253 return OrigCost > GlobalSlicingCost;
12256 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12257 /// operations, split it in the various pieces being extracted.
12259 /// This sort of thing is introduced by SROA.
12260 /// This slicing takes care not to insert overlapping loads.
12261 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12262 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12263 if (Level < AfterLegalizeDAG)
12266 LoadSDNode *LD = cast<LoadSDNode>(N);
12267 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12268 !LD->getValueType(0).isInteger())
12271 // Keep track of already used bits to detect overlapping values.
12272 // In that case, we will just abort the transformation.
12273 APInt UsedBits(LD->getValueSizeInBits(0), 0);
12275 SmallVector<LoadedSlice, 4> LoadedSlices;
12277 // Check if this load is used as several smaller chunks of bits.
12278 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12279 // of computation for each trunc.
12280 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12281 UI != UIEnd; ++UI) {
12282 // Skip the uses of the chain.
12283 if (UI.getUse().getResNo() != 0)
12286 SDNode *User = *UI;
12287 unsigned Shift = 0;
12289 // Check if this is a trunc(lshr).
12290 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12291 isa<ConstantSDNode>(User->getOperand(1))) {
12292 Shift = User->getConstantOperandVal(1);
12293 User = *User->use_begin();
12296 // At this point, User is a Truncate, iff we encountered, trunc or
12298 if (User->getOpcode() != ISD::TRUNCATE)
12301 // The width of the type must be a power of 2 and greater than 8-bits.
12302 // Otherwise the load cannot be represented in LLVM IR.
12303 // Moreover, if we shifted with a non-8-bits multiple, the slice
12304 // will be across several bytes. We do not support that.
12305 unsigned Width = User->getValueSizeInBits(0);
12306 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12309 // Build the slice for this chain of computations.
12310 LoadedSlice LS(User, LD, Shift, &DAG);
12311 APInt CurrentUsedBits = LS.getUsedBits();
12313 // Check if this slice overlaps with another.
12314 if ((CurrentUsedBits & UsedBits) != 0)
12316 // Update the bits used globally.
12317 UsedBits |= CurrentUsedBits;
12319 // Check if the new slice would be legal.
12323 // Record the slice.
12324 LoadedSlices.push_back(LS);
12327 // Abort slicing if it does not seem to be profitable.
12328 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12333 // Rewrite each chain to use an independent load.
12334 // By construction, each chain can be represented by a unique load.
12336 // Prepare the argument for the new token factor for all the slices.
12337 SmallVector<SDValue, 8> ArgChains;
12338 for (SmallVectorImpl<LoadedSlice>::const_iterator
12339 LSIt = LoadedSlices.begin(),
12340 LSItEnd = LoadedSlices.end();
12341 LSIt != LSItEnd; ++LSIt) {
12342 SDValue SliceInst = LSIt->loadSlice();
12343 CombineTo(LSIt->Inst, SliceInst, true);
12344 if (SliceInst.getOpcode() != ISD::LOAD)
12345 SliceInst = SliceInst.getOperand(0);
12346 assert(SliceInst->getOpcode() == ISD::LOAD &&
12347 "It takes more than a zext to get to the loaded slice!!");
12348 ArgChains.push_back(SliceInst.getValue(1));
12351 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12353 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12354 AddToWorklist(Chain.getNode());
12358 /// Check to see if V is (and load (ptr), imm), where the load is having
12359 /// specific bytes cleared out. If so, return the byte size being masked out
12360 /// and the shift amount.
12361 static std::pair<unsigned, unsigned>
12362 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12363 std::pair<unsigned, unsigned> Result(0, 0);
12365 // Check for the structure we're looking for.
12366 if (V->getOpcode() != ISD::AND ||
12367 !isa<ConstantSDNode>(V->getOperand(1)) ||
12368 !ISD::isNormalLoad(V->getOperand(0).getNode()))
12371 // Check the chain and pointer.
12372 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12373 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
12375 // The store should be chained directly to the load or be an operand of a
12377 if (LD == Chain.getNode())
12379 else if (Chain->getOpcode() != ISD::TokenFactor)
12380 return Result; // Fail.
12383 for (const SDValue &ChainOp : Chain->op_values())
12384 if (ChainOp.getNode() == LD) {
12388 if (!isOk) return Result;
12391 // This only handles simple types.
12392 if (V.getValueType() != MVT::i16 &&
12393 V.getValueType() != MVT::i32 &&
12394 V.getValueType() != MVT::i64)
12397 // Check the constant mask. Invert it so that the bits being masked out are
12398 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
12399 // follow the sign bit for uniformity.
12400 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12401 unsigned NotMaskLZ = countLeadingZeros(NotMask);
12402 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
12403 unsigned NotMaskTZ = countTrailingZeros(NotMask);
12404 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
12405 if (NotMaskLZ == 64) return Result; // All zero mask.
12407 // See if we have a continuous run of bits. If so, we have 0*1+0*
12408 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12411 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12412 if (V.getValueType() != MVT::i64 && NotMaskLZ)
12413 NotMaskLZ -= 64-V.getValueSizeInBits();
12415 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12416 switch (MaskedBytes) {
12420 default: return Result; // All one mask, or 5-byte mask.
12423 // Verify that the first bit starts at a multiple of mask so that the access
12424 // is aligned the same as the access width.
12425 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12427 Result.first = MaskedBytes;
12428 Result.second = NotMaskTZ/8;
12432 /// Check to see if IVal is something that provides a value as specified by
12433 /// MaskInfo. If so, replace the specified store with a narrower store of
12434 /// truncated IVal.
12436 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12437 SDValue IVal, StoreSDNode *St,
12439 unsigned NumBytes = MaskInfo.first;
12440 unsigned ByteShift = MaskInfo.second;
12441 SelectionDAG &DAG = DC->getDAG();
12443 // Check to see if IVal is all zeros in the part being masked in by the 'or'
12444 // that uses this. If not, this is not a replacement.
12445 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12446 ByteShift*8, (ByteShift+NumBytes)*8);
12447 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12449 // Check that it is legal on the target to do this. It is legal if the new
12450 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12452 MVT VT = MVT::getIntegerVT(NumBytes*8);
12453 if (!DC->isTypeLegal(VT))
12456 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
12457 // shifted by ByteShift and truncated down to NumBytes.
12460 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12461 DAG.getConstant(ByteShift*8, DL,
12462 DC->getShiftAmountTy(IVal.getValueType())));
12465 // Figure out the offset for the store and the alignment of the access.
12467 unsigned NewAlign = St->getAlignment();
12469 if (DAG.getDataLayout().isLittleEndian())
12470 StOffset = ByteShift;
12472 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12474 SDValue Ptr = St->getBasePtr();
12477 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12478 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12479 NewAlign = MinAlign(NewAlign, StOffset);
12482 // Truncate down to the new size.
12483 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12487 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12488 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12492 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12493 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12494 /// narrowing the load and store if it would end up being a win for performance
12496 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12497 StoreSDNode *ST = cast<StoreSDNode>(N);
12498 if (ST->isVolatile())
12501 SDValue Chain = ST->getChain();
12502 SDValue Value = ST->getValue();
12503 SDValue Ptr = ST->getBasePtr();
12504 EVT VT = Value.getValueType();
12506 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12509 unsigned Opc = Value.getOpcode();
12511 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12512 // is a byte mask indicating a consecutive number of bytes, check to see if
12513 // Y is known to provide just those bytes. If so, we try to replace the
12514 // load + replace + store sequence with a single (narrower) store, which makes
12516 if (Opc == ISD::OR) {
12517 std::pair<unsigned, unsigned> MaskedLoad;
12518 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12519 if (MaskedLoad.first)
12520 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12521 Value.getOperand(1), ST,this))
12522 return SDValue(NewST, 0);
12524 // Or is commutative, so try swapping X and Y.
12525 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12526 if (MaskedLoad.first)
12527 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12528 Value.getOperand(0), ST,this))
12529 return SDValue(NewST, 0);
12532 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12533 Value.getOperand(1).getOpcode() != ISD::Constant)
12536 SDValue N0 = Value.getOperand(0);
12537 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12538 Chain == SDValue(N0.getNode(), 1)) {
12539 LoadSDNode *LD = cast<LoadSDNode>(N0);
12540 if (LD->getBasePtr() != Ptr ||
12541 LD->getPointerInfo().getAddrSpace() !=
12542 ST->getPointerInfo().getAddrSpace())
12545 // Find the type to narrow it the load / op / store to.
12546 SDValue N1 = Value.getOperand(1);
12547 unsigned BitWidth = N1.getValueSizeInBits();
12548 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12549 if (Opc == ISD::AND)
12550 Imm ^= APInt::getAllOnesValue(BitWidth);
12551 if (Imm == 0 || Imm.isAllOnesValue())
12553 unsigned ShAmt = Imm.countTrailingZeros();
12554 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12555 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12556 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12557 // The narrowing should be profitable, the load/store operation should be
12558 // legal (or custom) and the store size should be equal to the NewVT width.
12559 while (NewBW < BitWidth &&
12560 (NewVT.getStoreSizeInBits() != NewBW ||
12561 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12562 !TLI.isNarrowingProfitable(VT, NewVT))) {
12563 NewBW = NextPowerOf2(NewBW);
12564 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12566 if (NewBW >= BitWidth)
12569 // If the lsb changed does not start at the type bitwidth boundary,
12570 // start at the previous one.
12572 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12573 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12574 std::min(BitWidth, ShAmt + NewBW));
12575 if ((Imm & Mask) == Imm) {
12576 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12577 if (Opc == ISD::AND)
12578 NewImm ^= APInt::getAllOnesValue(NewBW);
12579 uint64_t PtrOff = ShAmt / 8;
12580 // For big endian targets, we need to adjust the offset to the pointer to
12581 // load the correct bytes.
12582 if (DAG.getDataLayout().isBigEndian())
12583 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12585 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12586 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12587 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12590 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12591 Ptr.getValueType(), Ptr,
12592 DAG.getConstant(PtrOff, SDLoc(LD),
12593 Ptr.getValueType()));
12595 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12596 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12597 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12598 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12599 DAG.getConstant(NewImm, SDLoc(Value),
12602 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12603 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12605 AddToWorklist(NewPtr.getNode());
12606 AddToWorklist(NewLD.getNode());
12607 AddToWorklist(NewVal.getNode());
12608 WorklistRemover DeadNodes(*this);
12609 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12618 /// For a given floating point load / store pair, if the load value isn't used
12619 /// by any other operations, then consider transforming the pair to integer
12620 /// load / store operations if the target deems the transformation profitable.
12621 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12622 StoreSDNode *ST = cast<StoreSDNode>(N);
12623 SDValue Chain = ST->getChain();
12624 SDValue Value = ST->getValue();
12625 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12626 Value.hasOneUse() &&
12627 Chain == SDValue(Value.getNode(), 1)) {
12628 LoadSDNode *LD = cast<LoadSDNode>(Value);
12629 EVT VT = LD->getMemoryVT();
12630 if (!VT.isFloatingPoint() ||
12631 VT != ST->getMemoryVT() ||
12632 LD->isNonTemporal() ||
12633 ST->isNonTemporal() ||
12634 LD->getPointerInfo().getAddrSpace() != 0 ||
12635 ST->getPointerInfo().getAddrSpace() != 0)
12638 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12639 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12640 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12641 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12642 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12645 unsigned LDAlign = LD->getAlignment();
12646 unsigned STAlign = ST->getAlignment();
12647 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12648 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12649 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12653 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12654 LD->getPointerInfo(), LDAlign);
12657 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12658 ST->getPointerInfo(), STAlign);
12660 AddToWorklist(NewLD.getNode());
12661 AddToWorklist(NewST.getNode());
12662 WorklistRemover DeadNodes(*this);
12663 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12671 // This is a helper function for visitMUL to check the profitability
12672 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12673 // MulNode is the original multiply, AddNode is (add x, c1),
12674 // and ConstNode is c2.
12676 // If the (add x, c1) has multiple uses, we could increase
12677 // the number of adds if we make this transformation.
12678 // It would only be worth doing this if we can remove a
12679 // multiply in the process. Check for that here.
12683 // We're checking for cases where we have common "c3 * A" expressions.
12684 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12686 SDValue &ConstNode) {
12689 // If the add only has one use, this would be OK to do.
12690 if (AddNode.getNode()->hasOneUse())
12693 // Walk all the users of the constant with which we're multiplying.
12694 for (SDNode *Use : ConstNode->uses()) {
12695 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12698 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12700 SDNode *MulVar = AddNode.getOperand(0).getNode();
12702 // OtherOp is what we're multiplying against the constant.
12703 if (Use->getOperand(0) == ConstNode)
12704 OtherOp = Use->getOperand(1).getNode();
12706 OtherOp = Use->getOperand(0).getNode();
12708 // Check to see if multiply is with the same operand of our "add".
12710 // ConstNode = CONST
12711 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12713 // AddNode = (A + c1) <-- MulVar is A.
12714 // = AddNode * ConstNode <-- current visiting instruction.
12716 // If we make this transformation, we will have a common
12717 // multiply (ConstNode * A) that we can save.
12718 if (OtherOp == MulVar)
12721 // Now check to see if a future expansion will give us a common
12724 // ConstNode = CONST
12725 // AddNode = (A + c1)
12726 // ... = AddNode * ConstNode <-- current visiting instruction.
12728 // OtherOp = (A + c2)
12729 // Use = OtherOp * ConstNode <-- visiting Use.
12731 // If we make this transformation, we will have a common
12732 // multiply (CONST * A) after we also do the same transformation
12733 // to the "t2" instruction.
12734 if (OtherOp->getOpcode() == ISD::ADD &&
12735 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12736 OtherOp->getOperand(0).getNode() == MulVar)
12741 // Didn't find a case where this would be profitable.
12745 static SDValue peekThroughBitcast(SDValue V) {
12746 while (V.getOpcode() == ISD::BITCAST)
12747 V = V.getOperand(0);
12751 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12752 unsigned NumStores) {
12753 SmallVector<SDValue, 8> Chains;
12754 SmallPtrSet<const SDNode *, 8> Visited;
12755 SDLoc StoreDL(StoreNodes[0].MemNode);
12757 for (unsigned i = 0; i < NumStores; ++i) {
12758 Visited.insert(StoreNodes[i].MemNode);
12761 // don't include nodes that are children
12762 for (unsigned i = 0; i < NumStores; ++i) {
12763 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12764 Chains.push_back(StoreNodes[i].MemNode->getChain());
12767 assert(Chains.size() > 0 && "Chain should have generated a chain");
12768 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12771 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12772 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12773 bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12774 // Make sure we have something to merge.
12778 // The latest Node in the DAG.
12779 SDLoc DL(StoreNodes[0].MemNode);
12781 int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
12782 unsigned SizeInBits = NumStores * ElementSizeBits;
12783 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12787 unsigned Elts = NumStores * NumMemElts;
12788 // Get the type for the merged vector store.
12789 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12791 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12795 if (IsConstantSrc) {
12796 SmallVector<SDValue, 8> BuildVector;
12797 for (unsigned I = 0; I != NumStores; ++I) {
12798 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12799 SDValue Val = St->getValue();
12800 // If constant is of the wrong type, convert it now.
12801 if (MemVT != Val.getValueType()) {
12802 Val = peekThroughBitcast(Val);
12803 // Deal with constants of wrong size.
12804 if (ElementSizeBits != Val.getValueSizeInBits()) {
12806 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12807 if (isa<ConstantFPSDNode>(Val)) {
12808 // Not clear how to truncate FP values.
12810 } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12811 Val = DAG.getConstant(C->getAPIntValue()
12812 .zextOrTrunc(Val.getValueSizeInBits())
12813 .zextOrTrunc(ElementSizeBits),
12814 SDLoc(C), IntMemVT);
12816 // Make sure correctly size type is the correct type.
12817 Val = DAG.getBitcast(MemVT, Val);
12819 BuildVector.push_back(Val);
12821 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12822 : ISD::BUILD_VECTOR,
12823 DL, StoreTy, BuildVector);
12825 SmallVector<SDValue, 8> Ops;
12826 for (unsigned i = 0; i < NumStores; ++i) {
12827 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12828 SDValue Val = peekThroughBitcast(St->getValue());
12829 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12830 // type MemVT. If the underlying value is not the correct
12831 // type, but it is an extraction of an appropriate vector we
12832 // can recast Val to be of the correct type. This may require
12833 // converting between EXTRACT_VECTOR_ELT and
12834 // EXTRACT_SUBVECTOR.
12835 if ((MemVT != Val.getValueType()) &&
12836 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12837 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12838 SDValue Vec = Val.getOperand(0);
12839 EVT MemVTScalarTy = MemVT.getScalarType();
12840 // We may need to add a bitcast here to get types to line up.
12841 if (MemVTScalarTy != Vec.getValueType()) {
12842 unsigned Elts = Vec.getValueType().getSizeInBits() /
12843 MemVTScalarTy.getSizeInBits();
12845 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12846 Vec = DAG.getBitcast(NewVecTy, Vec);
12848 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12849 : ISD::EXTRACT_VECTOR_ELT;
12850 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12852 Ops.push_back(Val);
12855 // Build the extracted vector elements back into a vector.
12856 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12857 : ISD::BUILD_VECTOR,
12861 // We should always use a vector store when merging extracted vector
12862 // elements, so this path implies a store of constants.
12863 assert(IsConstantSrc && "Merged vector elements should use vector store");
12865 APInt StoreInt(SizeInBits, 0);
12867 // Construct a single integer constant which is made of the smaller
12868 // constant inputs.
12869 bool IsLE = DAG.getDataLayout().isLittleEndian();
12870 for (unsigned i = 0; i < NumStores; ++i) {
12871 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12872 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12874 SDValue Val = St->getValue();
12875 StoreInt <<= ElementSizeBits;
12876 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12877 StoreInt |= C->getAPIntValue()
12878 .zextOrTrunc(ElementSizeBits)
12879 .zextOrTrunc(SizeInBits);
12880 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12881 StoreInt |= C->getValueAPF()
12883 .zextOrTrunc(ElementSizeBits)
12884 .zextOrTrunc(SizeInBits);
12885 // If fp truncation is necessary give up for now.
12886 if (MemVT.getSizeInBits() != ElementSizeBits)
12889 llvm_unreachable("Invalid constant element type");
12893 // Create the new Load and Store operations.
12894 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12897 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12898 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12900 // make sure we use trunc store if it's necessary to be legal.
12903 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12904 FirstInChain->getPointerInfo(),
12905 FirstInChain->getAlignment());
12906 } else { // Must be realized as a trunc store
12907 EVT LegalizedStoredValueTy =
12908 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12909 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12910 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12911 SDValue ExtendedStoreVal =
12912 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12913 LegalizedStoredValueTy);
12914 NewStore = DAG.getTruncStore(
12915 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12916 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12917 FirstInChain->getAlignment(),
12918 FirstInChain->getMemOperand()->getFlags());
12921 // Replace all merged stores with the new store.
12922 for (unsigned i = 0; i < NumStores; ++i)
12923 CombineTo(StoreNodes[i].MemNode, NewStore);
12925 AddToWorklist(NewChain.getNode());
12929 void DAGCombiner::getStoreMergeCandidates(
12930 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12931 // This holds the base pointer, index, and the offset in bytes from the base
12933 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12934 EVT MemVT = St->getMemoryVT();
12936 SDValue Val = peekThroughBitcast(St->getValue());
12937 // We must have a base and an offset.
12938 if (!BasePtr.getBase().getNode())
12941 // Do not handle stores to undef base pointers.
12942 if (BasePtr.getBase().isUndef())
12945 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12946 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12947 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12948 bool IsLoadSrc = isa<LoadSDNode>(Val);
12949 BaseIndexOffset LBasePtr;
12950 // Match on loadbaseptr if relevant.
12953 auto *Ld = cast<LoadSDNode>(Val);
12954 LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12955 LoadVT = Ld->getMemoryVT();
12956 // Load and store should be the same type.
12957 if (MemVT != LoadVT)
12960 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12961 int64_t &Offset) -> bool {
12962 if (Other->isVolatile() || Other->isIndexed())
12964 SDValue Val = peekThroughBitcast(Other->getValue());
12965 // Allow merging constants of different types as integers.
12966 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
12967 : Other->getMemoryVT() != MemVT;
12971 // The Load's Base Ptr must also match
12972 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
12973 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12974 if (LoadVT != OtherLd->getMemoryVT())
12976 if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12981 if (IsConstantSrc) {
12984 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
12987 if (IsExtractVecSrc) {
12988 // Do not merge truncated stores here.
12989 if (Other->isTruncatingStore())
12991 if (!MemVT.bitsEq(Val.getValueType()))
12993 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12994 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12997 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12998 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13001 // We looking for a root node which is an ancestor to all mergable
13002 // stores. We search up through a load, to our root and then down
13003 // through all children. For instance we will find Store{1,2,3} if
13004 // St is Store1, Store2. or Store3 where the root is not a load
13005 // which always true for nonvolatile ops. TODO: Expand
13006 // the search to find all valid candidates through multiple layers of loads.
13009 // |-------|-------|
13010 // Load Load Store3
13014 // FIXME: We should be able to climb and
13015 // descend TokenFactors to find candidates as well.
13017 SDNode *RootNode = (St->getChain()).getNode();
13019 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13020 RootNode = Ldn->getChain().getNode();
13021 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13022 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13023 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13024 if (I2.getOperandNo() == 0)
13025 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13026 BaseIndexOffset Ptr;
13028 if (CandidateMatch(OtherST, Ptr, PtrDiff))
13029 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13032 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13033 if (I.getOperandNo() == 0)
13034 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13035 BaseIndexOffset Ptr;
13037 if (CandidateMatch(OtherST, Ptr, PtrDiff))
13038 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13042 // We need to check that merging these stores does not cause a loop in
13043 // the DAG. Any store candidate may depend on another candidate
13044 // indirectly through its operand (we already consider dependencies
13045 // through the chain). Check in parallel by searching up from
13046 // non-chain operands of candidates.
13047 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13048 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
13049 // FIXME: We should be able to truncate a full search of
13050 // predecessors by doing a BFS and keeping tabs the originating
13051 // stores from which worklist nodes come from in a similar way to
13052 // TokenFactor simplfication.
13054 SmallPtrSet<const SDNode *, 16> Visited;
13055 SmallVector<const SDNode *, 8> Worklist;
13056 unsigned int Max = 8192;
13057 // Search Ops of store candidates.
13058 for (unsigned i = 0; i < NumStores; ++i) {
13059 SDNode *n = StoreNodes[i].MemNode;
13060 // Potential loops may happen only through non-chain operands
13061 for (unsigned j = 1; j < n->getNumOperands(); ++j)
13062 Worklist.push_back(n->getOperand(j).getNode());
13064 // Search through DAG. We can stop early if we find a store node.
13065 for (unsigned i = 0; i < NumStores; ++i) {
13066 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13069 // Check if we ended early, failing conservatively if so.
13070 if (Visited.size() >= Max)
13076 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13077 if (OptLevel == CodeGenOpt::None)
13080 EVT MemVT = St->getMemoryVT();
13081 int64_t ElementSizeBytes = MemVT.getStoreSize();
13082 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13084 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13087 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13088 Attribute::NoImplicitFloat);
13090 // This function cannot currently deal with non-byte-sized memory sizes.
13091 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13094 if (!MemVT.isSimple())
13097 // Perform an early exit check. Do not bother looking at stored values that
13098 // are not constants, loads, or extracted vector elements.
13099 SDValue StoredVal = peekThroughBitcast(St->getValue());
13100 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13101 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13102 isa<ConstantFPSDNode>(StoredVal);
13103 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13104 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13106 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13109 SmallVector<MemOpLink, 8> StoreNodes;
13110 // Find potential store merge candidates by searching through chain sub-DAG
13111 getStoreMergeCandidates(St, StoreNodes);
13113 // Check if there is anything to merge.
13114 if (StoreNodes.size() < 2)
13117 // Sort the memory operands according to their distance from the
13119 std::sort(StoreNodes.begin(), StoreNodes.end(),
13120 [](MemOpLink LHS, MemOpLink RHS) {
13121 return LHS.OffsetFromBase < RHS.OffsetFromBase;
13124 // Store Merge attempts to merge the lowest stores. This generally
13125 // works out as if successful, as the remaining stores are checked
13126 // after the first collection of stores is merged. However, in the
13127 // case that a non-mergeable store is found first, e.g., {p[-2],
13128 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13129 // mergeable cases. To prevent this, we prune such stores from the
13130 // front of StoreNodes here.
13133 while (StoreNodes.size() > 1) {
13134 unsigned StartIdx = 0;
13135 while ((StartIdx + 1 < StoreNodes.size()) &&
13136 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13137 StoreNodes[StartIdx + 1].OffsetFromBase)
13140 // Bail if we don't have enough candidates to merge.
13141 if (StartIdx + 1 >= StoreNodes.size())
13145 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13147 // Scan the memory operations on the chain and find the first
13148 // non-consecutive store memory address.
13149 unsigned NumConsecutiveStores = 1;
13150 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13151 // Check that the addresses are consecutive starting from the second
13152 // element in the list of stores.
13153 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13154 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13155 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13157 NumConsecutiveStores = i + 1;
13160 if (NumConsecutiveStores < 2) {
13161 StoreNodes.erase(StoreNodes.begin(),
13162 StoreNodes.begin() + NumConsecutiveStores);
13166 // Check that we can merge these candidates without causing a cycle
13167 if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
13168 NumConsecutiveStores)) {
13169 StoreNodes.erase(StoreNodes.begin(),
13170 StoreNodes.begin() + NumConsecutiveStores);
13174 // The node with the lowest store address.
13175 LLVMContext &Context = *DAG.getContext();
13176 const DataLayout &DL = DAG.getDataLayout();
13178 // Store the constants into memory as one consecutive store.
13179 if (IsConstantSrc) {
13180 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13181 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13182 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13183 unsigned LastLegalType = 1;
13184 unsigned LastLegalVectorType = 1;
13185 bool LastIntegerTrunc = false;
13186 bool NonZero = false;
13187 unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13188 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13189 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13190 SDValue StoredVal = ST->getValue();
13191 bool IsElementZero = false;
13192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13193 IsElementZero = C->isNullValue();
13194 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13195 IsElementZero = C->getConstantFPValue()->isNullValue();
13196 if (IsElementZero) {
13197 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13198 FirstZeroAfterNonZero = i;
13200 NonZero |= !IsElementZero;
13202 // Find a legal type for the constant store.
13203 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13204 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13205 bool IsFast = false;
13206 if (TLI.isTypeLegal(StoreTy) &&
13207 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13208 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13209 FirstStoreAlign, &IsFast) &&
13211 LastIntegerTrunc = false;
13212 LastLegalType = i + 1;
13213 // Or check whether a truncstore is legal.
13214 } else if (TLI.getTypeAction(Context, StoreTy) ==
13215 TargetLowering::TypePromoteInteger) {
13216 EVT LegalizedStoredValueTy =
13217 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13218 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13219 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13220 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13221 FirstStoreAlign, &IsFast) &&
13223 LastIntegerTrunc = true;
13224 LastLegalType = i + 1;
13228 // We only use vectors if the constant is known to be zero or the target
13229 // allows it and the function is not marked with the noimplicitfloat
13232 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13234 // Find a legal type for the vector store.
13235 unsigned Elts = (i + 1) * NumMemElts;
13236 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13237 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13238 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13239 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13240 FirstStoreAlign, &IsFast) &&
13242 LastLegalVectorType = i + 1;
13246 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13247 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13249 // Check if we found a legal integer type that creates a meaningful merge.
13251 // We know that candidate stores are in order and of correct
13252 // shape. While there is no mergeable sequence from the
13253 // beginning one may start later in the sequence. The only
13254 // reason a merge of size N could have failed where another of
13255 // the same size would not have, is if the alignment has
13256 // improved or we've dropped a non-zero value. Drop as many
13257 // candidates as we can here.
13258 unsigned NumSkip = 1;
13260 (NumSkip < NumConsecutiveStores) &&
13261 (NumSkip < FirstZeroAfterNonZero) &&
13262 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13265 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13269 bool Merged = MergeStoresOfConstantsOrVecElts(
13270 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13273 // Remove merged stores for next iteration.
13274 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13278 // When extracting multiple vector elements, try to store them
13279 // in one vector store rather than a sequence of scalar stores.
13280 if (IsExtractVecSrc) {
13281 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13282 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13283 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13284 unsigned NumStoresToMerge = 1;
13285 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13286 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13287 SDValue StVal = peekThroughBitcast(St->getValue());
13288 // This restriction could be loosened.
13289 // Bail out if any stored values are not elements extracted from a
13290 // vector. It should be possible to handle mixed sources, but load
13291 // sources need more careful handling (see the block of code below that
13292 // handles consecutive loads).
13293 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13294 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13297 // Find a legal type for the vector store.
13298 unsigned Elts = (i + 1) * NumMemElts;
13300 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13302 if (TLI.isTypeLegal(Ty) &&
13303 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13304 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13305 FirstStoreAlign, &IsFast) &&
13307 NumStoresToMerge = i + 1;
13310 // Check if we found a legal integer type that creates a meaningful merge.
13311 if (NumStoresToMerge < 2) {
13312 // We know that candidate stores are in order and of correct
13313 // shape. While there is no mergeable sequence from the
13314 // beginning one may start later in the sequence. The only
13315 // reason a merge of size N could have failed where another of
13316 // the same size would not have, is if the alignment has
13317 // improved. Drop as many candidates as we can here.
13318 unsigned NumSkip = 1;
13319 while ((NumSkip < NumConsecutiveStores) &&
13320 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13323 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13327 bool Merged = MergeStoresOfConstantsOrVecElts(
13328 StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13330 StoreNodes.erase(StoreNodes.begin(),
13331 StoreNodes.begin() + NumStoresToMerge);
13334 // Remove merged stores for next iteration.
13335 StoreNodes.erase(StoreNodes.begin(),
13336 StoreNodes.begin() + NumStoresToMerge);
13341 // Below we handle the case of multiple consecutive stores that
13342 // come from multiple consecutive loads. We merge them into a single
13343 // wide load and a single wide store.
13345 // Look for load nodes which are used by the stored values.
13346 SmallVector<MemOpLink, 8> LoadNodes;
13348 // Find acceptable loads. Loads need to have the same chain (token factor),
13349 // must not be zext, volatile, indexed, and they must be consecutive.
13350 BaseIndexOffset LdBasePtr;
13351 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13352 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13353 SDValue Val = peekThroughBitcast(St->getValue());
13354 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13358 // Loads must only have one use.
13359 if (!Ld->hasNUsesOfValue(1, 0))
13362 // The memory operands must not be volatile.
13363 if (Ld->isVolatile() || Ld->isIndexed())
13366 // The stored memory type must be the same.
13367 if (Ld->getMemoryVT() != MemVT)
13370 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
13371 // If this is not the first ptr that we check.
13372 int64_t LdOffset = 0;
13373 if (LdBasePtr.getBase().getNode()) {
13374 // The base ptr must be the same.
13375 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13378 // Check that all other base pointers are the same as this one.
13382 // We found a potential memory operand to merge.
13383 LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13386 if (LoadNodes.size() < 2) {
13387 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13391 // If we have load/store pair instructions and we only have two values,
13392 // don't bother merging.
13393 unsigned RequiredAlignment;
13394 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13395 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13396 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13399 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13400 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13401 unsigned FirstStoreAlign = FirstInChain->getAlignment();
13402 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13403 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13404 unsigned FirstLoadAlign = FirstLoad->getAlignment();
13406 // Scan the memory operations on the chain and find the first
13407 // non-consecutive load memory address. These variables hold the index in
13408 // the store node array.
13409 unsigned LastConsecutiveLoad = 1;
13410 // This variable refers to the size and not index in the array.
13411 unsigned LastLegalVectorType = 1;
13412 unsigned LastLegalIntegerType = 1;
13413 bool isDereferenceable = true;
13414 bool DoIntegerTruncate = false;
13415 StartAddress = LoadNodes[0].OffsetFromBase;
13416 SDValue FirstChain = FirstLoad->getChain();
13417 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13418 // All loads must share the same chain.
13419 if (LoadNodes[i].MemNode->getChain() != FirstChain)
13422 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13423 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13425 LastConsecutiveLoad = i;
13427 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13428 isDereferenceable = false;
13430 // Find a legal type for the vector store.
13431 unsigned Elts = (i + 1) * NumMemElts;
13432 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13434 bool IsFastSt, IsFastLd;
13435 if (TLI.isTypeLegal(StoreTy) &&
13436 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13437 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13438 FirstStoreAlign, &IsFastSt) &&
13440 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13441 FirstLoadAlign, &IsFastLd) &&
13443 LastLegalVectorType = i + 1;
13446 // Find a legal type for the integer store.
13447 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13448 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13449 if (TLI.isTypeLegal(StoreTy) &&
13450 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13451 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13452 FirstStoreAlign, &IsFastSt) &&
13454 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13455 FirstLoadAlign, &IsFastLd) &&
13457 LastLegalIntegerType = i + 1;
13458 DoIntegerTruncate = false;
13459 // Or check whether a truncstore and extload is legal.
13460 } else if (TLI.getTypeAction(Context, StoreTy) ==
13461 TargetLowering::TypePromoteInteger) {
13462 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13463 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13464 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13465 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13467 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13469 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13470 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13471 FirstStoreAlign, &IsFastSt) &&
13473 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13474 FirstLoadAlign, &IsFastLd) &&
13476 LastLegalIntegerType = i + 1;
13477 DoIntegerTruncate = true;
13482 // Only use vector types if the vector type is larger than the integer type.
13483 // If they are the same, use integers.
13484 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13485 unsigned LastLegalType =
13486 std::max(LastLegalVectorType, LastLegalIntegerType);
13488 // We add +1 here because the LastXXX variables refer to location while
13489 // the NumElem refers to array/index size.
13490 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13491 NumElem = std::min(LastLegalType, NumElem);
13494 // We know that candidate stores are in order and of correct
13495 // shape. While there is no mergeable sequence from the
13496 // beginning one may start later in the sequence. The only
13497 // reason a merge of size N could have failed where another of
13498 // the same size would not have is if the alignment or either
13499 // the load or store has improved. Drop as many candidates as we
13501 unsigned NumSkip = 1;
13502 while ((NumSkip < LoadNodes.size()) &&
13503 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13504 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13506 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13510 // Find if it is better to use vectors or integers to load and store
13514 // Find a legal type for the vector store.
13515 unsigned Elts = NumElem * NumMemElts;
13516 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13518 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13519 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13522 SDLoc LoadDL(LoadNodes[0].MemNode);
13523 SDLoc StoreDL(StoreNodes[0].MemNode);
13525 // The merged loads are required to have the same incoming chain, so
13526 // using the first's chain is acceptable.
13528 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13529 AddToWorklist(NewStoreChain.getNode());
13531 MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13532 MachineMemOperand::MODereferenceable:
13533 MachineMemOperand::MONone;
13535 SDValue NewLoad, NewStore;
13536 if (UseVectorTy || !DoIntegerTruncate) {
13537 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13538 FirstLoad->getBasePtr(),
13539 FirstLoad->getPointerInfo(), FirstLoadAlign,
13541 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13542 FirstInChain->getBasePtr(),
13543 FirstInChain->getPointerInfo(), FirstStoreAlign);
13544 } else { // This must be the truncstore/extload case
13546 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13548 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13549 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13550 JointMemOpVT, FirstLoadAlign, MMOFlags);
13551 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13552 FirstInChain->getBasePtr(),
13553 FirstInChain->getPointerInfo(), JointMemOpVT,
13554 FirstInChain->getAlignment(),
13555 FirstInChain->getMemOperand()->getFlags());
13558 // Transfer chain users from old loads to the new load.
13559 for (unsigned i = 0; i < NumElem; ++i) {
13560 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13561 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13562 SDValue(NewLoad.getNode(), 1));
13565 // Replace the all stores with the new store. Recursively remove
13566 // corresponding value if its no longer used.
13567 for (unsigned i = 0; i < NumElem; ++i) {
13568 SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13569 CombineTo(StoreNodes[i].MemNode, NewStore);
13570 if (Val.getNode()->use_empty())
13571 recursivelyDeleteUnusedNodes(Val.getNode());
13575 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13580 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13584 // Replace the chain to avoid dependency.
13585 if (ST->isTruncatingStore()) {
13586 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13587 ST->getBasePtr(), ST->getMemoryVT(),
13588 ST->getMemOperand());
13590 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13591 ST->getMemOperand());
13594 // Create token to keep both nodes around.
13595 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13596 MVT::Other, ST->getChain(), ReplStore);
13598 // Make sure the new and old chains are cleaned up.
13599 AddToWorklist(Token.getNode());
13601 // Don't add users to work list.
13602 return CombineTo(ST, Token, false);
13605 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13606 SDValue Value = ST->getValue();
13607 if (Value.getOpcode() == ISD::TargetConstantFP)
13612 SDValue Chain = ST->getChain();
13613 SDValue Ptr = ST->getBasePtr();
13615 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13617 // NOTE: If the original store is volatile, this transform must not increase
13618 // the number of stores. For example, on x86-32 an f64 can be stored in one
13619 // processor operation but an i64 (which is not legal) requires two. So the
13620 // transform should not be done in this case.
13623 switch (CFP->getSimpleValueType(0).SimpleTy) {
13625 llvm_unreachable("Unknown FP type");
13626 case MVT::f16: // We don't do this for these yet.
13632 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13633 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13635 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13636 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13638 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13643 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13644 !ST->isVolatile()) ||
13645 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13647 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13648 getZExtValue(), SDLoc(CFP), MVT::i64);
13649 return DAG.getStore(Chain, DL, Tmp,
13650 Ptr, ST->getMemOperand());
13653 if (!ST->isVolatile() &&
13654 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13655 // Many FP stores are not made apparent until after legalize, e.g. for
13656 // argument passing. Since this is so common, custom legalize the
13657 // 64-bit integer store into two 32-bit stores.
13658 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13659 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13660 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13661 if (DAG.getDataLayout().isBigEndian())
13664 unsigned Alignment = ST->getAlignment();
13665 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13666 AAMDNodes AAInfo = ST->getAAInfo();
13668 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13669 ST->getAlignment(), MMOFlags, AAInfo);
13670 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13671 DAG.getConstant(4, DL, Ptr.getValueType()));
13672 Alignment = MinAlign(Alignment, 4U);
13673 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13674 ST->getPointerInfo().getWithOffset(4),
13675 Alignment, MMOFlags, AAInfo);
13676 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13684 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13685 StoreSDNode *ST = cast<StoreSDNode>(N);
13686 SDValue Chain = ST->getChain();
13687 SDValue Value = ST->getValue();
13688 SDValue Ptr = ST->getBasePtr();
13690 // If this is a store of a bit convert, store the input value if the
13691 // resultant store does not need a higher alignment than the original.
13692 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13693 ST->isUnindexed()) {
13694 EVT SVT = Value.getOperand(0).getValueType();
13695 if (((!LegalOperations && !ST->isVolatile()) ||
13696 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13697 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13698 unsigned OrigAlign = ST->getAlignment();
13700 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13701 ST->getAddressSpace(), OrigAlign, &Fast) &&
13703 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13704 ST->getPointerInfo(), OrigAlign,
13705 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13710 // Turn 'store undef, Ptr' -> nothing.
13711 if (Value.isUndef() && ST->isUnindexed())
13714 // Try to infer better alignment information than the store already has.
13715 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13716 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13717 if (Align > ST->getAlignment()) {
13719 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13720 ST->getMemoryVT(), Align,
13721 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13722 if (NewStore.getNode() != N)
13723 return CombineTo(ST, NewStore, true);
13728 // Try transforming a pair floating point load / store ops to integer
13729 // load / store ops.
13730 if (SDValue NewST = TransformFPLoadStorePair(N))
13733 if (ST->isUnindexed()) {
13734 // Walk up chain skipping non-aliasing memory nodes, on this store and any
13735 // adjacent stores.
13736 if (findBetterNeighborChains(ST)) {
13737 // replaceStoreChain uses CombineTo, which handled all of the worklist
13738 // manipulation. Return the original node to not do anything else.
13739 return SDValue(ST, 0);
13741 Chain = ST->getChain();
13744 // FIXME: is there such a thing as a truncating indexed store?
13745 if (ST->isTruncatingStore() && ST->isUnindexed() &&
13746 Value.getValueType().isInteger()) {
13747 // See if we can simplify the input to this truncstore with knowledge that
13748 // only the low bits are being used. For example:
13749 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
13750 SDValue Shorter = DAG.GetDemandedBits(
13751 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13752 ST->getMemoryVT().getScalarSizeInBits()));
13753 AddToWorklist(Value.getNode());
13754 if (Shorter.getNode())
13755 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13756 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13758 // Otherwise, see if we can simplify the operation with
13759 // SimplifyDemandedBits, which only works if the value has a single use.
13760 if (SimplifyDemandedBits(
13762 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13763 ST->getMemoryVT().getScalarSizeInBits()))) {
13764 // Re-visit the store if anything changed and the store hasn't been merged
13765 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13766 // node back to the worklist if necessary, but we also need to re-visit
13767 // the Store node itself.
13768 if (N->getOpcode() != ISD::DELETED_NODE)
13770 return SDValue(N, 0);
13774 // If this is a load followed by a store to the same location, then the store
13776 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13777 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13778 ST->isUnindexed() && !ST->isVolatile() &&
13779 // There can't be any side effects between the load and store, such as
13780 // a call or store.
13781 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13782 // The store is dead, remove it.
13787 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13788 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13789 !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13790 ST->getMemoryVT() == ST1->getMemoryVT()) {
13791 // If this is a store followed by a store with the same value to the same
13792 // location, then the store is dead/noop.
13793 if (ST1->getValue() == Value) {
13794 // The store is dead, remove it.
13798 // If this is a store who's preceeding store to the same location
13799 // and no one other node is chained to that store we can effectively
13800 // drop the store. Do not remove stores to undef as they may be used as
13802 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13803 !ST1->getBasePtr().isUndef()) {
13804 // ST1 is fully overwritten and can be elided. Combine with it's chain
13806 CombineTo(ST1, ST1->getChain());
13812 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13813 // truncating store. We can do this even if this is already a truncstore.
13814 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13815 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13816 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13817 ST->getMemoryVT())) {
13818 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13819 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13822 // Always perform this optimization before types are legal. If the target
13823 // prefers, also try this after legalization to catch stores that were created
13824 // by intrinsics or other nodes.
13825 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
13827 // There can be multiple store sequences on the same chain.
13828 // Keep trying to merge store sequences until we are unable to do so
13829 // or until we merge the last store on the chain.
13830 bool Changed = MergeConsecutiveStores(ST);
13831 if (!Changed) break;
13832 // Return N as merge only uses CombineTo and no worklist clean
13833 // up is necessary.
13834 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13835 return SDValue(N, 0);
13839 // Try transforming N to an indexed store.
13840 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13841 return SDValue(N, 0);
13843 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13845 // Make sure to do this only after attempting to merge stores in order to
13846 // avoid changing the types of some subset of stores due to visit order,
13847 // preventing their merging.
13848 if (isa<ConstantFPSDNode>(ST->getValue())) {
13849 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13853 if (SDValue NewSt = splitMergedValStore(ST))
13856 return ReduceLoadOpStoreWidth(N);
13859 /// For the instruction sequence of store below, F and I values
13860 /// are bundled together as an i64 value before being stored into memory.
13861 /// Sometimes it is more efficent to generate separate stores for F and I,
13862 /// which can remove the bitwise instructions or sink them to colder places.
13864 /// (store (or (zext (bitcast F to i32) to i64),
13865 /// (shl (zext I to i64), 32)), addr) -->
13866 /// (store F, addr) and (store I, addr+4)
13868 /// Similarly, splitting for other merged store can also be beneficial, like:
13869 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13870 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13871 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13872 /// For pair of {i16, i8}, i32 store --> two i16 stores.
13873 /// For pair of {i8, i8}, i16 store --> two i8 stores.
13875 /// We allow each target to determine specifically which kind of splitting is
13878 /// The store patterns are commonly seen from the simple code snippet below
13879 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13880 /// void goo(const std::pair<int, float> &);
13883 /// goo(std::make_pair(tmp, ftmp));
13887 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13888 if (OptLevel == CodeGenOpt::None)
13891 SDValue Val = ST->getValue();
13894 // Match OR operand.
13895 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13898 // Match SHL operand and get Lower and Higher parts of Val.
13899 SDValue Op1 = Val.getOperand(0);
13900 SDValue Op2 = Val.getOperand(1);
13902 if (Op1.getOpcode() != ISD::SHL) {
13903 std::swap(Op1, Op2);
13904 if (Op1.getOpcode() != ISD::SHL)
13908 Hi = Op1.getOperand(0);
13909 if (!Op1.hasOneUse())
13912 // Match shift amount to HalfValBitSize.
13913 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13914 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13915 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13918 // Lo and Hi are zero-extended from int with size less equal than 32
13920 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13921 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13922 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13923 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13924 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13925 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13928 // Use the EVT of low and high parts before bitcast as the input
13929 // of target query.
13930 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13931 ? Lo.getOperand(0).getValueType()
13932 : Lo.getValueType();
13933 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13934 ? Hi.getOperand(0).getValueType()
13935 : Hi.getValueType();
13936 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13939 // Start to split store.
13940 unsigned Alignment = ST->getAlignment();
13941 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13942 AAMDNodes AAInfo = ST->getAAInfo();
13944 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13945 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13946 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13947 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13949 SDValue Chain = ST->getChain();
13950 SDValue Ptr = ST->getBasePtr();
13951 // Lower value store.
13952 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13953 ST->getAlignment(), MMOFlags, AAInfo);
13955 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13956 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13957 // Higher value store.
13959 DAG.getStore(St0, DL, Hi, Ptr,
13960 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13961 Alignment / 2, MMOFlags, AAInfo);
13965 /// Convert a disguised subvector insertion into a shuffle:
13966 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
13967 /// bitcast(shuffle (bitcast V), (extended X), Mask)
13968 /// Note: We do not use an insert_subvector node because that requires a legal
13969 /// subvector type.
13970 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
13971 SDValue InsertVal = N->getOperand(1);
13972 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
13973 !InsertVal.getOperand(0).getValueType().isVector())
13976 SDValue SubVec = InsertVal.getOperand(0);
13977 SDValue DestVec = N->getOperand(0);
13978 EVT SubVecVT = SubVec.getValueType();
13979 EVT VT = DestVec.getValueType();
13980 unsigned NumSrcElts = SubVecVT.getVectorNumElements();
13981 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
13982 unsigned NumMaskVals = ExtendRatio * NumSrcElts;
13984 // Step 1: Create a shuffle mask that implements this insert operation. The
13985 // vector that we are inserting into will be operand 0 of the shuffle, so
13986 // those elements are just 'i'. The inserted subvector is in the first
13987 // positions of operand 1 of the shuffle. Example:
13988 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
13989 SmallVector<int, 16> Mask(NumMaskVals);
13990 for (unsigned i = 0; i != NumMaskVals; ++i) {
13991 if (i / NumSrcElts == InsIndex)
13992 Mask[i] = (i % NumSrcElts) + NumMaskVals;
13997 // Bail out if the target can not handle the shuffle we want to create.
13998 EVT SubVecEltVT = SubVecVT.getVectorElementType();
13999 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14000 if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14003 // Step 2: Create a wide vector from the inserted source vector by appending
14004 // undefined elements. This is the same size as our destination vector.
14006 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14007 ConcatOps[0] = SubVec;
14008 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14010 // Step 3: Shuffle in the padded subvector.
14011 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14012 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14013 AddToWorklist(PaddedSubV.getNode());
14014 AddToWorklist(DestVecBC.getNode());
14015 AddToWorklist(Shuf.getNode());
14016 return DAG.getBitcast(VT, Shuf);
14019 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14020 SDValue InVec = N->getOperand(0);
14021 SDValue InVal = N->getOperand(1);
14022 SDValue EltNo = N->getOperand(2);
14025 // If the inserted element is an UNDEF, just use the input vector.
14026 if (InVal.isUndef())
14029 EVT VT = InVec.getValueType();
14031 // Remove redundant insertions:
14032 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14033 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14034 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14037 // We must know which element is being inserted for folds below here.
14038 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14041 unsigned Elt = IndexC->getZExtValue();
14043 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14046 // Canonicalize insert_vector_elt dag nodes.
14048 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14049 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14051 // Do this only if the child insert_vector node has one use; also
14052 // do this only if indices are both constants and Idx1 < Idx0.
14053 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14054 && isa<ConstantSDNode>(InVec.getOperand(2))) {
14055 unsigned OtherElt = InVec.getConstantOperandVal(2);
14056 if (Elt < OtherElt) {
14058 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14059 InVec.getOperand(0), InVal, EltNo);
14060 AddToWorklist(NewOp.getNode());
14061 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14062 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14066 // If we can't generate a legal BUILD_VECTOR, exit
14067 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14070 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14071 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
14072 // vector elements.
14073 SmallVector<SDValue, 8> Ops;
14074 // Do not combine these two vectors if the output vector will not replace
14075 // the input vector.
14076 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14077 Ops.append(InVec.getNode()->op_begin(),
14078 InVec.getNode()->op_end());
14079 } else if (InVec.isUndef()) {
14080 unsigned NElts = VT.getVectorNumElements();
14081 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14086 // Insert the element
14087 if (Elt < Ops.size()) {
14088 // All the operands of BUILD_VECTOR must have the same type;
14089 // we enforce that here.
14090 EVT OpVT = Ops[0].getValueType();
14091 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14094 // Return the new vector
14095 return DAG.getBuildVector(VT, DL, Ops);
14098 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14099 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14100 assert(!OriginalLoad->isVolatile());
14102 EVT ResultVT = EVE->getValueType(0);
14103 EVT VecEltVT = InVecVT.getVectorElementType();
14104 unsigned Align = OriginalLoad->getAlignment();
14105 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14106 VecEltVT.getTypeForEVT(*DAG.getContext()));
14108 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14111 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14112 ISD::NON_EXTLOAD : ISD::EXTLOAD;
14113 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14118 SDValue NewPtr = OriginalLoad->getBasePtr();
14120 EVT PtrType = NewPtr.getValueType();
14121 MachinePointerInfo MPI;
14123 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14124 int Elt = ConstEltNo->getZExtValue();
14125 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14126 Offset = DAG.getConstant(PtrOff, DL, PtrType);
14127 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14129 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14130 Offset = DAG.getNode(
14131 ISD::MUL, DL, PtrType, Offset,
14132 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14133 MPI = OriginalLoad->getPointerInfo();
14135 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14137 // The replacement we need to do here is a little tricky: we need to
14138 // replace an extractelement of a load with a load.
14139 // Use ReplaceAllUsesOfValuesWith to do the replacement.
14140 // Note that this replacement assumes that the extractvalue is the only
14141 // use of the load; that's okay because we don't want to perform this
14142 // transformation in other cases anyway.
14145 if (ResultVT.bitsGT(VecEltVT)) {
14146 // If the result type of vextract is wider than the load, then issue an
14147 // extending load instead.
14148 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14152 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14153 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14154 Align, OriginalLoad->getMemOperand()->getFlags(),
14155 OriginalLoad->getAAInfo());
14156 Chain = Load.getValue(1);
14158 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14159 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14160 OriginalLoad->getAAInfo());
14161 Chain = Load.getValue(1);
14162 if (ResultVT.bitsLT(VecEltVT))
14163 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14165 Load = DAG.getBitcast(ResultVT, Load);
14167 WorklistRemover DeadNodes(*this);
14168 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14169 SDValue To[] = { Load, Chain };
14170 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14171 // Since we're explicitly calling ReplaceAllUses, add the new node to the
14172 // worklist explicitly as well.
14173 AddToWorklist(Load.getNode());
14174 AddUsersToWorklist(Load.getNode()); // Add users too
14175 // Make sure to revisit this node to clean it up; it will usually be dead.
14176 AddToWorklist(EVE);
14178 return SDValue(EVE, 0);
14181 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14182 // (vextract (scalar_to_vector val, 0) -> val
14183 SDValue InVec = N->getOperand(0);
14184 EVT VT = InVec.getValueType();
14185 EVT NVT = N->getValueType(0);
14187 if (InVec.isUndef())
14188 return DAG.getUNDEF(NVT);
14190 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14191 // Check if the result type doesn't match the inserted element type. A
14192 // SCALAR_TO_VECTOR may truncate the inserted element and the
14193 // EXTRACT_VECTOR_ELT may widen the extracted vector.
14194 SDValue InOp = InVec.getOperand(0);
14195 if (InOp.getValueType() != NVT) {
14196 assert(InOp.getValueType().isInteger() && NVT.isInteger());
14197 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14202 SDValue EltNo = N->getOperand(1);
14203 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14205 // extract_vector_elt (build_vector x, y), 1 -> y
14207 InVec.getOpcode() == ISD::BUILD_VECTOR &&
14208 TLI.isTypeLegal(VT) &&
14209 (InVec.hasOneUse() ||
14210 TLI.aggressivelyPreferBuildVectorSources(VT))) {
14211 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14212 EVT InEltVT = Elt.getValueType();
14214 // Sometimes build_vector's scalar input types do not match result type.
14215 if (NVT == InEltVT)
14218 // TODO: It may be useful to truncate if free if the build_vector implicitly
14222 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14223 bool isLE = DAG.getDataLayout().isLittleEndian();
14224 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14225 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14226 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14227 SDValue BCSrc = InVec.getOperand(0);
14228 if (BCSrc.getValueType().isScalarInteger())
14229 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14232 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14234 // This only really matters if the index is non-constant since other combines
14235 // on the constant elements already work.
14236 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14237 EltNo == InVec.getOperand(2)) {
14238 SDValue Elt = InVec.getOperand(1);
14239 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14242 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14243 // We only perform this optimization before the op legalization phase because
14244 // we may introduce new vector instructions which are not backed by TD
14245 // patterns. For example on AVX, extracting elements from a wide vector
14246 // without using extract_subvector. However, if we can find an underlying
14247 // scalar value, then we can always use that.
14248 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14249 int NumElem = VT.getVectorNumElements();
14250 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14251 // Find the new index to extract from.
14252 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14254 // Extracting an undef index is undef.
14256 return DAG.getUNDEF(NVT);
14258 // Select the right vector half to extract from.
14260 if (OrigElt < NumElem) {
14261 SVInVec = InVec->getOperand(0);
14263 SVInVec = InVec->getOperand(1);
14264 OrigElt -= NumElem;
14267 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14268 SDValue InOp = SVInVec.getOperand(OrigElt);
14269 if (InOp.getValueType() != NVT) {
14270 assert(InOp.getValueType().isInteger() && NVT.isInteger());
14271 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14277 // FIXME: We should handle recursing on other vector shuffles and
14278 // scalar_to_vector here as well.
14280 if (!LegalOperations ||
14281 // FIXME: Should really be just isOperationLegalOrCustom.
14282 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14283 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14284 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14285 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14286 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14290 bool BCNumEltsChanged = false;
14291 EVT ExtVT = VT.getVectorElementType();
14294 // If the result of load has to be truncated, then it's not necessarily
14296 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14299 if (InVec.getOpcode() == ISD::BITCAST) {
14300 // Don't duplicate a load with other uses.
14301 if (!InVec.hasOneUse())
14304 EVT BCVT = InVec.getOperand(0).getValueType();
14305 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14307 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14308 BCNumEltsChanged = true;
14309 InVec = InVec.getOperand(0);
14310 ExtVT = BCVT.getVectorElementType();
14313 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14314 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14315 ISD::isNormalLoad(InVec.getNode()) &&
14316 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14317 SDValue Index = N->getOperand(1);
14318 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14319 if (!OrigLoad->isVolatile()) {
14320 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14326 // Perform only after legalization to ensure build_vector / vector_shuffle
14327 // optimizations have already been done.
14328 if (!LegalOperations) return SDValue();
14330 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14331 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14332 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14335 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14337 LoadSDNode *LN0 = nullptr;
14338 const ShuffleVectorSDNode *SVN = nullptr;
14339 if (ISD::isNormalLoad(InVec.getNode())) {
14340 LN0 = cast<LoadSDNode>(InVec);
14341 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14342 InVec.getOperand(0).getValueType() == ExtVT &&
14343 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14344 // Don't duplicate a load with other uses.
14345 if (!InVec.hasOneUse())
14348 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14349 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14350 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14352 // (load $addr+1*size)
14354 // Don't duplicate a load with other uses.
14355 if (!InVec.hasOneUse())
14358 // If the bit convert changed the number of elements, it is unsafe
14359 // to examine the mask.
14360 if (BCNumEltsChanged)
14363 // Select the input vector, guarding against out of range extract vector.
14364 unsigned NumElems = VT.getVectorNumElements();
14365 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14366 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14368 if (InVec.getOpcode() == ISD::BITCAST) {
14369 // Don't duplicate a load with other uses.
14370 if (!InVec.hasOneUse())
14373 InVec = InVec.getOperand(0);
14375 if (ISD::isNormalLoad(InVec.getNode())) {
14376 LN0 = cast<LoadSDNode>(InVec);
14377 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14378 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14382 // Make sure we found a non-volatile load and the extractelement is
14384 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14387 // If Idx was -1 above, Elt is going to be -1, so just return undef.
14389 return DAG.getUNDEF(LVT);
14391 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14397 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14398 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14399 // We perform this optimization post type-legalization because
14400 // the type-legalizer often scalarizes integer-promoted vectors.
14401 // Performing this optimization before may create bit-casts which
14402 // will be type-legalized to complex code sequences.
14403 // We perform this optimization only before the operation legalizer because we
14404 // may introduce illegal operations.
14405 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14408 unsigned NumInScalars = N->getNumOperands();
14410 EVT VT = N->getValueType(0);
14412 // Check to see if this is a BUILD_VECTOR of a bunch of values
14413 // which come from any_extend or zero_extend nodes. If so, we can create
14414 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14415 // optimizations. We do not handle sign-extend because we can't fill the sign
14417 EVT SourceType = MVT::Other;
14418 bool AllAnyExt = true;
14420 for (unsigned i = 0; i != NumInScalars; ++i) {
14421 SDValue In = N->getOperand(i);
14422 // Ignore undef inputs.
14423 if (In.isUndef()) continue;
14425 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
14426 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14428 // Abort if the element is not an extension.
14429 if (!ZeroExt && !AnyExt) {
14430 SourceType = MVT::Other;
14434 // The input is a ZeroExt or AnyExt. Check the original type.
14435 EVT InTy = In.getOperand(0).getValueType();
14437 // Check that all of the widened source types are the same.
14438 if (SourceType == MVT::Other)
14441 else if (InTy != SourceType) {
14442 // Multiple income types. Abort.
14443 SourceType = MVT::Other;
14447 // Check if all of the extends are ANY_EXTENDs.
14448 AllAnyExt &= AnyExt;
14451 // In order to have valid types, all of the inputs must be extended from the
14452 // same source type and all of the inputs must be any or zero extend.
14453 // Scalar sizes must be a power of two.
14454 EVT OutScalarTy = VT.getScalarType();
14455 bool ValidTypes = SourceType != MVT::Other &&
14456 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14457 isPowerOf2_32(SourceType.getSizeInBits());
14459 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14460 // turn into a single shuffle instruction.
14464 bool isLE = DAG.getDataLayout().isLittleEndian();
14465 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14466 assert(ElemRatio > 1 && "Invalid element size ratio");
14467 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14468 DAG.getConstant(0, DL, SourceType);
14470 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14471 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14473 // Populate the new build_vector
14474 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14475 SDValue Cast = N->getOperand(i);
14476 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14477 Cast.getOpcode() == ISD::ZERO_EXTEND ||
14478 Cast.isUndef()) && "Invalid cast opcode");
14480 if (Cast.isUndef())
14481 In = DAG.getUNDEF(SourceType);
14483 In = Cast->getOperand(0);
14484 unsigned Index = isLE ? (i * ElemRatio) :
14485 (i * ElemRatio + (ElemRatio - 1));
14487 assert(Index < Ops.size() && "Invalid index");
14491 // The type of the new BUILD_VECTOR node.
14492 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14493 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14494 "Invalid vector size");
14495 // Check if the new vector type is legal.
14496 if (!isTypeLegal(VecVT)) return SDValue();
14498 // Make the new BUILD_VECTOR.
14499 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14501 // The new BUILD_VECTOR node has the potential to be further optimized.
14502 AddToWorklist(BV.getNode());
14503 // Bitcast to the desired type.
14504 return DAG.getBitcast(VT, BV);
14507 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14508 EVT VT = N->getValueType(0);
14510 unsigned NumInScalars = N->getNumOperands();
14513 EVT SrcVT = MVT::Other;
14514 unsigned Opcode = ISD::DELETED_NODE;
14515 unsigned NumDefs = 0;
14517 for (unsigned i = 0; i != NumInScalars; ++i) {
14518 SDValue In = N->getOperand(i);
14519 unsigned Opc = In.getOpcode();
14521 if (Opc == ISD::UNDEF)
14524 // If all scalar values are floats and converted from integers.
14525 if (Opcode == ISD::DELETED_NODE &&
14526 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14533 EVT InVT = In.getOperand(0).getValueType();
14535 // If all scalar values are typed differently, bail out. It's chosen to
14536 // simplify BUILD_VECTOR of integer types.
14537 if (SrcVT == MVT::Other)
14544 // If the vector has just one element defined, it's not worth to fold it into
14545 // a vectorized one.
14549 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14550 && "Should only handle conversion from integer to float.");
14551 assert(SrcVT != MVT::Other && "Cannot determine source type!");
14553 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14555 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14558 // Just because the floating-point vector type is legal does not necessarily
14559 // mean that the corresponding integer vector type is.
14560 if (!isTypeLegal(NVT))
14563 SmallVector<SDValue, 8> Opnds;
14564 for (unsigned i = 0; i != NumInScalars; ++i) {
14565 SDValue In = N->getOperand(i);
14568 Opnds.push_back(DAG.getUNDEF(SrcVT));
14570 Opnds.push_back(In.getOperand(0));
14572 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14573 AddToWorklist(BV.getNode());
14575 return DAG.getNode(Opcode, DL, VT, BV);
14578 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14579 ArrayRef<int> VectorMask,
14580 SDValue VecIn1, SDValue VecIn2,
14581 unsigned LeftIdx) {
14582 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14583 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14585 EVT VT = N->getValueType(0);
14586 EVT InVT1 = VecIn1.getValueType();
14587 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14589 unsigned Vec2Offset = 0;
14590 unsigned NumElems = VT.getVectorNumElements();
14591 unsigned ShuffleNumElems = NumElems;
14593 // In case both the input vectors are extracted from same base
14594 // vector we do not need extra addend (Vec2Offset) while
14595 // computing shuffle mask.
14596 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14597 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14598 !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14599 Vec2Offset = InVT1.getVectorNumElements();
14601 // We can't generate a shuffle node with mismatched input and output types.
14602 // Try to make the types match the type of the output.
14603 if (InVT1 != VT || InVT2 != VT) {
14604 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14605 // If the output vector length is a multiple of both input lengths,
14606 // we can concatenate them and pad the rest with undefs.
14607 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14608 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14609 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14610 ConcatOps[0] = VecIn1;
14611 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14612 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14613 VecIn2 = SDValue();
14614 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14615 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14618 if (!VecIn2.getNode()) {
14619 // If we only have one input vector, and it's twice the size of the
14620 // output, split it in two.
14621 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14622 DAG.getConstant(NumElems, DL, IdxTy));
14623 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14624 // Since we now have shorter input vectors, adjust the offset of the
14625 // second vector's start.
14626 Vec2Offset = NumElems;
14627 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14628 // VecIn1 is wider than the output, and we have another, possibly
14629 // smaller input. Pad the smaller input with undefs, shuffle at the
14630 // input vector width, and extract the output.
14631 // The shuffle type is different than VT, so check legality again.
14632 if (LegalOperations &&
14633 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14636 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14637 // lower it back into a BUILD_VECTOR. So if the inserted type is
14638 // illegal, don't even try.
14639 if (InVT1 != InVT2) {
14640 if (!TLI.isTypeLegal(InVT2))
14642 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14643 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14645 ShuffleNumElems = NumElems * 2;
14647 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14648 // than VecIn1. We can't handle this for now - this case will disappear
14649 // when we start sorting the vectors by type.
14652 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14653 InVT1.getSizeInBits() == VT.getSizeInBits()) {
14654 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14655 ConcatOps[0] = VecIn2;
14656 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14658 // TODO: Support cases where the length mismatch isn't exactly by a
14660 // TODO: Move this check upwards, so that if we have bad type
14661 // mismatches, we don't create any DAG nodes.
14666 // Initialize mask to undef.
14667 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14669 // Only need to run up to the number of elements actually used, not the
14670 // total number of elements in the shuffle - if we are shuffling a wider
14671 // vector, the high lanes should be set to undef.
14672 for (unsigned i = 0; i != NumElems; ++i) {
14673 if (VectorMask[i] <= 0)
14676 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14677 if (VectorMask[i] == (int)LeftIdx) {
14678 Mask[i] = ExtIndex;
14679 } else if (VectorMask[i] == (int)LeftIdx + 1) {
14680 Mask[i] = Vec2Offset + ExtIndex;
14684 // The type the input vectors may have changed above.
14685 InVT1 = VecIn1.getValueType();
14687 // If we already have a VecIn2, it should have the same type as VecIn1.
14688 // If we don't, get an undef/zero vector of the appropriate type.
14689 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14690 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14692 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14693 if (ShuffleNumElems > NumElems)
14694 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14699 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14700 // operations. If the types of the vectors we're extracting from allow it,
14701 // turn this into a vector_shuffle node.
14702 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14704 EVT VT = N->getValueType(0);
14706 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14707 if (!isTypeLegal(VT))
14710 // May only combine to shuffle after legalize if shuffle is legal.
14711 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14714 bool UsesZeroVector = false;
14715 unsigned NumElems = N->getNumOperands();
14717 // Record, for each element of the newly built vector, which input vector
14718 // that element comes from. -1 stands for undef, 0 for the zero vector,
14719 // and positive values for the input vectors.
14720 // VectorMask maps each element to its vector number, and VecIn maps vector
14721 // numbers to their initial SDValues.
14723 SmallVector<int, 8> VectorMask(NumElems, -1);
14724 SmallVector<SDValue, 8> VecIn;
14725 VecIn.push_back(SDValue());
14727 for (unsigned i = 0; i != NumElems; ++i) {
14728 SDValue Op = N->getOperand(i);
14733 // See if we can use a blend with a zero vector.
14734 // TODO: Should we generalize this to a blend with an arbitrary constant
14736 if (isNullConstant(Op) || isNullFPConstant(Op)) {
14737 UsesZeroVector = true;
14742 // Not an undef or zero. If the input is something other than an
14743 // EXTRACT_VECTOR_ELT with a constant index, bail out.
14744 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14745 !isa<ConstantSDNode>(Op.getOperand(1)))
14747 SDValue ExtractedFromVec = Op.getOperand(0);
14749 // All inputs must have the same element type as the output.
14750 if (VT.getVectorElementType() !=
14751 ExtractedFromVec.getValueType().getVectorElementType())
14754 // Have we seen this input vector before?
14755 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14756 // a map back from SDValues to numbers isn't worth it.
14757 unsigned Idx = std::distance(
14758 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14759 if (Idx == VecIn.size())
14760 VecIn.push_back(ExtractedFromVec);
14762 VectorMask[i] = Idx;
14765 // If we didn't find at least one input vector, bail out.
14766 if (VecIn.size() < 2)
14769 // If all the Operands of BUILD_VECTOR extract from same
14770 // vector, then split the vector efficiently based on the maximum
14771 // vector access index and adjust the VectorMask and
14772 // VecIn accordingly.
14773 if (VecIn.size() == 2) {
14774 unsigned MaxIndex = 0;
14775 unsigned NearestPow2 = 0;
14776 SDValue Vec = VecIn.back();
14777 EVT InVT = Vec.getValueType();
14778 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14779 SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14781 for (unsigned i = 0; i < NumElems; i++) {
14782 if (VectorMask[i] <= 0)
14784 unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14785 IndexVec[i] = Index;
14786 MaxIndex = std::max(MaxIndex, Index);
14789 NearestPow2 = PowerOf2Ceil(MaxIndex);
14790 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14791 NumElems * 2 < NearestPow2) {
14792 unsigned SplitSize = NearestPow2 / 2;
14793 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14794 InVT.getVectorElementType(), SplitSize);
14795 if (TLI.isTypeLegal(SplitVT)) {
14796 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14797 DAG.getConstant(SplitSize, DL, IdxTy));
14798 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14799 DAG.getConstant(0, DL, IdxTy));
14801 VecIn.push_back(VecIn1);
14802 VecIn.push_back(VecIn2);
14804 for (unsigned i = 0; i < NumElems; i++) {
14805 if (VectorMask[i] <= 0)
14807 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14813 // TODO: We want to sort the vectors by descending length, so that adjacent
14814 // pairs have similar length, and the longer vector is always first in the
14817 // TODO: Should this fire if some of the input vectors has illegal type (like
14818 // it does now), or should we let legalization run its course first?
14821 // Take pairs of vectors, and shuffle them so that the result has elements
14822 // from these vectors in the correct places.
14823 // For example, given:
14824 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14825 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14826 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14827 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14828 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14829 // We will generate:
14830 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14831 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14832 SmallVector<SDValue, 4> Shuffles;
14833 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14834 unsigned LeftIdx = 2 * In + 1;
14835 SDValue VecLeft = VecIn[LeftIdx];
14837 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14839 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14840 VecRight, LeftIdx))
14841 Shuffles.push_back(Shuffle);
14846 // If we need the zero vector as an "ingredient" in the blend tree, add it
14847 // to the list of shuffles.
14848 if (UsesZeroVector)
14849 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14850 : DAG.getConstantFP(0.0, DL, VT));
14852 // If we only have one shuffle, we're done.
14853 if (Shuffles.size() == 1)
14854 return Shuffles[0];
14856 // Update the vector mask to point to the post-shuffle vectors.
14857 for (int &Vec : VectorMask)
14859 Vec = Shuffles.size() - 1;
14861 Vec = (Vec - 1) / 2;
14863 // More than one shuffle. Generate a binary tree of blends, e.g. if from
14864 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14866 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14867 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14868 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14869 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14870 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14871 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14872 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14874 // Make sure the initial size of the shuffle list is even.
14875 if (Shuffles.size() % 2)
14876 Shuffles.push_back(DAG.getUNDEF(VT));
14878 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14880 Shuffles[CurSize] = DAG.getUNDEF(VT);
14883 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14885 int Right = 2 * In + 1;
14886 SmallVector<int, 8> Mask(NumElems, -1);
14887 for (unsigned i = 0; i != NumElems; ++i) {
14888 if (VectorMask[i] == Left) {
14890 VectorMask[i] = In;
14891 } else if (VectorMask[i] == Right) {
14892 Mask[i] = i + NumElems;
14893 VectorMask[i] = In;
14898 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14901 return Shuffles[0];
14904 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14905 EVT VT = N->getValueType(0);
14907 // A vector built entirely of undefs is undef.
14908 if (ISD::allOperandsUndef(N))
14909 return DAG.getUNDEF(VT);
14911 // Check if we can express BUILD VECTOR via subvector extract.
14912 if (!LegalTypes && (N->getNumOperands() > 1)) {
14913 SDValue Op0 = N->getOperand(0);
14914 auto checkElem = [&](SDValue Op) -> uint64_t {
14915 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14916 (Op0.getOperand(0) == Op.getOperand(0)))
14917 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14918 return CNode->getZExtValue();
14922 int Offset = checkElem(Op0);
14923 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14924 if (Offset + i != checkElem(N->getOperand(i))) {
14930 if ((Offset == 0) &&
14931 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14932 return Op0.getOperand(0);
14933 if ((Offset != -1) &&
14934 ((Offset % N->getValueType(0).getVectorNumElements()) ==
14935 0)) // IDX must be multiple of output size.
14936 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14937 Op0.getOperand(0), Op0.getOperand(1));
14940 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14943 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14946 if (SDValue V = reduceBuildVecToShuffle(N))
14952 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14953 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14954 EVT OpVT = N->getOperand(0).getValueType();
14956 // If the operands are legal vectors, leave them alone.
14957 if (TLI.isTypeLegal(OpVT))
14961 EVT VT = N->getValueType(0);
14962 SmallVector<SDValue, 8> Ops;
14964 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14965 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14967 // Keep track of what we encounter.
14968 bool AnyInteger = false;
14969 bool AnyFP = false;
14970 for (const SDValue &Op : N->ops()) {
14971 if (ISD::BITCAST == Op.getOpcode() &&
14972 !Op.getOperand(0).getValueType().isVector())
14973 Ops.push_back(Op.getOperand(0));
14974 else if (ISD::UNDEF == Op.getOpcode())
14975 Ops.push_back(ScalarUndef);
14979 // Note whether we encounter an integer or floating point scalar.
14980 // If it's neither, bail out, it could be something weird like x86mmx.
14981 EVT LastOpVT = Ops.back().getValueType();
14982 if (LastOpVT.isFloatingPoint())
14984 else if (LastOpVT.isInteger())
14990 // If any of the operands is a floating point scalar bitcast to a vector,
14991 // use floating point types throughout, and bitcast everything.
14992 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14994 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14995 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14997 for (SDValue &Op : Ops) {
14998 if (Op.getValueType() == SVT)
15003 Op = DAG.getBitcast(SVT, Op);
15008 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15009 VT.getSizeInBits() / SVT.getSizeInBits());
15010 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15013 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15014 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15015 // most two distinct vectors the same size as the result, attempt to turn this
15016 // into a legal shuffle.
15017 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15018 EVT VT = N->getValueType(0);
15019 EVT OpVT = N->getOperand(0).getValueType();
15020 int NumElts = VT.getVectorNumElements();
15021 int NumOpElts = OpVT.getVectorNumElements();
15023 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15024 SmallVector<int, 8> Mask;
15026 for (SDValue Op : N->ops()) {
15027 // Peek through any bitcast.
15028 Op = peekThroughBitcast(Op);
15030 // UNDEF nodes convert to UNDEF shuffle mask values.
15031 if (Op.isUndef()) {
15032 Mask.append((unsigned)NumOpElts, -1);
15036 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15039 // What vector are we extracting the subvector from and at what index?
15040 SDValue ExtVec = Op.getOperand(0);
15042 // We want the EVT of the original extraction to correctly scale the
15043 // extraction index.
15044 EVT ExtVT = ExtVec.getValueType();
15046 // Peek through any bitcast.
15047 ExtVec = peekThroughBitcast(ExtVec);
15049 // UNDEF nodes convert to UNDEF shuffle mask values.
15050 if (ExtVec.isUndef()) {
15051 Mask.append((unsigned)NumOpElts, -1);
15055 if (!isa<ConstantSDNode>(Op.getOperand(1)))
15057 int ExtIdx = Op.getConstantOperandVal(1);
15059 // Ensure that we are extracting a subvector from a vector the same
15060 // size as the result.
15061 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15064 // Scale the subvector index to account for any bitcast.
15065 int NumExtElts = ExtVT.getVectorNumElements();
15066 if (0 == (NumExtElts % NumElts))
15067 ExtIdx /= (NumExtElts / NumElts);
15068 else if (0 == (NumElts % NumExtElts))
15069 ExtIdx *= (NumElts / NumExtElts);
15073 // At most we can reference 2 inputs in the final shuffle.
15074 if (SV0.isUndef() || SV0 == ExtVec) {
15076 for (int i = 0; i != NumOpElts; ++i)
15077 Mask.push_back(i + ExtIdx);
15078 } else if (SV1.isUndef() || SV1 == ExtVec) {
15080 for (int i = 0; i != NumOpElts; ++i)
15081 Mask.push_back(i + ExtIdx + NumElts);
15087 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15090 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15091 DAG.getBitcast(VT, SV1), Mask);
15094 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15095 // If we only have one input vector, we don't need to do any concatenation.
15096 if (N->getNumOperands() == 1)
15097 return N->getOperand(0);
15099 // Check if all of the operands are undefs.
15100 EVT VT = N->getValueType(0);
15101 if (ISD::allOperandsUndef(N))
15102 return DAG.getUNDEF(VT);
15104 // Optimize concat_vectors where all but the first of the vectors are undef.
15105 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15106 return Op.isUndef();
15108 SDValue In = N->getOperand(0);
15109 assert(In.getValueType().isVector() && "Must concat vectors");
15111 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15112 if (In->getOpcode() == ISD::BITCAST &&
15113 !In->getOperand(0)->getValueType(0).isVector()) {
15114 SDValue Scalar = In->getOperand(0);
15116 // If the bitcast type isn't legal, it might be a trunc of a legal type;
15117 // look through the trunc so we can still do the transform:
15118 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15119 if (Scalar->getOpcode() == ISD::TRUNCATE &&
15120 !TLI.isTypeLegal(Scalar.getValueType()) &&
15121 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15122 Scalar = Scalar->getOperand(0);
15124 EVT SclTy = Scalar->getValueType(0);
15126 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15129 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15130 if (VNTNumElms < 2)
15133 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15134 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15137 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15138 return DAG.getBitcast(VT, Res);
15142 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15143 // We have already tested above for an UNDEF only concatenation.
15144 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15145 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15146 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15147 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15149 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15150 SmallVector<SDValue, 8> Opnds;
15151 EVT SVT = VT.getScalarType();
15154 if (!SVT.isFloatingPoint()) {
15155 // If BUILD_VECTOR are from built from integer, they may have different
15156 // operand types. Get the smallest type and truncate all operands to it.
15157 bool FoundMinVT = false;
15158 for (const SDValue &Op : N->ops())
15159 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15160 EVT OpSVT = Op.getOperand(0)->getValueType(0);
15161 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15164 assert(FoundMinVT && "Concat vector type mismatch");
15167 for (const SDValue &Op : N->ops()) {
15168 EVT OpVT = Op.getValueType();
15169 unsigned NumElts = OpVT.getVectorNumElements();
15171 if (ISD::UNDEF == Op.getOpcode())
15172 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15174 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15175 if (SVT.isFloatingPoint()) {
15176 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
15177 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15179 for (unsigned i = 0; i != NumElts; ++i)
15181 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15186 assert(VT.getVectorNumElements() == Opnds.size() &&
15187 "Concat vector type mismatch");
15188 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15191 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15192 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15195 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15196 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15197 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15200 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15201 // nodes often generate nop CONCAT_VECTOR nodes.
15202 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15203 // place the incoming vectors at the exact same location.
15204 SDValue SingleSource = SDValue();
15205 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15208 SDValue Op = N->getOperand(i);
15213 // Check if this is the identity extract:
15214 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15217 // Find the single incoming vector for the extract_subvector.
15218 if (SingleSource.getNode()) {
15219 if (Op.getOperand(0) != SingleSource)
15222 SingleSource = Op.getOperand(0);
15224 // Check the source type is the same as the type of the result.
15225 // If not, this concat may extend the vector, so we can not
15226 // optimize it away.
15227 if (SingleSource.getValueType() != N->getValueType(0))
15231 unsigned IdentityIndex = i * PartNumElem;
15232 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15233 // The extract index must be constant.
15237 // Check that we are reading from the identity index.
15238 if (CS->getZExtValue() != IdentityIndex)
15242 if (SingleSource.getNode())
15243 return SingleSource;
15248 /// If we are extracting a subvector produced by a wide binary operator with at
15249 /// at least one operand that was the result of a vector concatenation, then try
15250 /// to use the narrow vector operands directly to avoid the concatenation and
15252 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15253 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15254 // some of these bailouts with other transforms.
15256 // The extract index must be a constant, so we can map it to a concat operand.
15257 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15261 // Only handle the case where we are doubling and then halving. A larger ratio
15262 // may require more than two narrow binops to replace the wide binop.
15263 EVT VT = Extract->getValueType(0);
15264 unsigned NumElems = VT.getVectorNumElements();
15265 assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15266 "Extract index is not a multiple of the vector length.");
15267 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15270 // We are looking for an optionally bitcasted wide vector binary operator
15271 // feeding an extract subvector.
15272 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15274 // TODO: The motivating case for this transform is an x86 AVX1 target. That
15275 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15276 // flavors, but no other 256-bit integer support. This could be extended to
15277 // handle any binop, but that may require fixing/adding other folds to avoid
15278 // codegen regressions.
15279 unsigned BOpcode = BinOp.getOpcode();
15280 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15283 // The binop must be a vector type, so we can chop it in half.
15284 EVT WideBVT = BinOp.getValueType();
15285 if (!WideBVT.isVector())
15288 // Bail out if the target does not support a narrower version of the binop.
15289 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15290 WideBVT.getVectorNumElements() / 2);
15291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15292 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15295 // Peek through bitcasts of the binary operator operands if needed.
15296 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15297 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15299 // We need at least one concatenation operation of a binop operand to make
15300 // this transform worthwhile. The concat must double the input vector sizes.
15301 // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15303 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15305 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15306 if (!ConcatL && !ConcatR)
15309 // If one of the binop operands was not the result of a concat, we must
15310 // extract a half-sized operand for our new narrow binop. We can't just reuse
15311 // the original extract index operand because we may have bitcasted.
15312 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15313 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15314 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15317 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15318 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15319 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15320 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15321 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15322 BinOp.getOperand(0),
15323 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15325 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15326 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15327 BinOp.getOperand(1),
15328 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15330 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15331 return DAG.getBitcast(VT, NarrowBinOp);
15334 /// If we are extracting a subvector from a wide vector load, convert to a
15335 /// narrow load to eliminate the extraction:
15336 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15337 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15338 // TODO: Add support for big-endian. The offset calculation must be adjusted.
15339 if (DAG.getDataLayout().isBigEndian())
15342 // TODO: The one-use check is overly conservative. Check the cost of the
15343 // extract instead or remove that condition entirely.
15344 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15345 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15346 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15350 // The narrow load will be offset from the base address of the old load if
15351 // we are extracting from something besides index 0 (little-endian).
15352 EVT VT = Extract->getValueType(0);
15354 SDValue BaseAddr = Ld->getOperand(1);
15355 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15357 // TODO: Use "BaseIndexOffset" to make this more effective.
15358 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15359 MachineFunction &MF = DAG.getMachineFunction();
15360 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15361 VT.getStoreSize());
15362 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15363 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15367 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15368 EVT NVT = N->getValueType(0);
15369 SDValue V = N->getOperand(0);
15371 // Extract from UNDEF is UNDEF.
15373 return DAG.getUNDEF(NVT);
15375 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15376 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15380 // (extract_subvec (concat V1, V2, ...), i)
15383 // Only operand 0 is checked as 'concat' assumes all inputs of the same
15385 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15386 isa<ConstantSDNode>(N->getOperand(1)) &&
15387 V->getOperand(0).getValueType() == NVT) {
15388 unsigned Idx = N->getConstantOperandVal(1);
15389 unsigned NumElems = NVT.getVectorNumElements();
15390 assert((Idx % NumElems) == 0 &&
15391 "IDX in concat is not a multiple of the result vector length.");
15392 return V->getOperand(Idx / NumElems);
15396 V = peekThroughBitcast(V);
15398 // If the input is a build vector. Try to make a smaller build vector.
15399 if (V->getOpcode() == ISD::BUILD_VECTOR) {
15400 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15401 EVT InVT = V->getValueType(0);
15402 unsigned ExtractSize = NVT.getSizeInBits();
15403 unsigned EltSize = InVT.getScalarSizeInBits();
15404 // Only do this if we won't split any elements.
15405 if (ExtractSize % EltSize == 0) {
15406 unsigned NumElems = ExtractSize / EltSize;
15407 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15408 InVT.getVectorElementType(), NumElems);
15409 if ((!LegalOperations ||
15410 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15411 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15412 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15415 // Extract the pieces from the original build_vector.
15416 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15417 makeArrayRef(V->op_begin() + IdxVal,
15419 return DAG.getBitcast(NVT, BuildVec);
15425 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15426 // Handle only simple case where vector being inserted and vector
15427 // being extracted are of same size.
15428 EVT SmallVT = V->getOperand(1).getValueType();
15429 if (!NVT.bitsEq(SmallVT))
15432 // Only handle cases where both indexes are constants.
15433 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15434 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15436 if (InsIdx && ExtIdx) {
15438 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15440 // indices are equal or bit offsets are equal => V1
15441 // otherwise => (extract_subvec V1, ExtIdx)
15442 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15443 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15444 return DAG.getBitcast(NVT, V->getOperand(1));
15445 return DAG.getNode(
15446 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15447 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15452 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15458 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15459 SDValue V, SelectionDAG &DAG) {
15461 EVT VT = V.getValueType();
15463 switch (V.getOpcode()) {
15467 case ISD::CONCAT_VECTORS: {
15468 EVT OpVT = V->getOperand(0).getValueType();
15469 int OpSize = OpVT.getVectorNumElements();
15470 SmallBitVector OpUsedElements(OpSize, false);
15471 bool FoundSimplification = false;
15472 SmallVector<SDValue, 4> NewOps;
15473 NewOps.reserve(V->getNumOperands());
15474 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15475 SDValue Op = V->getOperand(i);
15476 bool OpUsed = false;
15477 for (int j = 0; j < OpSize; ++j)
15478 if (UsedElements[i * OpSize + j]) {
15479 OpUsedElements[j] = true;
15483 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15484 : DAG.getUNDEF(OpVT));
15485 FoundSimplification |= Op == NewOps.back();
15486 OpUsedElements.reset();
15488 if (FoundSimplification)
15489 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15493 case ISD::INSERT_SUBVECTOR: {
15494 SDValue BaseV = V->getOperand(0);
15495 SDValue SubV = V->getOperand(1);
15496 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15500 int SubSize = SubV.getValueType().getVectorNumElements();
15501 int Idx = IdxN->getZExtValue();
15502 bool SubVectorUsed = false;
15503 SmallBitVector SubUsedElements(SubSize, false);
15504 for (int i = 0; i < SubSize; ++i)
15505 if (UsedElements[i + Idx]) {
15506 SubVectorUsed = true;
15507 SubUsedElements[i] = true;
15508 UsedElements[i + Idx] = false;
15511 // Now recurse on both the base and sub vectors.
15512 SDValue SimplifiedSubV =
15514 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15515 : DAG.getUNDEF(SubV.getValueType());
15516 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15517 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15518 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15519 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15525 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15526 SDValue N1, SelectionDAG &DAG) {
15527 EVT VT = SVN->getValueType(0);
15528 int NumElts = VT.getVectorNumElements();
15529 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15530 for (int M : SVN->getMask())
15531 if (M >= 0 && M < NumElts)
15532 N0UsedElements[M] = true;
15533 else if (M >= NumElts)
15534 N1UsedElements[M - NumElts] = true;
15536 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15537 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15538 if (S0 == N0 && S1 == N1)
15541 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15544 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15545 SDValue N1, SelectionDAG &DAG) {
15546 auto isUndefElt = [](SDValue V, int Idx) {
15547 // TODO - handle more cases as required.
15548 if (V.getOpcode() == ISD::BUILD_VECTOR)
15549 return V.getOperand(Idx).isUndef();
15550 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
15551 return (Idx != 0) || V.getOperand(0).isUndef();
15555 EVT VT = SVN->getValueType(0);
15556 unsigned NumElts = VT.getVectorNumElements();
15558 bool Changed = false;
15559 SmallVector<int, 8> NewMask;
15560 for (unsigned i = 0; i != NumElts; ++i) {
15561 int Idx = SVN->getMaskElt(i);
15562 if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15563 ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15567 NewMask.push_back(Idx);
15570 return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15575 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15576 // or turn a shuffle of a single concat into simpler shuffle then concat.
15577 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15578 EVT VT = N->getValueType(0);
15579 unsigned NumElts = VT.getVectorNumElements();
15581 SDValue N0 = N->getOperand(0);
15582 SDValue N1 = N->getOperand(1);
15583 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15585 SmallVector<SDValue, 4> Ops;
15586 EVT ConcatVT = N0.getOperand(0).getValueType();
15587 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15588 unsigned NumConcats = NumElts / NumElemsPerConcat;
15590 // Special case: shuffle(concat(A,B)) can be more efficiently represented
15591 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15592 // half vector elements.
15593 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15594 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15595 SVN->getMask().end(), [](int i) { return i == -1; })) {
15596 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15597 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15598 N1 = DAG.getUNDEF(ConcatVT);
15599 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15602 // Look at every vector that's inserted. We're looking for exact
15603 // subvector-sized copies from a concatenated vector
15604 for (unsigned I = 0; I != NumConcats; ++I) {
15605 // Make sure we're dealing with a copy.
15606 unsigned Begin = I * NumElemsPerConcat;
15607 bool AllUndef = true, NoUndef = true;
15608 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15609 if (SVN->getMaskElt(J) >= 0)
15616 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15619 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15620 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15623 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15624 if (FirstElt < N0.getNumOperands())
15625 Ops.push_back(N0.getOperand(FirstElt));
15627 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15629 } else if (AllUndef) {
15630 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15631 } else { // Mixed with general masks and undefs, can't do optimization.
15636 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15639 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15640 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15642 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15643 // a simplification in some sense, but it isn't appropriate in general: some
15644 // BUILD_VECTORs are substantially cheaper than others. The general case
15645 // of a BUILD_VECTOR requires inserting each element individually (or
15646 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15647 // all constants is a single constant pool load. A BUILD_VECTOR where each
15648 // element is identical is a splat. A BUILD_VECTOR where most of the operands
15649 // are undef lowers to a small number of element insertions.
15651 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15652 // We don't fold shuffles where one side is a non-zero constant, and we don't
15653 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15654 // non-constant operands. This seems to work out reasonably well in practice.
15655 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15657 const TargetLowering &TLI) {
15658 EVT VT = SVN->getValueType(0);
15659 unsigned NumElts = VT.getVectorNumElements();
15660 SDValue N0 = SVN->getOperand(0);
15661 SDValue N1 = SVN->getOperand(1);
15663 if (!N0->hasOneUse() || !N1->hasOneUse())
15666 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15667 // discussed above.
15668 if (!N1.isUndef()) {
15669 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15670 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15671 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15673 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15677 // If both inputs are splats of the same value then we can safely merge this
15678 // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
15679 bool IsSplat = false;
15680 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
15681 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
15683 if (SDValue Splat0 = BV0->getSplatValue())
15684 IsSplat = (Splat0 == BV1->getSplatValue());
15686 SmallVector<SDValue, 8> Ops;
15687 SmallSet<SDValue, 16> DuplicateOps;
15688 for (int M : SVN->getMask()) {
15689 SDValue Op = DAG.getUNDEF(VT.getScalarType());
15691 int Idx = M < (int)NumElts ? M : M - NumElts;
15692 SDValue &S = (M < (int)NumElts ? N0 : N1);
15693 if (S.getOpcode() == ISD::BUILD_VECTOR) {
15694 Op = S.getOperand(Idx);
15695 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15696 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
15697 Op = S.getOperand(0);
15699 // Operand can't be combined - bail out.
15704 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
15705 // generating a splat; semantically, this is fine, but it's likely to
15706 // generate low-quality code if the target can't reconstruct an appropriate
15708 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15709 if (!IsSplat && !DuplicateOps.insert(Op).second)
15715 // BUILD_VECTOR requires all inputs to be of the same type, find the
15716 // maximum type and extend them all.
15717 EVT SVT = VT.getScalarType();
15718 if (SVT.isInteger())
15719 for (SDValue &Op : Ops)
15720 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15721 if (SVT != VT.getScalarType())
15722 for (SDValue &Op : Ops)
15723 Op = TLI.isZExtFree(Op.getValueType(), SVT)
15724 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15725 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15726 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15729 // Match shuffles that can be converted to any_vector_extend_in_reg.
15730 // This is often generated during legalization.
15731 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15732 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15733 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15735 const TargetLowering &TLI,
15736 bool LegalOperations,
15738 EVT VT = SVN->getValueType(0);
15739 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15741 // TODO Add support for big-endian when we have a test case.
15742 if (!VT.isInteger() || IsBigEndian)
15745 unsigned NumElts = VT.getVectorNumElements();
15746 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15747 ArrayRef<int> Mask = SVN->getMask();
15748 SDValue N0 = SVN->getOperand(0);
15750 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15751 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15752 for (unsigned i = 0; i != NumElts; ++i) {
15755 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15762 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15763 // power-of-2 extensions as they are the most likely.
15764 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15765 // Check for non power of 2 vector sizes
15766 if (NumElts % Scale != 0)
15768 if (!isAnyExtend(Scale))
15771 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15772 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15773 if (!LegalTypes || TLI.isTypeLegal(OutVT))
15774 if (!LegalOperations ||
15775 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15776 return DAG.getBitcast(VT,
15777 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15783 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15784 // each source element of a large type into the lowest elements of a smaller
15785 // destination type. This is often generated during legalization.
15786 // If the source node itself was a '*_extend_vector_inreg' node then we should
15787 // then be able to remove it.
15788 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15789 SelectionDAG &DAG) {
15790 EVT VT = SVN->getValueType(0);
15791 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15793 // TODO Add support for big-endian when we have a test case.
15794 if (!VT.isInteger() || IsBigEndian)
15797 SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15799 unsigned Opcode = N0.getOpcode();
15800 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15801 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15802 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15805 SDValue N00 = N0.getOperand(0);
15806 ArrayRef<int> Mask = SVN->getMask();
15807 unsigned NumElts = VT.getVectorNumElements();
15808 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15809 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15810 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15812 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15814 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15816 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15817 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15818 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15819 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15820 for (unsigned i = 0; i != NumElts; ++i) {
15823 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15830 // At the moment we just handle the case where we've truncated back to the
15831 // same size as before the extension.
15832 // TODO: handle more extension/truncation cases as cases arise.
15833 if (EltSizeInBits != ExtSrcSizeInBits)
15836 // We can remove *extend_vector_inreg only if the truncation happens at
15837 // the same scale as the extension.
15838 if (isTruncate(ExtScale))
15839 return DAG.getBitcast(VT, N00);
15844 // Combine shuffles of splat-shuffles of the form:
15845 // shuffle (shuffle V, undef, splat-mask), undef, M
15846 // If splat-mask contains undef elements, we need to be careful about
15847 // introducing undef's in the folded mask which are not the result of composing
15848 // the masks of the shuffles.
15849 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15850 ShuffleVectorSDNode *Splat,
15851 SelectionDAG &DAG) {
15852 ArrayRef<int> SplatMask = Splat->getMask();
15853 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15855 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15856 // every undef mask element in the splat-shuffle has a corresponding undef
15857 // element in the user-shuffle's mask or if the composition of mask elements
15858 // would result in undef.
15859 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15860 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15861 // In this case it is not legal to simplify to the splat-shuffle because we
15862 // may be exposing the users of the shuffle an undef element at index 1
15863 // which was not there before the combine.
15864 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15865 // In this case the composition of masks yields SplatMask, so it's ok to
15866 // simplify to the splat-shuffle.
15867 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15868 // In this case the composed mask includes all undef elements of SplatMask
15869 // and in addition sets element zero to undef. It is safe to simplify to
15870 // the splat-shuffle.
15871 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15872 ArrayRef<int> SplatMask) {
15873 for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15874 if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15875 SplatMask[UserMask[i]] != -1)
15879 if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15880 return SDValue(Splat, 0);
15882 // Create a new shuffle with a mask that is composed of the two shuffles'
15884 SmallVector<int, 32> NewMask;
15885 for (int Idx : UserMask)
15886 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15888 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15889 Splat->getOperand(0), Splat->getOperand(1),
15893 /// If the shuffle mask is taking exactly one element from the first vector
15894 /// operand and passing through all other elements from the second vector
15895 /// operand, return the index of the mask element that is choosing an element
15896 /// from the first operand. Otherwise, return -1.
15897 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
15898 int MaskSize = Mask.size();
15899 int EltFromOp0 = -1;
15900 // TODO: This does not match if there are undef elements in the shuffle mask.
15901 // Should we ignore undefs in the shuffle mask instead? The trade-off is
15902 // removing an instruction (a shuffle), but losing the knowledge that some
15903 // vector lanes are not needed.
15904 for (int i = 0; i != MaskSize; ++i) {
15905 if (Mask[i] >= 0 && Mask[i] < MaskSize) {
15906 // We're looking for a shuffle of exactly one element from operand 0.
15907 if (EltFromOp0 != -1)
15910 } else if (Mask[i] != i + MaskSize) {
15911 // Nothing from operand 1 can change lanes.
15918 /// If a shuffle inserts exactly one element from a source vector operand into
15919 /// another vector operand and we can access the specified element as a scalar,
15920 /// then we can eliminate the shuffle.
15921 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
15922 SelectionDAG &DAG) {
15923 // First, check if we are taking one element of a vector and shuffling that
15924 // element into another vector.
15925 ArrayRef<int> Mask = Shuf->getMask();
15926 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
15927 SDValue Op0 = Shuf->getOperand(0);
15928 SDValue Op1 = Shuf->getOperand(1);
15929 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
15930 if (ShufOp0Index == -1) {
15931 // Commute mask and check again.
15932 ShuffleVectorSDNode::commuteMask(CommutedMask);
15933 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
15934 if (ShufOp0Index == -1)
15936 // Commute operands to match the commuted shuffle mask.
15937 std::swap(Op0, Op1);
15938 Mask = CommutedMask;
15941 // The shuffle inserts exactly one element from operand 0 into operand 1.
15942 // Now see if we can access that element as a scalar via a real insert element
15944 // TODO: We can try harder to locate the element as a scalar. Examples: it
15945 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
15946 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
15947 "Shuffle mask value must be from operand 0");
15948 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
15951 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
15952 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
15955 // There's an existing insertelement with constant insertion index, so we
15956 // don't need to check the legality/profitability of a replacement operation
15957 // that differs at most in the constant value. The target should be able to
15958 // lower any of those in a similar way. If not, legalization will expand this
15959 // to a scalar-to-vector plus shuffle.
15961 // Note that the shuffle may move the scalar from the position that the insert
15962 // element used. Therefore, our new insert element occurs at the shuffle's
15963 // mask index value, not the insert's index value.
15964 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
15965 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
15966 Op0.getOperand(2).getValueType());
15967 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
15968 Op1, Op0.getOperand(1), NewInsIndex);
15971 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15972 EVT VT = N->getValueType(0);
15973 unsigned NumElts = VT.getVectorNumElements();
15975 SDValue N0 = N->getOperand(0);
15976 SDValue N1 = N->getOperand(1);
15978 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15980 // Canonicalize shuffle undef, undef -> undef
15981 if (N0.isUndef() && N1.isUndef())
15982 return DAG.getUNDEF(VT);
15984 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15986 // Canonicalize shuffle v, v -> v, undef
15988 SmallVector<int, 8> NewMask;
15989 for (unsigned i = 0; i != NumElts; ++i) {
15990 int Idx = SVN->getMaskElt(i);
15991 if (Idx >= (int)NumElts) Idx -= NumElts;
15992 NewMask.push_back(Idx);
15994 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15997 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
15999 return DAG.getCommutedVectorShuffle(*SVN);
16001 // Remove references to rhs if it is undef
16002 if (N1.isUndef()) {
16003 bool Changed = false;
16004 SmallVector<int, 8> NewMask;
16005 for (unsigned i = 0; i != NumElts; ++i) {
16006 int Idx = SVN->getMaskElt(i);
16007 if (Idx >= (int)NumElts) {
16011 NewMask.push_back(Idx);
16014 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16017 // Simplify shuffle mask if a referenced element is UNDEF.
16018 if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
16021 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16024 // A shuffle of a single vector that is a splat can always be folded.
16025 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16026 if (N1->isUndef() && N0Shuf->isSplat())
16027 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16029 // If it is a splat, check if the argument vector is another splat or a
16031 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16032 SDNode *V = N0.getNode();
16034 // If this is a bit convert that changes the element type of the vector but
16035 // not the number of vector elements, look through it. Be careful not to
16036 // look though conversions that change things like v4f32 to v2f64.
16037 if (V->getOpcode() == ISD::BITCAST) {
16038 SDValue ConvInput = V->getOperand(0);
16039 if (ConvInput.getValueType().isVector() &&
16040 ConvInput.getValueType().getVectorNumElements() == NumElts)
16041 V = ConvInput.getNode();
16044 if (V->getOpcode() == ISD::BUILD_VECTOR) {
16045 assert(V->getNumOperands() == NumElts &&
16046 "BUILD_VECTOR has wrong number of operands");
16048 bool AllSame = true;
16049 for (unsigned i = 0; i != NumElts; ++i) {
16050 if (!V->getOperand(i).isUndef()) {
16051 Base = V->getOperand(i);
16055 // Splat of <u, u, u, u>, return <u, u, u, u>
16056 if (!Base.getNode())
16058 for (unsigned i = 0; i != NumElts; ++i) {
16059 if (V->getOperand(i) != Base) {
16064 // Splat of <x, x, x, x>, return <x, x, x, x>
16068 // Canonicalize any other splat as a build_vector.
16069 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16070 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16071 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16073 // We may have jumped through bitcasts, so the type of the
16074 // BUILD_VECTOR may not match the type of the shuffle.
16075 if (V->getValueType(0) != VT)
16076 NewBV = DAG.getBitcast(VT, NewBV);
16081 // There are various patterns used to build up a vector from smaller vectors,
16082 // subvectors, or elements. Scan chains of these and replace unused insertions
16083 // or components with undef.
16084 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
16087 // Match shuffles that can be converted to any_vector_extend_in_reg.
16088 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16091 // Combine "truncate_vector_in_reg" style shuffles.
16092 if (SDValue V = combineTruncationShuffle(SVN, DAG))
16095 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16096 Level < AfterLegalizeVectorOps &&
16098 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16099 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16100 if (SDValue V = partitionShuffleOfConcats(N, DAG))
16104 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16105 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16106 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16107 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16110 // If this shuffle only has a single input that is a bitcasted shuffle,
16111 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16112 // back to their original types.
16113 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16114 N1.isUndef() && Level < AfterLegalizeVectorOps &&
16115 TLI.isTypeLegal(VT)) {
16117 // Peek through the bitcast only if there is one user.
16119 while (BC0.getOpcode() == ISD::BITCAST) {
16120 if (!BC0.hasOneUse())
16122 BC0 = BC0.getOperand(0);
16125 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16127 return SmallVector<int, 8>(Mask.begin(), Mask.end());
16129 SmallVector<int, 8> NewMask;
16131 for (int s = 0; s != Scale; ++s)
16132 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16136 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16137 EVT SVT = VT.getScalarType();
16138 EVT InnerVT = BC0->getValueType(0);
16139 EVT InnerSVT = InnerVT.getScalarType();
16141 // Determine which shuffle works with the smaller scalar type.
16142 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16143 EVT ScaleSVT = ScaleVT.getScalarType();
16145 if (TLI.isTypeLegal(ScaleVT) &&
16146 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16147 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16148 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16149 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16151 // Scale the shuffle masks to the smaller scalar type.
16152 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16153 SmallVector<int, 8> InnerMask =
16154 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16155 SmallVector<int, 8> OuterMask =
16156 ScaleShuffleMask(SVN->getMask(), OuterScale);
16158 // Merge the shuffle masks.
16159 SmallVector<int, 8> NewMask;
16160 for (int M : OuterMask)
16161 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16163 // Test for shuffle mask legality over both commutations.
16164 SDValue SV0 = BC0->getOperand(0);
16165 SDValue SV1 = BC0->getOperand(1);
16166 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16168 std::swap(SV0, SV1);
16169 ShuffleVectorSDNode::commuteMask(NewMask);
16170 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16174 SV0 = DAG.getBitcast(ScaleVT, SV0);
16175 SV1 = DAG.getBitcast(ScaleVT, SV1);
16176 return DAG.getBitcast(
16177 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16183 // Canonicalize shuffles according to rules:
16184 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16185 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16186 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16187 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16188 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16189 TLI.isTypeLegal(VT)) {
16190 // The incoming shuffle must be of the same type as the result of the
16191 // current shuffle.
16192 assert(N1->getOperand(0).getValueType() == VT &&
16193 "Shuffle types don't match");
16195 SDValue SV0 = N1->getOperand(0);
16196 SDValue SV1 = N1->getOperand(1);
16197 bool HasSameOp0 = N0 == SV0;
16198 bool IsSV1Undef = SV1.isUndef();
16199 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16200 // Commute the operands of this shuffle so that next rule
16202 return DAG.getCommutedVectorShuffle(*SVN);
16205 // Try to fold according to rules:
16206 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16207 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16208 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16209 // Don't try to fold shuffles with illegal type.
16210 // Only fold if this shuffle is the only user of the other shuffle.
16211 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16212 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16213 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16215 // Don't try to fold splats; they're likely to simplify somehow, or they
16217 if (OtherSV->isSplat())
16220 // The incoming shuffle must be of the same type as the result of the
16221 // current shuffle.
16222 assert(OtherSV->getOperand(0).getValueType() == VT &&
16223 "Shuffle types don't match");
16226 SmallVector<int, 4> Mask;
16227 // Compute the combined shuffle mask for a shuffle with SV0 as the first
16228 // operand, and SV1 as the second operand.
16229 for (unsigned i = 0; i != NumElts; ++i) {
16230 int Idx = SVN->getMaskElt(i);
16232 // Propagate Undef.
16233 Mask.push_back(Idx);
16237 SDValue CurrentVec;
16238 if (Idx < (int)NumElts) {
16239 // This shuffle index refers to the inner shuffle N0. Lookup the inner
16240 // shuffle mask to identify which vector is actually referenced.
16241 Idx = OtherSV->getMaskElt(Idx);
16243 // Propagate Undef.
16244 Mask.push_back(Idx);
16248 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16249 : OtherSV->getOperand(1);
16251 // This shuffle index references an element within N1.
16255 // Simple case where 'CurrentVec' is UNDEF.
16256 if (CurrentVec.isUndef()) {
16257 Mask.push_back(-1);
16261 // Canonicalize the shuffle index. We don't know yet if CurrentVec
16262 // will be the first or second operand of the combined shuffle.
16263 Idx = Idx % NumElts;
16264 if (!SV0.getNode() || SV0 == CurrentVec) {
16265 // Ok. CurrentVec is the left hand side.
16266 // Update the mask accordingly.
16268 Mask.push_back(Idx);
16272 // Bail out if we cannot convert the shuffle pair into a single shuffle.
16273 if (SV1.getNode() && SV1 != CurrentVec)
16276 // Ok. CurrentVec is the right hand side.
16277 // Update the mask accordingly.
16279 Mask.push_back(Idx + NumElts);
16282 // Check if all indices in Mask are Undef. In case, propagate Undef.
16283 bool isUndefMask = true;
16284 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16285 isUndefMask &= Mask[i] < 0;
16288 return DAG.getUNDEF(VT);
16290 if (!SV0.getNode())
16291 SV0 = DAG.getUNDEF(VT);
16292 if (!SV1.getNode())
16293 SV1 = DAG.getUNDEF(VT);
16295 // Avoid introducing shuffles with illegal mask.
16296 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16297 ShuffleVectorSDNode::commuteMask(Mask);
16299 if (!TLI.isShuffleMaskLegal(Mask, VT))
16302 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16303 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16304 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16305 std::swap(SV0, SV1);
16308 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16309 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16310 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16311 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16317 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16318 SDValue InVal = N->getOperand(0);
16319 EVT VT = N->getValueType(0);
16321 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16322 // with a VECTOR_SHUFFLE and possible truncate.
16323 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16324 SDValue InVec = InVal->getOperand(0);
16325 SDValue EltNo = InVal->getOperand(1);
16326 auto InVecT = InVec.getValueType();
16327 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16328 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16329 int Elt = C0->getZExtValue();
16332 // If we have an implict truncate do truncate here as long as it's legal.
16333 // if it's not legal, this should
16334 if (VT.getScalarType() != InVal.getValueType() &&
16335 InVal.getValueType().isScalarInteger() &&
16336 isTypeLegal(VT.getScalarType())) {
16338 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16339 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16341 if (VT.getScalarType() == InVecT.getScalarType() &&
16342 VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16343 TLI.isShuffleMaskLegal(NewMask, VT)) {
16344 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16345 DAG.getUNDEF(InVecT), NewMask);
16346 // If the initial vector is the correct size this shuffle is a
16350 // If not we must truncate the vector.
16351 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16352 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16353 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16355 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16356 VT.getVectorNumElements());
16357 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16368 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16369 EVT VT = N->getValueType(0);
16370 SDValue N0 = N->getOperand(0);
16371 SDValue N1 = N->getOperand(1);
16372 SDValue N2 = N->getOperand(2);
16374 // If inserting an UNDEF, just return the original vector.
16378 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16379 // us to pull BITCASTs from input to output.
16380 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16381 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16382 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16384 // If this is an insert of an extracted vector into an undef vector, we can
16385 // just use the input to the extract.
16386 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16387 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16388 return N1.getOperand(0);
16390 // If we are inserting a bitcast value into an undef, with the same
16391 // number of elements, just use the bitcast input of the extract.
16392 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16393 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16394 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16395 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16396 N1.getOperand(0).getOperand(1) == N2 &&
16397 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16398 VT.getVectorNumElements()) {
16399 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16402 // If both N1 and N2 are bitcast values on which insert_subvector
16403 // would makes sense, pull the bitcast through.
16404 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16405 // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16406 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16407 SDValue CN0 = N0.getOperand(0);
16408 SDValue CN1 = N1.getOperand(0);
16409 if (CN0.getValueType().getVectorElementType() ==
16410 CN1.getValueType().getVectorElementType() &&
16411 CN0.getValueType().getVectorNumElements() ==
16412 VT.getVectorNumElements()) {
16413 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16414 CN0.getValueType(), CN0, CN1, N2);
16415 return DAG.getBitcast(VT, NewINSERT);
16419 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16420 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16421 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16422 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16423 N0.getOperand(1).getValueType() == N1.getValueType() &&
16424 N0.getOperand(2) == N2)
16425 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16428 if (!isa<ConstantSDNode>(N2))
16431 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16433 // Canonicalize insert_subvector dag nodes.
16435 // (insert_subvector (insert_subvector A, Idx0), Idx1)
16436 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16437 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16438 N1.getValueType() == N0.getOperand(1).getValueType() &&
16439 isa<ConstantSDNode>(N0.getOperand(2))) {
16440 unsigned OtherIdx = N0.getConstantOperandVal(2);
16441 if (InsIdx < OtherIdx) {
16443 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16444 N0.getOperand(0), N1, N2);
16445 AddToWorklist(NewOp.getNode());
16446 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16447 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16451 // If the input vector is a concatenation, and the insert replaces
16452 // one of the pieces, we can optimize into a single concat_vectors.
16453 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16454 N0.getOperand(0).getValueType() == N1.getValueType()) {
16455 unsigned Factor = N1.getValueType().getVectorNumElements();
16457 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16458 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16460 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16466 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16467 SDValue N0 = N->getOperand(0);
16469 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16470 if (N0->getOpcode() == ISD::FP16_TO_FP)
16471 return N0->getOperand(0);
16476 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16477 SDValue N0 = N->getOperand(0);
16479 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16480 if (N0->getOpcode() == ISD::AND) {
16481 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16482 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16483 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16491 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16492 /// with the destination vector and a zero vector.
16493 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16494 /// vector_shuffle V, Zero, <0, 4, 2, 4>
16495 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16496 EVT VT = N->getValueType(0);
16497 SDValue LHS = N->getOperand(0);
16498 SDValue RHS = peekThroughBitcast(N->getOperand(1));
16501 // Make sure we're not running after operation legalization where it
16502 // may have custom lowered the vector shuffles.
16503 if (LegalOperations)
16506 if (N->getOpcode() != ISD::AND)
16509 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16512 EVT RVT = RHS.getValueType();
16513 unsigned NumElts = RHS.getNumOperands();
16515 // Attempt to create a valid clear mask, splitting the mask into
16516 // sub elements and checking to see if each is
16517 // all zeros or all ones - suitable for shuffle masking.
16518 auto BuildClearMask = [&](int Split) {
16519 int NumSubElts = NumElts * Split;
16520 int NumSubBits = RVT.getScalarSizeInBits() / Split;
16522 SmallVector<int, 8> Indices;
16523 for (int i = 0; i != NumSubElts; ++i) {
16524 int EltIdx = i / Split;
16525 int SubIdx = i % Split;
16526 SDValue Elt = RHS.getOperand(EltIdx);
16527 if (Elt.isUndef()) {
16528 Indices.push_back(-1);
16533 if (isa<ConstantSDNode>(Elt))
16534 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16535 else if (isa<ConstantFPSDNode>(Elt))
16536 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16540 // Extract the sub element from the constant bit mask.
16541 if (DAG.getDataLayout().isBigEndian()) {
16542 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16544 Bits.lshrInPlace(SubIdx * NumSubBits);
16548 Bits = Bits.trunc(NumSubBits);
16550 if (Bits.isAllOnesValue())
16551 Indices.push_back(i);
16552 else if (Bits == 0)
16553 Indices.push_back(i + NumSubElts);
16558 // Let's see if the target supports this vector_shuffle.
16559 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16560 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16561 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16564 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16565 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16566 DAG.getBitcast(ClearVT, LHS),
16570 // Determine maximum split level (byte level masking).
16572 if (RVT.getScalarSizeInBits() % 8 == 0)
16573 MaxSplit = RVT.getScalarSizeInBits() / 8;
16575 for (int Split = 1; Split <= MaxSplit; ++Split)
16576 if (RVT.getScalarSizeInBits() % Split == 0)
16577 if (SDValue S = BuildClearMask(Split))
16583 /// Visit a binary vector operation, like ADD.
16584 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16585 assert(N->getValueType(0).isVector() &&
16586 "SimplifyVBinOp only works on vectors!");
16588 SDValue LHS = N->getOperand(0);
16589 SDValue RHS = N->getOperand(1);
16590 SDValue Ops[] = {LHS, RHS};
16592 // See if we can constant fold the vector operation.
16593 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16594 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16597 // Try to convert a constant mask AND into a shuffle clear mask.
16598 if (SDValue Shuffle = XformToShuffleWithZero(N))
16601 // Type legalization might introduce new shuffles in the DAG.
16602 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16603 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
16604 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16605 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16606 LHS.getOperand(1).isUndef() &&
16607 RHS.getOperand(1).isUndef()) {
16608 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16609 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16611 if (SVN0->getMask().equals(SVN1->getMask())) {
16612 EVT VT = N->getValueType(0);
16613 SDValue UndefVector = LHS.getOperand(1);
16614 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16615 LHS.getOperand(0), RHS.getOperand(0),
16617 AddUsersToWorklist(N);
16618 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16626 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16628 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16630 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16631 cast<CondCodeSDNode>(N0.getOperand(2))->get());
16633 // If we got a simplified select_cc node back from SimplifySelectCC, then
16634 // break it down into a new SETCC node, and a new SELECT node, and then return
16635 // the SELECT node, since we were called with a SELECT node.
16636 if (SCC.getNode()) {
16637 // Check to see if we got a select_cc back (to turn into setcc/select).
16638 // Otherwise, just return whatever node we got back, like fabs.
16639 if (SCC.getOpcode() == ISD::SELECT_CC) {
16640 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16642 SCC.getOperand(0), SCC.getOperand(1),
16643 SCC.getOperand(4));
16644 AddToWorklist(SETCC.getNode());
16645 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16646 SCC.getOperand(2), SCC.getOperand(3));
16654 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16655 /// being selected between, see if we can simplify the select. Callers of this
16656 /// should assume that TheSelect is deleted if this returns true. As such, they
16657 /// should return the appropriate thing (e.g. the node) back to the top-level of
16658 /// the DAG combiner loop to avoid it being looked at.
16659 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16661 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16662 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16663 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16664 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16665 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16666 SDValue Sqrt = RHS;
16669 const ConstantFPSDNode *Zero = nullptr;
16671 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16672 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16673 CmpLHS = TheSelect->getOperand(0);
16674 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16676 // SELECT or VSELECT
16677 SDValue Cmp = TheSelect->getOperand(0);
16678 if (Cmp.getOpcode() == ISD::SETCC) {
16679 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16680 CmpLHS = Cmp.getOperand(0);
16681 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16684 if (Zero && Zero->isZero() &&
16685 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16686 CC == ISD::SETULT || CC == ISD::SETLT)) {
16687 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16688 CombineTo(TheSelect, Sqrt);
16693 // Cannot simplify select with vector condition
16694 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16696 // If this is a select from two identical things, try to pull the operation
16697 // through the select.
16698 if (LHS.getOpcode() != RHS.getOpcode() ||
16699 !LHS.hasOneUse() || !RHS.hasOneUse())
16702 // If this is a load and the token chain is identical, replace the select
16703 // of two loads with a load through a select of the address to load from.
16704 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16705 // constants have been dropped into the constant pool.
16706 if (LHS.getOpcode() == ISD::LOAD) {
16707 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16708 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16710 // Token chains must be identical.
16711 if (LHS.getOperand(0) != RHS.getOperand(0) ||
16712 // Do not let this transformation reduce the number of volatile loads.
16713 LLD->isVolatile() || RLD->isVolatile() ||
16714 // FIXME: If either is a pre/post inc/dec load,
16715 // we'd need to split out the address adjustment.
16716 LLD->isIndexed() || RLD->isIndexed() ||
16717 // If this is an EXTLOAD, the VT's must match.
16718 LLD->getMemoryVT() != RLD->getMemoryVT() ||
16719 // If this is an EXTLOAD, the kind of extension must match.
16720 (LLD->getExtensionType() != RLD->getExtensionType() &&
16721 // The only exception is if one of the extensions is anyext.
16722 LLD->getExtensionType() != ISD::EXTLOAD &&
16723 RLD->getExtensionType() != ISD::EXTLOAD) ||
16724 // FIXME: this discards src value information. This is
16725 // over-conservative. It would be beneficial to be able to remember
16726 // both potential memory locations. Since we are discarding
16727 // src value info, don't do the transformation if the memory
16728 // locations are not in the default address space.
16729 LLD->getPointerInfo().getAddrSpace() != 0 ||
16730 RLD->getPointerInfo().getAddrSpace() != 0 ||
16731 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16732 LLD->getBasePtr().getValueType()))
16735 // Check that the select condition doesn't reach either load. If so,
16736 // folding this will induce a cycle into the DAG. If not, this is safe to
16737 // xform, so create a select of the addresses.
16739 if (TheSelect->getOpcode() == ISD::SELECT) {
16740 SDNode *CondNode = TheSelect->getOperand(0).getNode();
16741 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16742 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16744 // The loads must not depend on one another.
16745 if (LLD->isPredecessorOf(RLD) ||
16746 RLD->isPredecessorOf(LLD))
16748 Addr = DAG.getSelect(SDLoc(TheSelect),
16749 LLD->getBasePtr().getValueType(),
16750 TheSelect->getOperand(0), LLD->getBasePtr(),
16751 RLD->getBasePtr());
16752 } else { // Otherwise SELECT_CC
16753 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16754 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16756 if ((LLD->hasAnyUseOfValue(1) &&
16757 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16758 (RLD->hasAnyUseOfValue(1) &&
16759 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16762 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16763 LLD->getBasePtr().getValueType(),
16764 TheSelect->getOperand(0),
16765 TheSelect->getOperand(1),
16766 LLD->getBasePtr(), RLD->getBasePtr(),
16767 TheSelect->getOperand(4));
16771 // It is safe to replace the two loads if they have different alignments,
16772 // but the new load must be the minimum (most restrictive) alignment of the
16774 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16775 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16776 if (!RLD->isInvariant())
16777 MMOFlags &= ~MachineMemOperand::MOInvariant;
16778 if (!RLD->isDereferenceable())
16779 MMOFlags &= ~MachineMemOperand::MODereferenceable;
16780 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16781 // FIXME: Discards pointer and AA info.
16782 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16783 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16786 // FIXME: Discards pointer and AA info.
16787 Load = DAG.getExtLoad(
16788 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16789 : LLD->getExtensionType(),
16790 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16791 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16794 // Users of the select now use the result of the load.
16795 CombineTo(TheSelect, Load);
16797 // Users of the old loads now use the new load's chain. We know the
16798 // old-load value is dead now.
16799 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16800 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16807 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16809 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16810 SDValue N1, SDValue N2, SDValue N3,
16811 ISD::CondCode CC) {
16812 // If this is a select where the false operand is zero and the compare is a
16813 // check of the sign bit, see if we can perform the "gzip trick":
16814 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16815 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16816 EVT XType = N0.getValueType();
16817 EVT AType = N2.getValueType();
16818 if (!isNullConstant(N3) || !XType.bitsGE(AType))
16821 // If the comparison is testing for a positive value, we have to invert
16822 // the sign bit mask, so only do that transform if the target has a bitwise
16823 // 'and not' instruction (the invert is free).
16824 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16825 // (X > -1) ? A : 0
16826 // (X > 0) ? X : 0 <-- This is canonical signed max.
16827 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16829 } else if (CC == ISD::SETLT) {
16831 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
16832 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16838 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16840 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16841 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16842 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16843 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16844 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16845 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16846 AddToWorklist(Shift.getNode());
16848 if (XType.bitsGT(AType)) {
16849 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16850 AddToWorklist(Shift.getNode());
16853 if (CC == ISD::SETGT)
16854 Shift = DAG.getNOT(DL, Shift, AType);
16856 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16859 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16860 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16861 AddToWorklist(Shift.getNode());
16863 if (XType.bitsGT(AType)) {
16864 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16865 AddToWorklist(Shift.getNode());
16868 if (CC == ISD::SETGT)
16869 Shift = DAG.getNOT(DL, Shift, AType);
16871 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16874 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16875 /// where 'cond' is the comparison specified by CC.
16876 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16877 SDValue N2, SDValue N3, ISD::CondCode CC,
16878 bool NotExtCompare) {
16879 // (x ? y : y) -> y.
16880 if (N2 == N3) return N2;
16882 EVT VT = N2.getValueType();
16883 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16884 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16886 // Determine if the condition we're dealing with is constant
16887 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16888 N0, N1, CC, DL, false);
16889 if (SCC.getNode()) AddToWorklist(SCC.getNode());
16891 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16892 // fold select_cc true, x, y -> x
16893 // fold select_cc false, x, y -> y
16894 return !SCCC->isNullValue() ? N2 : N3;
16897 // Check to see if we can simplify the select into an fabs node
16898 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16899 // Allow either -0.0 or 0.0
16900 if (CFP->isZero()) {
16901 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16902 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16903 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16904 N2 == N3.getOperand(0))
16905 return DAG.getNode(ISD::FABS, DL, VT, N0);
16907 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16908 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16909 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16910 N2.getOperand(0) == N3)
16911 return DAG.getNode(ISD::FABS, DL, VT, N3);
16915 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16916 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16917 // in it. This is a win when the constant is not otherwise available because
16918 // it replaces two constant pool loads with one. We only do this if the FP
16919 // type is known to be legal, because if it isn't, then we are before legalize
16920 // types an we want the other legalization to happen first (e.g. to avoid
16921 // messing with soft float) and if the ConstantFP is not legal, because if
16922 // it is legal, we may not need to store the FP constant in a constant pool.
16923 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16924 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16925 if (TLI.isTypeLegal(N2.getValueType()) &&
16926 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16927 TargetLowering::Legal &&
16928 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16929 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16930 // If both constants have multiple uses, then we won't need to do an
16931 // extra load, they are likely around in registers for other users.
16932 (TV->hasOneUse() || FV->hasOneUse())) {
16933 Constant *Elts[] = {
16934 const_cast<ConstantFP*>(FV->getConstantFPValue()),
16935 const_cast<ConstantFP*>(TV->getConstantFPValue())
16937 Type *FPTy = Elts[0]->getType();
16938 const DataLayout &TD = DAG.getDataLayout();
16940 // Create a ConstantArray of the two constants.
16941 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16943 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16944 TD.getPrefTypeAlignment(FPTy));
16945 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16947 // Get the offsets to the 0 and 1 element of the array so that we can
16948 // select between them.
16949 SDValue Zero = DAG.getIntPtrConstant(0, DL);
16950 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16951 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16953 SDValue Cond = DAG.getSetCC(DL,
16954 getSetCCResultType(N0.getValueType()),
16956 AddToWorklist(Cond.getNode());
16957 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16959 AddToWorklist(CstOffset.getNode());
16960 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16962 AddToWorklist(CPIdx.getNode());
16963 return DAG.getLoad(
16964 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16965 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16970 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16973 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16974 // where y is has a single bit set.
16975 // A plaintext description would be, we can turn the SELECT_CC into an AND
16976 // when the condition can be materialized as an all-ones register. Any
16977 // single bit-test can be materialized as an all-ones register with
16978 // shift-left and shift-right-arith.
16979 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16980 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16981 SDValue AndLHS = N0->getOperand(0);
16982 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16983 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16984 // Shift the tested bit over the sign bit.
16985 const APInt &AndMask = ConstAndRHS->getAPIntValue();
16987 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16988 getShiftAmountTy(AndLHS.getValueType()));
16989 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16991 // Now arithmetic right shift it all the way over, so the result is either
16992 // all-ones, or zero.
16994 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16995 getShiftAmountTy(Shl.getValueType()));
16996 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16998 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17002 // fold select C, 16, 0 -> shl C, 4
17003 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17004 TLI.getBooleanContents(N0.getValueType()) ==
17005 TargetLowering::ZeroOrOneBooleanContent) {
17007 // If the caller doesn't want us to simplify this into a zext of a compare,
17009 if (NotExtCompare && N2C->isOne())
17012 // Get a SetCC of the condition
17013 // NOTE: Don't create a SETCC if it's not legal on this target.
17014 if (!LegalOperations ||
17015 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17017 // cast from setcc result type to select result type
17019 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17021 if (N2.getValueType().bitsLT(SCC.getValueType()))
17022 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17023 N2.getValueType());
17025 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17026 N2.getValueType(), SCC);
17028 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17029 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17030 N2.getValueType(), SCC);
17033 AddToWorklist(SCC.getNode());
17034 AddToWorklist(Temp.getNode());
17039 // shl setcc result by log2 n2c
17040 return DAG.getNode(
17041 ISD::SHL, DL, N2.getValueType(), Temp,
17042 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17043 getShiftAmountTy(Temp.getValueType())));
17047 // Check to see if this is an integer abs.
17048 // select_cc setg[te] X, 0, X, -X ->
17049 // select_cc setgt X, -1, X, -X ->
17050 // select_cc setl[te] X, 0, -X, X ->
17051 // select_cc setlt X, 1, -X, X ->
17052 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17054 ConstantSDNode *SubC = nullptr;
17055 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17056 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17057 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17058 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17059 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17060 (N1C->isOne() && CC == ISD::SETLT)) &&
17061 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17062 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17064 EVT XType = N0.getValueType();
17065 if (SubC && SubC->isNullValue() && XType.isInteger()) {
17067 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17069 DAG.getConstant(XType.getSizeInBits() - 1, DL,
17070 getShiftAmountTy(N0.getValueType())));
17071 SDValue Add = DAG.getNode(ISD::ADD, DL,
17073 AddToWorklist(Shift.getNode());
17074 AddToWorklist(Add.getNode());
17075 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17079 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17080 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17081 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17082 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17083 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17084 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17085 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17086 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17087 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17088 SDValue ValueOnZero = N2;
17089 SDValue Count = N3;
17090 // If the condition is NE instead of E, swap the operands.
17091 if (CC == ISD::SETNE)
17092 std::swap(ValueOnZero, Count);
17093 // Check if the value on zero is a constant equal to the bits in the type.
17094 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17095 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17096 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17097 // legal, combine to just cttz.
17098 if ((Count.getOpcode() == ISD::CTTZ ||
17099 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17100 N0 == Count.getOperand(0) &&
17101 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17102 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17103 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17104 // legal, combine to just ctlz.
17105 if ((Count.getOpcode() == ISD::CTLZ ||
17106 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17107 N0 == Count.getOperand(0) &&
17108 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17109 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17117 /// This is a stub for TargetLowering::SimplifySetCC.
17118 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17119 ISD::CondCode Cond, const SDLoc &DL,
17120 bool foldBooleans) {
17121 TargetLowering::DAGCombinerInfo
17122 DagCombineInfo(DAG, Level, false, this);
17123 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17126 /// Given an ISD::SDIV node expressing a divide by constant, return
17127 /// a DAG expression to select that will generate the same value by multiplying
17128 /// by a magic number.
17129 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17130 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17131 // when optimising for minimum size, we don't want to expand a div to a mul
17133 if (DAG.getMachineFunction().getFunction().optForMinSize())
17136 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17140 // Avoid division by zero.
17141 if (C->isNullValue())
17144 std::vector<SDNode *> Built;
17146 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17148 for (SDNode *N : Built)
17153 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17154 /// DAG expression that will generate the same value by right shifting.
17155 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17156 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17160 // Avoid division by zero.
17161 if (C->isNullValue())
17164 std::vector<SDNode *> Built;
17165 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17167 for (SDNode *N : Built)
17172 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17173 /// expression that will generate the same value by multiplying by a magic
17175 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17176 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17177 // when optimising for minimum size, we don't want to expand a div to a mul
17179 if (DAG.getMachineFunction().getFunction().optForMinSize())
17182 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17186 // Avoid division by zero.
17187 if (C->isNullValue())
17190 std::vector<SDNode *> Built;
17192 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17194 for (SDNode *N : Built)
17199 /// Determines the LogBase2 value for a non-null input value using the
17200 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17201 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17202 EVT VT = V.getValueType();
17203 unsigned EltBits = VT.getScalarSizeInBits();
17204 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17205 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17206 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17210 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17211 /// For the reciprocal, we need to find the zero of the function:
17212 /// F(X) = A X - 1 [which has a zero at X = 1/A]
17214 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17215 /// does not require additional intermediate precision]
17216 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17217 if (Level >= AfterLegalizeDAG)
17220 // TODO: Handle half and/or extended types?
17221 EVT VT = Op.getValueType();
17222 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17225 // If estimates are explicitly disabled for this function, we're done.
17226 MachineFunction &MF = DAG.getMachineFunction();
17227 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17228 if (Enabled == TLI.ReciprocalEstimate::Disabled)
17231 // Estimates may be explicitly enabled for this type with a custom number of
17232 // refinement steps.
17233 int Iterations = TLI.getDivRefinementSteps(VT, MF);
17234 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17235 AddToWorklist(Est.getNode());
17238 EVT VT = Op.getValueType();
17240 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17242 // Newton iterations: Est = Est + Est (1 - Arg * Est)
17243 for (int i = 0; i < Iterations; ++i) {
17244 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17245 AddToWorklist(NewEst.getNode());
17247 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17248 AddToWorklist(NewEst.getNode());
17250 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17251 AddToWorklist(NewEst.getNode());
17253 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17254 AddToWorklist(Est.getNode());
17263 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17264 /// For the reciprocal sqrt, we need to find the zero of the function:
17265 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17267 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17268 /// As a result, we precompute A/2 prior to the iteration loop.
17269 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17270 unsigned Iterations,
17271 SDNodeFlags Flags, bool Reciprocal) {
17272 EVT VT = Arg.getValueType();
17274 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17276 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17277 // this entire sequence requires only one FP constant.
17278 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17279 AddToWorklist(HalfArg.getNode());
17281 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17282 AddToWorklist(HalfArg.getNode());
17284 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17285 for (unsigned i = 0; i < Iterations; ++i) {
17286 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17287 AddToWorklist(NewEst.getNode());
17289 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17290 AddToWorklist(NewEst.getNode());
17292 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17293 AddToWorklist(NewEst.getNode());
17295 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17296 AddToWorklist(Est.getNode());
17299 // If non-reciprocal square root is requested, multiply the result by Arg.
17301 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17302 AddToWorklist(Est.getNode());
17308 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17309 /// For the reciprocal sqrt, we need to find the zero of the function:
17310 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17312 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17313 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17314 unsigned Iterations,
17315 SDNodeFlags Flags, bool Reciprocal) {
17316 EVT VT = Arg.getValueType();
17318 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17319 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17321 // This routine must enter the loop below to work correctly
17322 // when (Reciprocal == false).
17323 assert(Iterations > 0);
17325 // Newton iterations for reciprocal square root:
17326 // E = (E * -0.5) * ((A * E) * E + -3.0)
17327 for (unsigned i = 0; i < Iterations; ++i) {
17328 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17329 AddToWorklist(AE.getNode());
17331 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17332 AddToWorklist(AEE.getNode());
17334 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17335 AddToWorklist(RHS.getNode());
17337 // When calculating a square root at the last iteration build:
17338 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17339 // (notice a common subexpression)
17341 if (Reciprocal || (i + 1) < Iterations) {
17342 // RSQRT: LHS = (E * -0.5)
17343 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17345 // SQRT: LHS = (A * E) * -0.5
17346 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17348 AddToWorklist(LHS.getNode());
17350 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17351 AddToWorklist(Est.getNode());
17357 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17358 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17359 /// Op can be zero.
17360 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17362 if (Level >= AfterLegalizeDAG)
17365 // TODO: Handle half and/or extended types?
17366 EVT VT = Op.getValueType();
17367 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17370 // If estimates are explicitly disabled for this function, we're done.
17371 MachineFunction &MF = DAG.getMachineFunction();
17372 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17373 if (Enabled == TLI.ReciprocalEstimate::Disabled)
17376 // Estimates may be explicitly enabled for this type with a custom number of
17377 // refinement steps.
17378 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17380 bool UseOneConstNR = false;
17382 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17384 AddToWorklist(Est.getNode());
17387 Est = UseOneConstNR
17388 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17389 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17392 // Unfortunately, Est is now NaN if the input was exactly 0.0.
17393 // Select out this case and force the answer to 0.0.
17394 EVT VT = Op.getValueType();
17397 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17398 EVT CCVT = getSetCCResultType(VT);
17399 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17400 AddToWorklist(ZeroCmp.getNode());
17402 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
17403 ZeroCmp, FPZero, Est);
17404 AddToWorklist(Est.getNode());
17413 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17414 return buildSqrtEstimateImpl(Op, Flags, true);
17417 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17418 return buildSqrtEstimateImpl(Op, Flags, false);
17421 /// Return true if base is a frame index, which is known not to alias with
17422 /// anything but itself. Provides base object and offset as results.
17423 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
17424 const GlobalValue *&GV, const void *&CV) {
17425 // Assume it is a primitive operation.
17426 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
17428 // If it's an adding a simple constant then integrate the offset.
17429 if (Base.getOpcode() == ISD::ADD) {
17430 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
17431 Base = Base.getOperand(0);
17432 Offset += C->getSExtValue();
17436 // Return the underlying GlobalValue, and update the Offset. Return false
17437 // for GlobalAddressSDNode since the same GlobalAddress may be represented
17438 // by multiple nodes with different offsets.
17439 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
17440 GV = G->getGlobal();
17441 Offset += G->getOffset();
17445 // Return the underlying Constant value, and update the Offset. Return false
17446 // for ConstantSDNodes since the same constant pool entry may be represented
17447 // by multiple nodes with different offsets.
17448 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
17449 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
17450 : (const void *)C->getConstVal();
17451 Offset += C->getOffset();
17454 // If it's any of the following then it can't alias with anything but itself.
17455 return isa<FrameIndexSDNode>(Base);
17458 /// Return true if there is any possibility that the two addresses overlap.
17459 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17460 // If they are the same then they must be aliases.
17461 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17463 // If they are both volatile then they cannot be reordered.
17464 if (Op0->isVolatile() && Op1->isVolatile()) return true;
17466 // If one operation reads from invariant memory, and the other may store, they
17467 // cannot alias. These should really be checking the equivalent of mayWrite,
17468 // but it only matters for memory nodes other than load /store.
17469 if (Op0->isInvariant() && Op1->writeMem())
17472 if (Op1->isInvariant() && Op0->writeMem())
17475 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17476 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17478 // Check for BaseIndexOffset matching.
17479 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
17480 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
17482 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17483 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17485 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17486 // able to calculate their relative offset if at least one arises
17487 // from an alloca. However, these allocas cannot overlap and we
17488 // can infer there is no alias.
17489 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17490 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17491 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17492 // If the base are the same frame index but the we couldn't find a
17493 // constant offset, (indices are different) be conservative.
17494 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17495 !MFI.isFixedObjectIndex(B->getIndex())))
17499 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
17500 // modified to use BaseIndexOffset.
17502 // Gather base node and offset information.
17503 SDValue Base0, Base1;
17504 int64_t Offset0, Offset1;
17505 const GlobalValue *GV0, *GV1;
17506 const void *CV0, *CV1;
17507 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
17508 Base0, Offset0, GV0, CV0);
17509 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
17510 Base1, Offset1, GV1, CV1);
17512 // If they have the same base address, then check to see if they overlap.
17513 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
17514 return !((Offset0 + NumBytes0) <= Offset1 ||
17515 (Offset1 + NumBytes1) <= Offset0);
17517 // It is possible for different frame indices to alias each other, mostly
17518 // when tail call optimization reuses return address slots for arguments.
17519 // To catch this case, look up the actual index of frame indices to compute
17520 // the real alias relationship.
17521 if (IsFrameIndex0 && IsFrameIndex1) {
17522 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17523 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
17524 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
17525 return !((Offset0 + NumBytes0) <= Offset1 ||
17526 (Offset1 + NumBytes1) <= Offset0);
17529 // Otherwise, if we know what the bases are, and they aren't identical, then
17530 // we know they cannot alias.
17531 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
17534 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
17535 // compared to the size and offset of the access, we may be able to prove they
17536 // do not alias. This check is conservative for now to catch cases created by
17537 // splitting vector types.
17538 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17539 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17540 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17541 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17542 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17543 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17544 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17545 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17547 // There is no overlap between these relatively aligned accesses of similar
17548 // size. Return no alias.
17549 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17550 (OffAlign1 + NumBytes1) <= OffAlign0)
17554 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17556 : DAG.getSubtarget().useAA();
17558 if (CombinerAAOnlyFunc.getNumOccurrences() &&
17559 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17564 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17565 // Use alias analysis information.
17566 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17567 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17568 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17569 AliasResult AAResult =
17570 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17571 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17572 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17573 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17574 if (AAResult == NoAlias)
17578 // Otherwise we have to assume they alias.
17582 /// Walk up chain skipping non-aliasing memory nodes,
17583 /// looking for aliasing nodes and adding them to the Aliases vector.
17584 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17585 SmallVectorImpl<SDValue> &Aliases) {
17586 SmallVector<SDValue, 8> Chains; // List of chains to visit.
17587 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
17589 // Get alias information for node.
17590 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17593 Chains.push_back(OriginalChain);
17594 unsigned Depth = 0;
17596 // Look at each chain and determine if it is an alias. If so, add it to the
17597 // aliases list. If not, then continue up the chain looking for the next
17599 while (!Chains.empty()) {
17600 SDValue Chain = Chains.pop_back_val();
17602 // For TokenFactor nodes, look at each operand and only continue up the
17603 // chain until we reach the depth limit.
17605 // FIXME: The depth check could be made to return the last non-aliasing
17606 // chain we found before we hit a tokenfactor rather than the original
17608 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17610 Aliases.push_back(OriginalChain);
17614 // Don't bother if we've been before.
17615 if (!Visited.insert(Chain.getNode()).second)
17618 switch (Chain.getOpcode()) {
17619 case ISD::EntryToken:
17620 // Entry token is ideal chain operand, but handled in FindBetterChain.
17625 // Get alias information for Chain.
17626 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17627 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17629 // If chain is alias then stop here.
17630 if (!(IsLoad && IsOpLoad) &&
17631 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17632 Aliases.push_back(Chain);
17634 // Look further up the chain.
17635 Chains.push_back(Chain.getOperand(0));
17641 case ISD::TokenFactor:
17642 // We have to check each of the operands of the token factor for "small"
17643 // token factors, so we queue them up. Adding the operands to the queue
17644 // (stack) in reverse order maintains the original order and increases the
17645 // likelihood that getNode will find a matching token factor (CSE.)
17646 if (Chain.getNumOperands() > 16) {
17647 Aliases.push_back(Chain);
17650 for (unsigned n = Chain.getNumOperands(); n;)
17651 Chains.push_back(Chain.getOperand(--n));
17655 case ISD::CopyFromReg:
17656 // Forward past CopyFromReg.
17657 Chains.push_back(Chain.getOperand(0));
17662 // For all other instructions we will just have to take what we can get.
17663 Aliases.push_back(Chain);
17669 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17670 /// (aliasing node.)
17671 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17672 if (OptLevel == CodeGenOpt::None)
17675 // Ops for replacing token factor.
17676 SmallVector<SDValue, 8> Aliases;
17678 // Accumulate all the aliases to this node.
17679 GatherAllAliases(N, OldChain, Aliases);
17681 // If no operands then chain to entry token.
17682 if (Aliases.size() == 0)
17683 return DAG.getEntryNode();
17685 // If a single operand then chain to it. We don't need to revisit it.
17686 if (Aliases.size() == 1)
17689 // Construct a custom tailored token factor.
17690 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17693 // This function tries to collect a bunch of potentially interesting
17694 // nodes to improve the chains of, all at once. This might seem
17695 // redundant, as this function gets called when visiting every store
17696 // node, so why not let the work be done on each store as it's visited?
17698 // I believe this is mainly important because MergeConsecutiveStores
17699 // is unable to deal with merging stores of different sizes, so unless
17700 // we improve the chains of all the potential candidates up-front
17701 // before running MergeConsecutiveStores, it might only see some of
17702 // the nodes that will eventually be candidates, and then not be able
17703 // to go from a partially-merged state to the desired final
17704 // fully-merged state.
17705 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17706 if (OptLevel == CodeGenOpt::None)
17709 // This holds the base pointer, index, and the offset in bytes from the base
17711 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
17713 // We must have a base and an offset.
17714 if (!BasePtr.getBase().getNode())
17717 // Do not handle stores to undef base pointers.
17718 if (BasePtr.getBase().isUndef())
17721 SmallVector<StoreSDNode *, 8> ChainedStores;
17722 ChainedStores.push_back(St);
17724 // Walk up the chain and look for nodes with offsets from the same
17725 // base pointer. Stop when reaching an instruction with a different kind
17726 // or instruction which has a different base pointer.
17727 StoreSDNode *Index = St;
17729 // If the chain has more than one use, then we can't reorder the mem ops.
17730 if (Index != St && !SDValue(Index, 0)->hasOneUse())
17733 if (Index->isVolatile() || Index->isIndexed())
17736 // Find the base pointer and offset for this memory node.
17737 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17739 // Check that the base pointer is the same as the original one.
17740 if (!BasePtr.equalBaseIndex(Ptr, DAG))
17743 // Walk up the chain to find the next store node, ignoring any
17744 // intermediate loads. Any other kind of node will halt the loop.
17745 SDNode *NextInChain = Index->getChain().getNode();
17747 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17748 // We found a store node. Use it for the next iteration.
17749 if (STn->isVolatile() || STn->isIndexed()) {
17753 ChainedStores.push_back(STn);
17756 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17757 NextInChain = Ldn->getChain().getNode();
17766 // At this point, ChainedStores lists all of the Store nodes
17767 // reachable by iterating up through chain nodes matching the above
17768 // conditions. For each such store identified, try to find an
17769 // earlier chain to attach the store to which won't violate the
17770 // required ordering.
17771 bool MadeChangeToSt = false;
17772 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17774 for (StoreSDNode *ChainedStore : ChainedStores) {
17775 SDValue Chain = ChainedStore->getChain();
17776 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17778 if (Chain != BetterChain) {
17779 if (ChainedStore == St)
17780 MadeChangeToSt = true;
17781 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17785 // Do all replacements after finding the replacements to make to avoid making
17786 // the chains more complicated by introducing new TokenFactors.
17787 for (auto Replacement : BetterChains)
17788 replaceStoreChain(Replacement.first, Replacement.second);
17790 return MadeChangeToSt;
17793 /// This is the entry point for the file.
17794 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17795 CodeGenOpt::Level OptLevel) {
17796 /// This is the main entry point to this class.
17797 DAGCombiner(*this, AA, OptLevel).Run(Level);