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/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitIMINMAX(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251 SDValue visitOR(SDNode *N);
252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitXOR(SDNode *N);
254 SDValue SimplifyVBinOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitBSWAP(SDNode *N);
260 SDValue visitCTLZ(SDNode *N);
261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTTZ(SDNode *N);
263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTPOP(SDNode *N);
265 SDValue visitSELECT(SDNode *N);
266 SDValue visitVSELECT(SDNode *N);
267 SDValue visitSELECT_CC(SDNode *N);
268 SDValue visitSETCC(SDNode *N);
269 SDValue visitSIGN_EXTEND(SDNode *N);
270 SDValue visitZERO_EXTEND(SDNode *N);
271 SDValue visitANY_EXTEND(SDNode *N);
272 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274 SDValue visitTRUNCATE(SDNode *N);
275 SDValue visitBITCAST(SDNode *N);
276 SDValue visitBUILD_PAIR(SDNode *N);
277 SDValue visitFADD(SDNode *N);
278 SDValue visitFSUB(SDNode *N);
279 SDValue visitFMUL(SDNode *N);
280 SDValue visitFMA(SDNode *N);
281 SDValue visitFDIV(SDNode *N);
282 SDValue visitFREM(SDNode *N);
283 SDValue visitFSQRT(SDNode *N);
284 SDValue visitFCOPYSIGN(SDNode *N);
285 SDValue visitSINT_TO_FP(SDNode *N);
286 SDValue visitUINT_TO_FP(SDNode *N);
287 SDValue visitFP_TO_SINT(SDNode *N);
288 SDValue visitFP_TO_UINT(SDNode *N);
289 SDValue visitFP_ROUND(SDNode *N);
290 SDValue visitFP_ROUND_INREG(SDNode *N);
291 SDValue visitFP_EXTEND(SDNode *N);
292 SDValue visitFNEG(SDNode *N);
293 SDValue visitFABS(SDNode *N);
294 SDValue visitFCEIL(SDNode *N);
295 SDValue visitFTRUNC(SDNode *N);
296 SDValue visitFFLOOR(SDNode *N);
297 SDValue visitFMINNUM(SDNode *N);
298 SDValue visitFMAXNUM(SDNode *N);
299 SDValue visitBRCOND(SDNode *N);
300 SDValue visitBR_CC(SDNode *N);
301 SDValue visitLOAD(SDNode *N);
302 SDValue visitSTORE(SDNode *N);
303 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
304 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
305 SDValue visitBUILD_VECTOR(SDNode *N);
306 SDValue visitCONCAT_VECTORS(SDNode *N);
307 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
308 SDValue visitVECTOR_SHUFFLE(SDNode *N);
309 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
310 SDValue visitINSERT_SUBVECTOR(SDNode *N);
311 SDValue visitMLOAD(SDNode *N);
312 SDValue visitMSTORE(SDNode *N);
313 SDValue visitMGATHER(SDNode *N);
314 SDValue visitMSCATTER(SDNode *N);
315 SDValue visitFP_TO_FP16(SDNode *N);
317 SDValue visitFADDForFMACombine(SDNode *N);
318 SDValue visitFSUBForFMACombine(SDNode *N);
320 SDValue XformToShuffleWithZero(SDNode *N);
321 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
323 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
325 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
326 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
327 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
328 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
329 SDValue N3, ISD::CondCode CC,
330 bool NotExtCompare = false);
331 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
332 SDLoc DL, bool foldBooleans = true);
334 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
336 bool isOneUseSetCC(SDValue N) const;
338 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
340 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
341 SDValue CombineExtLoad(SDNode *N);
342 SDValue combineRepeatedFPDivisors(SDNode *N);
343 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
344 SDValue BuildSDIV(SDNode *N);
345 SDValue BuildSDIVPow2(SDNode *N);
346 SDValue BuildUDIV(SDNode *N);
347 SDValue BuildReciprocalEstimate(SDValue Op);
348 SDValue BuildRsqrtEstimate(SDValue Op);
349 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
350 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
351 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
352 bool DemandHighBits = true);
353 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
354 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
355 SDValue InnerPos, SDValue InnerNeg,
356 unsigned PosOpcode, unsigned NegOpcode,
358 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
359 SDValue ReduceLoadWidth(SDNode *N);
360 SDValue ReduceLoadOpStoreWidth(SDNode *N);
361 SDValue TransformFPLoadStorePair(SDNode *N);
362 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
363 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
365 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
367 /// Walk up chain skipping non-aliasing memory nodes,
368 /// looking for aliasing nodes and adding them to the Aliases vector.
369 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
370 SmallVectorImpl<SDValue> &Aliases);
372 /// Return true if there is any possibility that the two addresses overlap.
373 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
375 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
376 /// chain (aliasing node.)
377 SDValue FindBetterChain(SDNode *N, SDValue Chain);
379 /// Holds a pointer to an LSBaseSDNode as well as information on where it
380 /// is located in a sequence of memory operations connected by a chain.
382 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
383 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
384 // Ptr to the mem node.
385 LSBaseSDNode *MemNode;
386 // Offset from the base ptr.
387 int64_t OffsetFromBase;
388 // What is the sequence number of this mem node.
389 // Lowest mem operand in the DAG starts at zero.
390 unsigned SequenceNum;
393 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
394 /// constant build_vector of the stored constant values in Stores.
395 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
397 ArrayRef<MemOpLink> Stores,
400 /// This is a helper function for MergeConsecutiveStores. When the source
401 /// elements of the consecutive stores are all constants or all extracted
402 /// vector elements, try to merge them into one larger store.
403 /// \return True if a merged store was created.
404 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
405 EVT MemVT, unsigned NumElem,
406 bool IsConstantSrc, bool UseVector);
408 /// This is a helper function for MergeConsecutiveStores.
409 /// Stores that may be merged are placed in StoreNodes.
410 /// Loads that may alias with those stores are placed in AliasLoadNodes.
411 void getStoreMergeAndAliasCandidates(
412 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
413 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
415 /// Merge consecutive store operations into a wide store.
416 /// This optimization uses wide integers or vectors when possible.
417 /// \return True if some memory operations were changed.
418 bool MergeConsecutiveStores(StoreSDNode *N);
420 /// \brief Try to transform a truncation where C is a constant:
421 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
423 /// \p N needs to be a truncation and its first operand an AND. Other
424 /// requirements are checked by the function (e.g. that trunc is
425 /// single-use) and if missed an empty SDValue is returned.
426 SDValue distributeTruncateThroughAnd(SDNode *N);
429 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
430 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
431 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
432 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
435 /// Runs the dag combiner on all nodes in the work list
436 void Run(CombineLevel AtLevel);
438 SelectionDAG &getDAG() const { return DAG; }
440 /// Returns a type large enough to hold any valid shift amount - before type
441 /// legalization these can be huge.
442 EVT getShiftAmountTy(EVT LHSTy) {
443 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
444 if (LHSTy.isVector())
446 auto &DL = DAG.getDataLayout();
447 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
448 : TLI.getPointerTy(DL);
451 /// This method returns true if we are running before type legalization or
452 /// if the specified VT is legal.
453 bool isTypeLegal(const EVT &VT) {
454 if (!LegalTypes) return true;
455 return TLI.isTypeLegal(VT);
458 /// Convenience wrapper around TargetLowering::getSetCCResultType
459 EVT getSetCCResultType(EVT VT) const {
460 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
467 /// This class is a DAGUpdateListener that removes any deleted
468 /// nodes from the worklist.
469 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
472 explicit WorklistRemover(DAGCombiner &dc)
473 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
475 void NodeDeleted(SDNode *N, SDNode *E) override {
476 DC.removeFromWorklist(N);
481 //===----------------------------------------------------------------------===//
482 // TargetLowering::DAGCombinerInfo implementation
483 //===----------------------------------------------------------------------===//
485 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
486 ((DAGCombiner*)DC)->AddToWorklist(N);
489 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
490 ((DAGCombiner*)DC)->removeFromWorklist(N);
493 SDValue TargetLowering::DAGCombinerInfo::
494 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
495 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
498 SDValue TargetLowering::DAGCombinerInfo::
499 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
500 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
504 SDValue TargetLowering::DAGCombinerInfo::
505 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
506 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
509 void TargetLowering::DAGCombinerInfo::
510 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
511 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
514 //===----------------------------------------------------------------------===//
516 //===----------------------------------------------------------------------===//
518 void DAGCombiner::deleteAndRecombine(SDNode *N) {
519 removeFromWorklist(N);
521 // If the operands of this node are only used by the node, they will now be
522 // dead. Make sure to re-visit them and recursively delete dead nodes.
523 for (const SDValue &Op : N->ops())
524 // For an operand generating multiple values, one of the values may
525 // become dead allowing further simplification (e.g. split index
526 // arithmetic from an indexed load).
527 if (Op->hasOneUse() || Op->getNumValues() > 1)
528 AddToWorklist(Op.getNode());
533 /// Return 1 if we can compute the negated form of the specified expression for
534 /// the same cost as the expression itself, or 2 if we can compute the negated
535 /// form more cheaply than the expression itself.
536 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
537 const TargetLowering &TLI,
538 const TargetOptions *Options,
539 unsigned Depth = 0) {
540 // fneg is removable even if it has multiple uses.
541 if (Op.getOpcode() == ISD::FNEG) return 2;
543 // Don't allow anything with multiple uses.
544 if (!Op.hasOneUse()) return 0;
546 // Don't recurse exponentially.
547 if (Depth > 6) return 0;
549 switch (Op.getOpcode()) {
550 default: return false;
551 case ISD::ConstantFP:
552 // Don't invert constant FP values after legalize. The negated constant
553 // isn't necessarily legal.
554 return LegalOperations ? 0 : 1;
556 // FIXME: determine better conditions for this xform.
557 if (!Options->UnsafeFPMath) return 0;
559 // After operation legalization, it might not be legal to create new FSUBs.
560 if (LegalOperations &&
561 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
569 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
572 // We can't turn -(A-B) into B-A when we honor signed zeros.
573 if (!Options->UnsafeFPMath) return 0;
575 // fold (fneg (fsub A, B)) -> (fsub B, A)
580 if (Options->HonorSignDependentRoundingFPMath()) return 0;
582 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
583 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
587 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
593 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
598 /// If isNegatibleForFree returns true, return the newly negated expression.
599 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
600 bool LegalOperations, unsigned Depth = 0) {
601 const TargetOptions &Options = DAG.getTarget().Options;
602 // fneg is removable even if it has multiple uses.
603 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
605 // Don't allow anything with multiple uses.
606 assert(Op.hasOneUse() && "Unknown reuse!");
608 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
609 switch (Op.getOpcode()) {
610 default: llvm_unreachable("Unknown code");
611 case ISD::ConstantFP: {
612 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
614 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
617 // FIXME: determine better conditions for this xform.
618 assert(Options.UnsafeFPMath);
620 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
621 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
622 DAG.getTargetLoweringInfo(), &Options, Depth+1))
623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624 GetNegatedExpression(Op.getOperand(0), DAG,
625 LegalOperations, Depth+1),
627 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
628 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
629 GetNegatedExpression(Op.getOperand(1), DAG,
630 LegalOperations, Depth+1),
633 // We can't turn -(A-B) into B-A when we honor signed zeros.
634 assert(Options.UnsafeFPMath);
636 // fold (fneg (fsub 0, B)) -> B
637 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
639 return Op.getOperand(1);
641 // fold (fneg (fsub A, B)) -> (fsub B, A)
642 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
643 Op.getOperand(1), Op.getOperand(0));
647 assert(!Options.HonorSignDependentRoundingFPMath());
649 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
650 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
651 DAG.getTargetLoweringInfo(), &Options, Depth+1))
652 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
653 GetNegatedExpression(Op.getOperand(0), DAG,
654 LegalOperations, Depth+1),
657 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
658 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
660 GetNegatedExpression(Op.getOperand(1), DAG,
661 LegalOperations, Depth+1));
665 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
666 GetNegatedExpression(Op.getOperand(0), DAG,
667 LegalOperations, Depth+1));
669 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
670 GetNegatedExpression(Op.getOperand(0), DAG,
671 LegalOperations, Depth+1),
676 // Return true if this node is a setcc, or is a select_cc
677 // that selects between the target values used for true and false, making it
678 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
679 // the appropriate nodes based on the type of node we are checking. This
680 // simplifies life a bit for the callers.
681 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
683 if (N.getOpcode() == ISD::SETCC) {
684 LHS = N.getOperand(0);
685 RHS = N.getOperand(1);
686 CC = N.getOperand(2);
690 if (N.getOpcode() != ISD::SELECT_CC ||
691 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
692 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
695 if (TLI.getBooleanContents(N.getValueType()) ==
696 TargetLowering::UndefinedBooleanContent)
699 LHS = N.getOperand(0);
700 RHS = N.getOperand(1);
701 CC = N.getOperand(4);
705 /// Return true if this is a SetCC-equivalent operation with only one use.
706 /// If this is true, it allows the users to invert the operation for free when
707 /// it is profitable to do so.
708 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
710 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
715 /// Returns true if N is a BUILD_VECTOR node whose
716 /// elements are all the same constant or undefined.
717 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
718 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
723 unsigned SplatBitSize;
725 EVT EltVT = N->getValueType(0).getVectorElementType();
726 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
728 EltVT.getSizeInBits() >= SplatBitSize);
731 // \brief Returns the SDNode if it is a constant integer BuildVector
732 // or constant integer.
733 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
734 if (isa<ConstantSDNode>(N))
736 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
741 // \brief Returns the SDNode if it is a constant float BuildVector
742 // or constant float.
743 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
744 if (isa<ConstantFPSDNode>(N))
746 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
751 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
753 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
754 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
757 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
758 BitVector UndefElements;
759 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
761 // BuildVectors can truncate their operands. Ignore that case here.
762 // FIXME: We blindly ignore splats which include undef which is overly
764 if (CN && UndefElements.none() &&
765 CN->getValueType(0) == N.getValueType().getScalarType())
772 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
774 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
775 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
778 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
779 BitVector UndefElements;
780 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
782 if (CN && UndefElements.none())
789 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
790 SDValue N0, SDValue N1) {
791 EVT VT = N0.getValueType();
792 if (N0.getOpcode() == Opc) {
793 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
795 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
796 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
797 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
800 if (N0.hasOneUse()) {
801 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
803 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
804 if (!OpNode.getNode())
806 AddToWorklist(OpNode.getNode());
807 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
812 if (N1.getOpcode() == Opc) {
813 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
814 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
815 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
816 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
817 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
820 if (N1.hasOneUse()) {
821 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
823 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
824 if (!OpNode.getNode())
826 AddToWorklist(OpNode.getNode());
827 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
835 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
837 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
839 DEBUG(dbgs() << "\nReplacing.1 ";
841 dbgs() << "\nWith: ";
842 To[0].getNode()->dump(&DAG);
843 dbgs() << " and " << NumTo-1 << " other values\n");
844 for (unsigned i = 0, e = NumTo; i != e; ++i)
845 assert((!To[i].getNode() ||
846 N->getValueType(i) == To[i].getValueType()) &&
847 "Cannot combine value to value of different type!");
849 WorklistRemover DeadNodes(*this);
850 DAG.ReplaceAllUsesWith(N, To);
852 // Push the new nodes and any users onto the worklist
853 for (unsigned i = 0, e = NumTo; i != e; ++i) {
854 if (To[i].getNode()) {
855 AddToWorklist(To[i].getNode());
856 AddUsersToWorklist(To[i].getNode());
861 // Finally, if the node is now dead, remove it from the graph. The node
862 // may not be dead if the replacement process recursively simplified to
863 // something else needing this node.
865 deleteAndRecombine(N);
866 return SDValue(N, 0);
870 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
871 // Replace all uses. If any nodes become isomorphic to other nodes and
872 // are deleted, make sure to remove them from our worklist.
873 WorklistRemover DeadNodes(*this);
874 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
876 // Push the new node and any (possibly new) users onto the worklist.
877 AddToWorklist(TLO.New.getNode());
878 AddUsersToWorklist(TLO.New.getNode());
880 // Finally, if the node is now dead, remove it from the graph. The node
881 // may not be dead if the replacement process recursively simplified to
882 // something else needing this node.
883 if (TLO.Old.getNode()->use_empty())
884 deleteAndRecombine(TLO.Old.getNode());
887 /// Check the specified integer node value to see if it can be simplified or if
888 /// things it uses can be simplified by bit propagation. If so, return true.
889 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
890 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
891 APInt KnownZero, KnownOne;
892 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
896 AddToWorklist(Op.getNode());
898 // Replace the old value with the new one.
900 DEBUG(dbgs() << "\nReplacing.2 ";
901 TLO.Old.getNode()->dump(&DAG);
902 dbgs() << "\nWith: ";
903 TLO.New.getNode()->dump(&DAG);
906 CommitTargetLoweringOpt(TLO);
910 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
912 EVT VT = Load->getValueType(0);
913 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
915 DEBUG(dbgs() << "\nReplacing.9 ";
917 dbgs() << "\nWith: ";
918 Trunc.getNode()->dump(&DAG);
920 WorklistRemover DeadNodes(*this);
921 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
922 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
923 deleteAndRecombine(Load);
924 AddToWorklist(Trunc.getNode());
927 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
930 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
931 EVT MemVT = LD->getMemoryVT();
932 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
933 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
935 : LD->getExtensionType();
937 return DAG.getExtLoad(ExtType, dl, PVT,
938 LD->getChain(), LD->getBasePtr(),
939 MemVT, LD->getMemOperand());
942 unsigned Opc = Op.getOpcode();
945 case ISD::AssertSext:
946 return DAG.getNode(ISD::AssertSext, dl, PVT,
947 SExtPromoteOperand(Op.getOperand(0), PVT),
949 case ISD::AssertZext:
950 return DAG.getNode(ISD::AssertZext, dl, PVT,
951 ZExtPromoteOperand(Op.getOperand(0), PVT),
953 case ISD::Constant: {
955 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
956 return DAG.getNode(ExtOpc, dl, PVT, Op);
960 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
962 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
965 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
966 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
968 EVT OldVT = Op.getValueType();
970 bool Replace = false;
971 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
972 if (!NewOp.getNode())
974 AddToWorklist(NewOp.getNode());
977 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
978 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
979 DAG.getValueType(OldVT));
982 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
983 EVT OldVT = Op.getValueType();
985 bool Replace = false;
986 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
987 if (!NewOp.getNode())
989 AddToWorklist(NewOp.getNode());
992 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
993 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
996 /// Promote the specified integer binary operation if the target indicates it is
997 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
998 /// i32 since i16 instructions are longer.
999 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1000 if (!LegalOperations)
1003 EVT VT = Op.getValueType();
1004 if (VT.isVector() || !VT.isInteger())
1007 // If operation type is 'undesirable', e.g. i16 on x86, consider
1009 unsigned Opc = Op.getOpcode();
1010 if (TLI.isTypeDesirableForOp(Opc, VT))
1014 // Consult target whether it is a good idea to promote this operation and
1015 // what's the right type to promote it to.
1016 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1017 assert(PVT != VT && "Don't know what type to promote to!");
1019 bool Replace0 = false;
1020 SDValue N0 = Op.getOperand(0);
1021 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1025 bool Replace1 = false;
1026 SDValue N1 = Op.getOperand(1);
1031 NN1 = PromoteOperand(N1, PVT, Replace1);
1036 AddToWorklist(NN0.getNode());
1038 AddToWorklist(NN1.getNode());
1041 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1043 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1045 DEBUG(dbgs() << "\nPromoting ";
1046 Op.getNode()->dump(&DAG));
1048 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1049 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1054 /// Promote the specified integer shift operation if the target indicates it is
1055 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1056 /// i32 since i16 instructions are longer.
1057 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1058 if (!LegalOperations)
1061 EVT VT = Op.getValueType();
1062 if (VT.isVector() || !VT.isInteger())
1065 // If operation type is 'undesirable', e.g. i16 on x86, consider
1067 unsigned Opc = Op.getOpcode();
1068 if (TLI.isTypeDesirableForOp(Opc, VT))
1072 // Consult target whether it is a good idea to promote this operation and
1073 // what's the right type to promote it to.
1074 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1075 assert(PVT != VT && "Don't know what type to promote to!");
1077 bool Replace = false;
1078 SDValue N0 = Op.getOperand(0);
1079 if (Opc == ISD::SRA)
1080 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1081 else if (Opc == ISD::SRL)
1082 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1084 N0 = PromoteOperand(N0, PVT, Replace);
1088 AddToWorklist(N0.getNode());
1090 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1092 DEBUG(dbgs() << "\nPromoting ";
1093 Op.getNode()->dump(&DAG));
1095 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1096 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1101 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1102 if (!LegalOperations)
1105 EVT VT = Op.getValueType();
1106 if (VT.isVector() || !VT.isInteger())
1109 // If operation type is 'undesirable', e.g. i16 on x86, consider
1111 unsigned Opc = Op.getOpcode();
1112 if (TLI.isTypeDesirableForOp(Opc, VT))
1116 // Consult target whether it is a good idea to promote this operation and
1117 // what's the right type to promote it to.
1118 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1119 assert(PVT != VT && "Don't know what type to promote to!");
1120 // fold (aext (aext x)) -> (aext x)
1121 // fold (aext (zext x)) -> (zext x)
1122 // fold (aext (sext x)) -> (sext x)
1123 DEBUG(dbgs() << "\nPromoting ";
1124 Op.getNode()->dump(&DAG));
1125 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1130 bool DAGCombiner::PromoteLoad(SDValue Op) {
1131 if (!LegalOperations)
1134 EVT VT = Op.getValueType();
1135 if (VT.isVector() || !VT.isInteger())
1138 // If operation type is 'undesirable', e.g. i16 on x86, consider
1140 unsigned Opc = Op.getOpcode();
1141 if (TLI.isTypeDesirableForOp(Opc, VT))
1145 // Consult target whether it is a good idea to promote this operation and
1146 // what's the right type to promote it to.
1147 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1148 assert(PVT != VT && "Don't know what type to promote to!");
1151 SDNode *N = Op.getNode();
1152 LoadSDNode *LD = cast<LoadSDNode>(N);
1153 EVT MemVT = LD->getMemoryVT();
1154 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1155 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1157 : LD->getExtensionType();
1158 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1159 LD->getChain(), LD->getBasePtr(),
1160 MemVT, LD->getMemOperand());
1161 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1163 DEBUG(dbgs() << "\nPromoting ";
1166 Result.getNode()->dump(&DAG);
1168 WorklistRemover DeadNodes(*this);
1169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1171 deleteAndRecombine(N);
1172 AddToWorklist(Result.getNode());
1178 /// \brief Recursively delete a node which has no uses and any operands for
1179 /// which it is the only use.
1181 /// Note that this both deletes the nodes and removes them from the worklist.
1182 /// It also adds any nodes who have had a user deleted to the worklist as they
1183 /// may now have only one use and subject to other combines.
1184 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1185 if (!N->use_empty())
1188 SmallSetVector<SDNode *, 16> Nodes;
1191 N = Nodes.pop_back_val();
1195 if (N->use_empty()) {
1196 for (const SDValue &ChildN : N->op_values())
1197 Nodes.insert(ChildN.getNode());
1199 removeFromWorklist(N);
1204 } while (!Nodes.empty());
1208 //===----------------------------------------------------------------------===//
1209 // Main DAG Combiner implementation
1210 //===----------------------------------------------------------------------===//
1212 void DAGCombiner::Run(CombineLevel AtLevel) {
1213 // set the instance variables, so that the various visit routines may use it.
1215 LegalOperations = Level >= AfterLegalizeVectorOps;
1216 LegalTypes = Level >= AfterLegalizeTypes;
1218 // Add all the dag nodes to the worklist.
1219 for (SDNode &Node : DAG.allnodes())
1220 AddToWorklist(&Node);
1222 // Create a dummy node (which is not added to allnodes), that adds a reference
1223 // to the root node, preventing it from being deleted, and tracking any
1224 // changes of the root.
1225 HandleSDNode Dummy(DAG.getRoot());
1227 // while the worklist isn't empty, find a node and
1228 // try and combine it.
1229 while (!WorklistMap.empty()) {
1231 // The Worklist holds the SDNodes in order, but it may contain null entries.
1233 N = Worklist.pop_back_val();
1236 bool GoodWorklistEntry = WorklistMap.erase(N);
1237 (void)GoodWorklistEntry;
1238 assert(GoodWorklistEntry &&
1239 "Found a worklist entry without a corresponding map entry!");
1241 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1242 // N is deleted from the DAG, since they too may now be dead or may have a
1243 // reduced number of uses, allowing other xforms.
1244 if (recursivelyDeleteUnusedNodes(N))
1247 WorklistRemover DeadNodes(*this);
1249 // If this combine is running after legalizing the DAG, re-legalize any
1250 // nodes pulled off the worklist.
1251 if (Level == AfterLegalizeDAG) {
1252 SmallSetVector<SDNode *, 16> UpdatedNodes;
1253 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255 for (SDNode *LN : UpdatedNodes) {
1257 AddUsersToWorklist(LN);
1263 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265 // Add any operands of the new node which have not yet been combined to the
1266 // worklist as well. Because the worklist uniques things already, this
1267 // won't repeatedly process the same operand.
1268 CombinedNodes.insert(N);
1269 for (const SDValue &ChildN : N->op_values())
1270 if (!CombinedNodes.count(ChildN.getNode()))
1271 AddToWorklist(ChildN.getNode());
1273 SDValue RV = combine(N);
1280 // If we get back the same node we passed in, rather than a new node or
1281 // zero, we know that the node must have defined multiple values and
1282 // CombineTo was used. Since CombineTo takes care of the worklist
1283 // mechanics for us, we have no work to do in this case.
1284 if (RV.getNode() == N)
1287 assert(N->getOpcode() != ISD::DELETED_NODE &&
1288 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1289 "Node was deleted but visit returned new node!");
1291 DEBUG(dbgs() << " ... into: ";
1292 RV.getNode()->dump(&DAG));
1294 // Transfer debug value.
1295 DAG.TransferDbgValues(SDValue(N, 0), RV);
1296 if (N->getNumValues() == RV.getNode()->getNumValues())
1297 DAG.ReplaceAllUsesWith(N, RV.getNode());
1299 assert(N->getValueType(0) == RV.getValueType() &&
1300 N->getNumValues() == 1 && "Type mismatch");
1302 DAG.ReplaceAllUsesWith(N, &OpV);
1305 // Push the new node and any users onto the worklist
1306 AddToWorklist(RV.getNode());
1307 AddUsersToWorklist(RV.getNode());
1309 // Finally, if the node is now dead, remove it from the graph. The node
1310 // may not be dead if the replacement process recursively simplified to
1311 // something else needing this node. This will also take care of adding any
1312 // operands which have lost a user to the worklist.
1313 recursivelyDeleteUnusedNodes(N);
1316 // If the root changed (e.g. it was a dead load, update the root).
1317 DAG.setRoot(Dummy.getValue());
1318 DAG.RemoveDeadNodes();
1321 SDValue DAGCombiner::visit(SDNode *N) {
1322 switch (N->getOpcode()) {
1324 case ISD::TokenFactor: return visitTokenFactor(N);
1325 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1326 case ISD::ADD: return visitADD(N);
1327 case ISD::SUB: return visitSUB(N);
1328 case ISD::ADDC: return visitADDC(N);
1329 case ISD::SUBC: return visitSUBC(N);
1330 case ISD::ADDE: return visitADDE(N);
1331 case ISD::SUBE: return visitSUBE(N);
1332 case ISD::MUL: return visitMUL(N);
1333 case ISD::SDIV: return visitSDIV(N);
1334 case ISD::UDIV: return visitUDIV(N);
1335 case ISD::SREM: return visitSREM(N);
1336 case ISD::UREM: return visitUREM(N);
1337 case ISD::MULHU: return visitMULHU(N);
1338 case ISD::MULHS: return visitMULHS(N);
1339 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1340 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1341 case ISD::SMULO: return visitSMULO(N);
1342 case ISD::UMULO: return visitUMULO(N);
1343 case ISD::SDIVREM: return visitSDIVREM(N);
1344 case ISD::UDIVREM: return visitUDIVREM(N);
1348 case ISD::UMAX: return visitIMINMAX(N);
1349 case ISD::AND: return visitAND(N);
1350 case ISD::OR: return visitOR(N);
1351 case ISD::XOR: return visitXOR(N);
1352 case ISD::SHL: return visitSHL(N);
1353 case ISD::SRA: return visitSRA(N);
1354 case ISD::SRL: return visitSRL(N);
1356 case ISD::ROTL: return visitRotate(N);
1357 case ISD::BSWAP: return visitBSWAP(N);
1358 case ISD::CTLZ: return visitCTLZ(N);
1359 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1360 case ISD::CTTZ: return visitCTTZ(N);
1361 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1362 case ISD::CTPOP: return visitCTPOP(N);
1363 case ISD::SELECT: return visitSELECT(N);
1364 case ISD::VSELECT: return visitVSELECT(N);
1365 case ISD::SELECT_CC: return visitSELECT_CC(N);
1366 case ISD::SETCC: return visitSETCC(N);
1367 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1368 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1369 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1370 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1371 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1372 case ISD::TRUNCATE: return visitTRUNCATE(N);
1373 case ISD::BITCAST: return visitBITCAST(N);
1374 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1375 case ISD::FADD: return visitFADD(N);
1376 case ISD::FSUB: return visitFSUB(N);
1377 case ISD::FMUL: return visitFMUL(N);
1378 case ISD::FMA: return visitFMA(N);
1379 case ISD::FDIV: return visitFDIV(N);
1380 case ISD::FREM: return visitFREM(N);
1381 case ISD::FSQRT: return visitFSQRT(N);
1382 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1383 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1384 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1385 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1386 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1387 case ISD::FP_ROUND: return visitFP_ROUND(N);
1388 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1389 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1390 case ISD::FNEG: return visitFNEG(N);
1391 case ISD::FABS: return visitFABS(N);
1392 case ISD::FFLOOR: return visitFFLOOR(N);
1393 case ISD::FMINNUM: return visitFMINNUM(N);
1394 case ISD::FMAXNUM: return visitFMAXNUM(N);
1395 case ISD::FCEIL: return visitFCEIL(N);
1396 case ISD::FTRUNC: return visitFTRUNC(N);
1397 case ISD::BRCOND: return visitBRCOND(N);
1398 case ISD::BR_CC: return visitBR_CC(N);
1399 case ISD::LOAD: return visitLOAD(N);
1400 case ISD::STORE: return visitSTORE(N);
1401 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1402 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1403 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1404 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1405 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1406 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1407 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1408 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1409 case ISD::MGATHER: return visitMGATHER(N);
1410 case ISD::MLOAD: return visitMLOAD(N);
1411 case ISD::MSCATTER: return visitMSCATTER(N);
1412 case ISD::MSTORE: return visitMSTORE(N);
1413 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1418 SDValue DAGCombiner::combine(SDNode *N) {
1419 SDValue RV = visit(N);
1421 // If nothing happened, try a target-specific DAG combine.
1422 if (!RV.getNode()) {
1423 assert(N->getOpcode() != ISD::DELETED_NODE &&
1424 "Node was deleted but visit returned NULL!");
1426 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1427 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1429 // Expose the DAG combiner to the target combiner impls.
1430 TargetLowering::DAGCombinerInfo
1431 DagCombineInfo(DAG, Level, false, this);
1433 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1437 // If nothing happened still, try promoting the operation.
1438 if (!RV.getNode()) {
1439 switch (N->getOpcode()) {
1447 RV = PromoteIntBinOp(SDValue(N, 0));
1452 RV = PromoteIntShiftOp(SDValue(N, 0));
1454 case ISD::SIGN_EXTEND:
1455 case ISD::ZERO_EXTEND:
1456 case ISD::ANY_EXTEND:
1457 RV = PromoteExtend(SDValue(N, 0));
1460 if (PromoteLoad(SDValue(N, 0)))
1466 // If N is a commutative binary node, try commuting it to enable more
1468 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1469 N->getNumValues() == 1) {
1470 SDValue N0 = N->getOperand(0);
1471 SDValue N1 = N->getOperand(1);
1473 // Constant operands are canonicalized to RHS.
1474 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1475 SDValue Ops[] = {N1, N0};
1477 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1478 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1481 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1484 return SDValue(CSENode, 0);
1491 /// Given a node, return its input chain if it has one, otherwise return a null
1493 static SDValue getInputChainForNode(SDNode *N) {
1494 if (unsigned NumOps = N->getNumOperands()) {
1495 if (N->getOperand(0).getValueType() == MVT::Other)
1496 return N->getOperand(0);
1497 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1498 return N->getOperand(NumOps-1);
1499 for (unsigned i = 1; i < NumOps-1; ++i)
1500 if (N->getOperand(i).getValueType() == MVT::Other)
1501 return N->getOperand(i);
1506 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1507 // If N has two operands, where one has an input chain equal to the other,
1508 // the 'other' chain is redundant.
1509 if (N->getNumOperands() == 2) {
1510 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1511 return N->getOperand(0);
1512 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1513 return N->getOperand(1);
1516 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1517 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1518 SmallPtrSet<SDNode*, 16> SeenOps;
1519 bool Changed = false; // If we should replace this token factor.
1521 // Start out with this token factor.
1524 // Iterate through token factors. The TFs grows when new token factors are
1526 for (unsigned i = 0; i < TFs.size(); ++i) {
1527 SDNode *TF = TFs[i];
1529 // Check each of the operands.
1530 for (const SDValue &Op : TF->op_values()) {
1532 switch (Op.getOpcode()) {
1533 case ISD::EntryToken:
1534 // Entry tokens don't need to be added to the list. They are
1539 case ISD::TokenFactor:
1540 if (Op.hasOneUse() &&
1541 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1542 // Queue up for processing.
1543 TFs.push_back(Op.getNode());
1544 // Clean up in case the token factor is removed.
1545 AddToWorklist(Op.getNode());
1552 // Only add if it isn't already in the list.
1553 if (SeenOps.insert(Op.getNode()).second)
1564 // If we've changed things around then replace token factor.
1567 // The entry token is the only possible outcome.
1568 Result = DAG.getEntryNode();
1570 // New and improved token factor.
1571 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1574 // Add users to worklist if AA is enabled, since it may introduce
1575 // a lot of new chained token factors while removing memory deps.
1576 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1577 : DAG.getSubtarget().useAA();
1578 return CombineTo(N, Result, UseAA /*add to worklist*/);
1584 /// MERGE_VALUES can always be eliminated.
1585 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1586 WorklistRemover DeadNodes(*this);
1587 // Replacing results may cause a different MERGE_VALUES to suddenly
1588 // be CSE'd with N, and carry its uses with it. Iterate until no
1589 // uses remain, to ensure that the node can be safely deleted.
1590 // First add the users of this node to the work list so that they
1591 // can be tried again once they have new operands.
1592 AddUsersToWorklist(N);
1594 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1595 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1596 } while (!N->use_empty());
1597 deleteAndRecombine(N);
1598 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1601 static bool isNullConstant(SDValue V) {
1602 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1603 return Const != nullptr && Const->isNullValue();
1606 static bool isNullFPConstant(SDValue V) {
1607 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1608 return Const != nullptr && Const->isZero() && !Const->isNegative();
1611 static bool isAllOnesConstant(SDValue V) {
1612 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1613 return Const != nullptr && Const->isAllOnesValue();
1616 static bool isOneConstant(SDValue V) {
1617 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1618 return Const != nullptr && Const->isOne();
1621 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1622 /// ContantSDNode pointer else nullptr.
1623 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1624 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1625 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1628 SDValue DAGCombiner::visitADD(SDNode *N) {
1629 SDValue N0 = N->getOperand(0);
1630 SDValue N1 = N->getOperand(1);
1631 EVT VT = N0.getValueType();
1634 if (VT.isVector()) {
1635 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1638 // fold (add x, 0) -> x, vector edition
1639 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1641 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1645 // fold (add x, undef) -> undef
1646 if (N0.getOpcode() == ISD::UNDEF)
1648 if (N1.getOpcode() == ISD::UNDEF)
1650 // fold (add c1, c2) -> c1+c2
1651 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1652 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1654 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1655 // canonicalize constant to RHS
1656 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1657 !isConstantIntBuildVectorOrConstantInt(N1))
1658 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1659 // fold (add x, 0) -> x
1660 if (isNullConstant(N1))
1662 // fold (add Sym, c) -> Sym+c
1663 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1664 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1665 GA->getOpcode() == ISD::GlobalAddress)
1666 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1668 (uint64_t)N1C->getSExtValue());
1669 // fold ((c1-A)+c2) -> (c1+c2)-A
1670 if (N1C && N0.getOpcode() == ISD::SUB)
1671 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1673 return DAG.getNode(ISD::SUB, DL, VT,
1674 DAG.getConstant(N1C->getAPIntValue()+
1675 N0C->getAPIntValue(), DL, VT),
1679 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1681 // fold ((0-A) + B) -> B-A
1682 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1683 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1684 // fold (A + (0-B)) -> A-B
1685 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1686 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1687 // fold (A+(B-A)) -> B
1688 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1689 return N1.getOperand(0);
1690 // fold ((B-A)+A) -> B
1691 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1692 return N0.getOperand(0);
1693 // fold (A+(B-(A+C))) to (B-C)
1694 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1695 N0 == N1.getOperand(1).getOperand(0))
1696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1697 N1.getOperand(1).getOperand(1));
1698 // fold (A+(B-(C+A))) to (B-C)
1699 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1700 N0 == N1.getOperand(1).getOperand(1))
1701 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1702 N1.getOperand(1).getOperand(0));
1703 // fold (A+((B-A)+or-C)) to (B+or-C)
1704 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1705 N1.getOperand(0).getOpcode() == ISD::SUB &&
1706 N0 == N1.getOperand(0).getOperand(1))
1707 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1708 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1710 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1711 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1712 SDValue N00 = N0.getOperand(0);
1713 SDValue N01 = N0.getOperand(1);
1714 SDValue N10 = N1.getOperand(0);
1715 SDValue N11 = N1.getOperand(1);
1717 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1718 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1719 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1720 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1723 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1724 return SDValue(N, 0);
1726 // fold (a+b) -> (a|b) iff a and b share no bits.
1727 if (VT.isInteger() && !VT.isVector()) {
1728 APInt LHSZero, LHSOne;
1729 APInt RHSZero, RHSOne;
1730 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1732 if (LHSZero.getBoolValue()) {
1733 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1735 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1736 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1737 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1738 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1739 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1744 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1745 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1746 isNullConstant(N1.getOperand(0).getOperand(0)))
1747 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1748 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1749 N1.getOperand(0).getOperand(1),
1751 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1752 isNullConstant(N0.getOperand(0).getOperand(0)))
1753 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1754 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1755 N0.getOperand(0).getOperand(1),
1758 if (N1.getOpcode() == ISD::AND) {
1759 SDValue AndOp0 = N1.getOperand(0);
1760 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1761 unsigned DestBits = VT.getScalarType().getSizeInBits();
1763 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1764 // and similar xforms where the inner op is either ~0 or 0.
1765 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1767 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1771 // add (sext i1), X -> sub X, (zext i1)
1772 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1773 N0.getOperand(0).getValueType() == MVT::i1 &&
1774 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1776 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1777 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1780 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1781 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1782 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1783 if (TN->getVT() == MVT::i1) {
1785 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1786 DAG.getConstant(1, DL, VT));
1787 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1794 SDValue DAGCombiner::visitADDC(SDNode *N) {
1795 SDValue N0 = N->getOperand(0);
1796 SDValue N1 = N->getOperand(1);
1797 EVT VT = N0.getValueType();
1799 // If the flag result is dead, turn this into an ADD.
1800 if (!N->hasAnyUseOfValue(1))
1801 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1802 DAG.getNode(ISD::CARRY_FALSE,
1803 SDLoc(N), MVT::Glue));
1805 // canonicalize constant to RHS.
1806 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1807 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1809 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1811 // fold (addc x, 0) -> x + no carry out
1812 if (isNullConstant(N1))
1813 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1814 SDLoc(N), MVT::Glue));
1816 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1817 APInt LHSZero, LHSOne;
1818 APInt RHSZero, RHSOne;
1819 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1821 if (LHSZero.getBoolValue()) {
1822 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1824 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1825 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1826 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1827 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1828 DAG.getNode(ISD::CARRY_FALSE,
1829 SDLoc(N), MVT::Glue));
1835 SDValue DAGCombiner::visitADDE(SDNode *N) {
1836 SDValue N0 = N->getOperand(0);
1837 SDValue N1 = N->getOperand(1);
1838 SDValue CarryIn = N->getOperand(2);
1840 // canonicalize constant to RHS
1841 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1842 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1844 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1847 // fold (adde x, y, false) -> (addc x, y)
1848 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1849 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1854 // Since it may not be valid to emit a fold to zero for vector initializers
1855 // check if we can before folding.
1856 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1858 bool LegalOperations, bool LegalTypes) {
1860 return DAG.getConstant(0, DL, VT);
1861 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1862 return DAG.getConstant(0, DL, VT);
1866 SDValue DAGCombiner::visitSUB(SDNode *N) {
1867 SDValue N0 = N->getOperand(0);
1868 SDValue N1 = N->getOperand(1);
1869 EVT VT = N0.getValueType();
1872 if (VT.isVector()) {
1873 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1876 // fold (sub x, 0) -> x, vector edition
1877 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1881 // fold (sub x, x) -> 0
1882 // FIXME: Refactor this and xor and other similar operations together.
1884 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1885 // fold (sub c1, c2) -> c1-c2
1886 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1887 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1889 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1890 // fold (sub x, c) -> (add x, -c)
1893 return DAG.getNode(ISD::ADD, DL, VT, N0,
1894 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1896 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1897 if (isAllOnesConstant(N0))
1898 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1899 // fold A-(A-B) -> B
1900 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1901 return N1.getOperand(1);
1902 // fold (A+B)-A -> B
1903 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1904 return N0.getOperand(1);
1905 // fold (A+B)-B -> A
1906 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1907 return N0.getOperand(0);
1908 // fold C2-(A+C1) -> (C2-C1)-A
1909 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1910 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1911 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1913 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1915 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1918 // fold ((A+(B+or-C))-B) -> A+or-C
1919 if (N0.getOpcode() == ISD::ADD &&
1920 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1921 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1922 N0.getOperand(1).getOperand(0) == N1)
1923 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1924 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1925 // fold ((A+(C+B))-B) -> A+C
1926 if (N0.getOpcode() == ISD::ADD &&
1927 N0.getOperand(1).getOpcode() == ISD::ADD &&
1928 N0.getOperand(1).getOperand(1) == N1)
1929 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1930 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1931 // fold ((A-(B-C))-C) -> A-B
1932 if (N0.getOpcode() == ISD::SUB &&
1933 N0.getOperand(1).getOpcode() == ISD::SUB &&
1934 N0.getOperand(1).getOperand(1) == N1)
1935 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1936 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1938 // If either operand of a sub is undef, the result is undef
1939 if (N0.getOpcode() == ISD::UNDEF)
1941 if (N1.getOpcode() == ISD::UNDEF)
1944 // If the relocation model supports it, consider symbol offsets.
1945 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1946 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1947 // fold (sub Sym, c) -> Sym-c
1948 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1949 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1951 (uint64_t)N1C->getSExtValue());
1952 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1953 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1954 if (GA->getGlobal() == GB->getGlobal())
1955 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1959 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1960 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1961 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1962 if (TN->getVT() == MVT::i1) {
1964 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1965 DAG.getConstant(1, DL, VT));
1966 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1973 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1974 SDValue N0 = N->getOperand(0);
1975 SDValue N1 = N->getOperand(1);
1976 EVT VT = N0.getValueType();
1978 // If the flag result is dead, turn this into an SUB.
1979 if (!N->hasAnyUseOfValue(1))
1980 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1981 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1984 // fold (subc x, x) -> 0 + no borrow
1987 return CombineTo(N, DAG.getConstant(0, DL, VT),
1988 DAG.getNode(ISD::CARRY_FALSE, DL,
1992 // fold (subc x, 0) -> x + no borrow
1993 if (isNullConstant(N1))
1994 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1997 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1998 if (isAllOnesConstant(N0))
1999 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2000 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2006 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2007 SDValue N0 = N->getOperand(0);
2008 SDValue N1 = N->getOperand(1);
2009 SDValue CarryIn = N->getOperand(2);
2011 // fold (sube x, y, false) -> (subc x, y)
2012 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2013 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2018 SDValue DAGCombiner::visitMUL(SDNode *N) {
2019 SDValue N0 = N->getOperand(0);
2020 SDValue N1 = N->getOperand(1);
2021 EVT VT = N0.getValueType();
2023 // fold (mul x, undef) -> 0
2024 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2025 return DAG.getConstant(0, SDLoc(N), VT);
2027 bool N0IsConst = false;
2028 bool N1IsConst = false;
2029 bool N1IsOpaqueConst = false;
2030 bool N0IsOpaqueConst = false;
2031 APInt ConstValue0, ConstValue1;
2033 if (VT.isVector()) {
2034 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2037 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2038 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2040 N0IsConst = isa<ConstantSDNode>(N0);
2042 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2043 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2045 N1IsConst = isa<ConstantSDNode>(N1);
2047 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2048 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2052 // fold (mul c1, c2) -> c1*c2
2053 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2054 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2055 N0.getNode(), N1.getNode());
2057 // canonicalize constant to RHS (vector doesn't have to splat)
2058 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2059 !isConstantIntBuildVectorOrConstantInt(N1))
2060 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2061 // fold (mul x, 0) -> 0
2062 if (N1IsConst && ConstValue1 == 0)
2064 // We require a splat of the entire scalar bit width for non-contiguous
2067 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2068 // fold (mul x, 1) -> x
2069 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2071 // fold (mul x, -1) -> 0-x
2072 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2074 return DAG.getNode(ISD::SUB, DL, VT,
2075 DAG.getConstant(0, DL, VT), N0);
2077 // fold (mul x, (1 << c)) -> x << c
2078 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2081 return DAG.getNode(ISD::SHL, DL, VT, N0,
2082 DAG.getConstant(ConstValue1.logBase2(), DL,
2083 getShiftAmountTy(N0.getValueType())));
2085 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2086 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2088 unsigned Log2Val = (-ConstValue1).logBase2();
2090 // FIXME: If the input is something that is easily negated (e.g. a
2091 // single-use add), we should put the negate there.
2092 return DAG.getNode(ISD::SUB, DL, VT,
2093 DAG.getConstant(0, DL, VT),
2094 DAG.getNode(ISD::SHL, DL, VT, N0,
2095 DAG.getConstant(Log2Val, DL,
2096 getShiftAmountTy(N0.getValueType()))));
2100 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2101 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2102 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2103 isa<ConstantSDNode>(N0.getOperand(1)))) {
2104 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2105 N1, N0.getOperand(1));
2106 AddToWorklist(C3.getNode());
2107 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2108 N0.getOperand(0), C3);
2111 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2114 SDValue Sh(nullptr,0), Y(nullptr,0);
2115 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2116 if (N0.getOpcode() == ISD::SHL &&
2117 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2118 isa<ConstantSDNode>(N0.getOperand(1))) &&
2119 N0.getNode()->hasOneUse()) {
2121 } else if (N1.getOpcode() == ISD::SHL &&
2122 isa<ConstantSDNode>(N1.getOperand(1)) &&
2123 N1.getNode()->hasOneUse()) {
2128 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2129 Sh.getOperand(0), Y);
2130 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2131 Mul, Sh.getOperand(1));
2135 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2136 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2137 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2138 isa<ConstantSDNode>(N0.getOperand(1))))
2139 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2140 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2141 N0.getOperand(0), N1),
2142 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2143 N0.getOperand(1), N1));
2146 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2152 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2153 SDValue N0 = N->getOperand(0);
2154 SDValue N1 = N->getOperand(1);
2155 EVT VT = N->getValueType(0);
2159 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2162 // fold (sdiv c1, c2) -> c1/c2
2163 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2164 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2165 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2166 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2167 // fold (sdiv X, 1) -> X
2168 if (N1C && N1C->isOne())
2170 // fold (sdiv X, -1) -> 0-X
2171 if (N1C && N1C->isAllOnesValue()) {
2173 return DAG.getNode(ISD::SUB, DL, VT,
2174 DAG.getConstant(0, DL, VT), N0);
2176 // If we know the sign bits of both operands are zero, strength reduce to a
2177 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2178 if (!VT.isVector()) {
2179 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2180 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2184 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
2185 // fold (sdiv X, pow2) -> simple ops after legalize
2186 // FIXME: We check for the exact bit here because the generic lowering gives
2187 // better results in that case. The target-specific lowering should learn how
2188 // to handle exact sdivs efficiently.
2189 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2190 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2191 (N1C->getAPIntValue().isPowerOf2() ||
2192 (-N1C->getAPIntValue()).isPowerOf2())) {
2193 // If integer division is cheap, then don't perform the following fold.
2194 if (TLI.isIntDivCheap(N->getValueType(0), MinSize))
2197 // Target-specific implementation of sdiv x, pow2.
2198 if (SDValue Res = BuildSDIVPow2(N))
2201 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2204 // Splat the sign bit into the register
2206 DAG.getNode(ISD::SRA, DL, VT, N0,
2207 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2208 getShiftAmountTy(N0.getValueType())));
2209 AddToWorklist(SGN.getNode());
2211 // Add (N0 < 0) ? abs2 - 1 : 0;
2213 DAG.getNode(ISD::SRL, DL, VT, SGN,
2214 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2215 getShiftAmountTy(SGN.getValueType())));
2216 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2217 AddToWorklist(SRL.getNode());
2218 AddToWorklist(ADD.getNode()); // Divide by pow2
2219 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2220 DAG.getConstant(lg2, DL,
2221 getShiftAmountTy(ADD.getValueType())));
2223 // If we're dividing by a positive value, we're done. Otherwise, we must
2224 // negate the result.
2225 if (N1C->getAPIntValue().isNonNegative())
2228 AddToWorklist(SRA.getNode());
2229 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2232 // If integer divide is expensive and we satisfy the requirements, emit an
2233 // alternate sequence.
2234 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize))
2235 if (SDValue Op = BuildSDIV(N))
2239 if (N0.getOpcode() == ISD::UNDEF)
2240 return DAG.getConstant(0, SDLoc(N), VT);
2241 // X / undef -> undef
2242 if (N1.getOpcode() == ISD::UNDEF)
2248 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2249 SDValue N0 = N->getOperand(0);
2250 SDValue N1 = N->getOperand(1);
2251 EVT VT = N->getValueType(0);
2255 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2258 // fold (udiv c1, c2) -> c1/c2
2259 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2262 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2265 // fold (udiv x, (1 << c)) -> x >>u c
2266 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2268 return DAG.getNode(ISD::SRL, DL, VT, N0,
2269 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2270 getShiftAmountTy(N0.getValueType())));
2272 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2273 if (N1.getOpcode() == ISD::SHL) {
2274 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2275 if (SHC->getAPIntValue().isPowerOf2()) {
2276 EVT ADDVT = N1.getOperand(1).getValueType();
2278 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2280 DAG.getConstant(SHC->getAPIntValue()
2283 AddToWorklist(Add.getNode());
2284 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2289 // fold (udiv x, c) -> alternate
2290 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
2291 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize))
2292 if (SDValue Op = BuildUDIV(N))
2296 if (N0.getOpcode() == ISD::UNDEF)
2297 return DAG.getConstant(0, SDLoc(N), VT);
2298 // X / undef -> undef
2299 if (N1.getOpcode() == ISD::UNDEF)
2305 SDValue DAGCombiner::visitSREM(SDNode *N) {
2306 SDValue N0 = N->getOperand(0);
2307 SDValue N1 = N->getOperand(1);
2308 EVT VT = N->getValueType(0);
2310 // fold (srem c1, c2) -> c1%c2
2311 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2312 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2314 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2317 // If we know the sign bits of both operands are zero, strength reduce to a
2318 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2319 if (!VT.isVector()) {
2320 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2321 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2324 // If X/C can be simplified by the division-by-constant logic, lower
2325 // X%C to the equivalent of X-X/C*C.
2326 if (N1C && !N1C->isNullValue()) {
2327 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2328 AddToWorklist(Div.getNode());
2329 SDValue OptimizedDiv = combine(Div.getNode());
2330 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2331 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2333 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2334 AddToWorklist(Mul.getNode());
2340 if (N0.getOpcode() == ISD::UNDEF)
2341 return DAG.getConstant(0, SDLoc(N), VT);
2342 // X % undef -> undef
2343 if (N1.getOpcode() == ISD::UNDEF)
2349 SDValue DAGCombiner::visitUREM(SDNode *N) {
2350 SDValue N0 = N->getOperand(0);
2351 SDValue N1 = N->getOperand(1);
2352 EVT VT = N->getValueType(0);
2354 // fold (urem c1, c2) -> c1%c2
2355 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2356 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2358 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2361 // fold (urem x, pow2) -> (and x, pow2-1)
2362 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2363 N1C->getAPIntValue().isPowerOf2()) {
2365 return DAG.getNode(ISD::AND, DL, VT, N0,
2366 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2368 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2369 if (N1.getOpcode() == ISD::SHL) {
2370 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2371 if (SHC->getAPIntValue().isPowerOf2()) {
2374 DAG.getNode(ISD::ADD, DL, VT, N1,
2375 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2377 AddToWorklist(Add.getNode());
2378 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2383 // If X/C can be simplified by the division-by-constant logic, lower
2384 // X%C to the equivalent of X-X/C*C.
2385 if (N1C && !N1C->isNullValue()) {
2386 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2387 AddToWorklist(Div.getNode());
2388 SDValue OptimizedDiv = combine(Div.getNode());
2389 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2390 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2392 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2393 AddToWorklist(Mul.getNode());
2399 if (N0.getOpcode() == ISD::UNDEF)
2400 return DAG.getConstant(0, SDLoc(N), VT);
2401 // X % undef -> undef
2402 if (N1.getOpcode() == ISD::UNDEF)
2408 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2409 SDValue N0 = N->getOperand(0);
2410 SDValue N1 = N->getOperand(1);
2411 EVT VT = N->getValueType(0);
2414 // fold (mulhs x, 0) -> 0
2415 if (isNullConstant(N1))
2417 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2418 if (isOneConstant(N1)) {
2420 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2421 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2423 getShiftAmountTy(N0.getValueType())));
2425 // fold (mulhs x, undef) -> 0
2426 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2427 return DAG.getConstant(0, SDLoc(N), VT);
2429 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2431 if (VT.isSimple() && !VT.isVector()) {
2432 MVT Simple = VT.getSimpleVT();
2433 unsigned SimpleSize = Simple.getSizeInBits();
2434 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2435 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2436 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2437 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2438 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2439 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2440 DAG.getConstant(SimpleSize, DL,
2441 getShiftAmountTy(N1.getValueType())));
2442 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2449 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2450 SDValue N0 = N->getOperand(0);
2451 SDValue N1 = N->getOperand(1);
2452 EVT VT = N->getValueType(0);
2455 // fold (mulhu x, 0) -> 0
2456 if (isNullConstant(N1))
2458 // fold (mulhu x, 1) -> 0
2459 if (isOneConstant(N1))
2460 return DAG.getConstant(0, DL, N0.getValueType());
2461 // fold (mulhu x, undef) -> 0
2462 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2463 return DAG.getConstant(0, DL, VT);
2465 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2467 if (VT.isSimple() && !VT.isVector()) {
2468 MVT Simple = VT.getSimpleVT();
2469 unsigned SimpleSize = Simple.getSizeInBits();
2470 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2471 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2472 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2473 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2474 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2475 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2476 DAG.getConstant(SimpleSize, DL,
2477 getShiftAmountTy(N1.getValueType())));
2478 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2485 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2486 /// give the opcodes for the two computations that are being performed. Return
2487 /// true if a simplification was made.
2488 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2490 // If the high half is not needed, just compute the low half.
2491 bool HiExists = N->hasAnyUseOfValue(1);
2493 (!LegalOperations ||
2494 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2495 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2496 return CombineTo(N, Res, Res);
2499 // If the low half is not needed, just compute the high half.
2500 bool LoExists = N->hasAnyUseOfValue(0);
2502 (!LegalOperations ||
2503 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2504 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2505 return CombineTo(N, Res, Res);
2508 // If both halves are used, return as it is.
2509 if (LoExists && HiExists)
2512 // If the two computed results can be simplified separately, separate them.
2514 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2515 AddToWorklist(Lo.getNode());
2516 SDValue LoOpt = combine(Lo.getNode());
2517 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2518 (!LegalOperations ||
2519 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2520 return CombineTo(N, LoOpt, LoOpt);
2524 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2525 AddToWorklist(Hi.getNode());
2526 SDValue HiOpt = combine(Hi.getNode());
2527 if (HiOpt.getNode() && HiOpt != Hi &&
2528 (!LegalOperations ||
2529 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2530 return CombineTo(N, HiOpt, HiOpt);
2536 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2537 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2540 EVT VT = N->getValueType(0);
2543 // If the type is twice as wide is legal, transform the mulhu to a wider
2544 // multiply plus a shift.
2545 if (VT.isSimple() && !VT.isVector()) {
2546 MVT Simple = VT.getSimpleVT();
2547 unsigned SimpleSize = Simple.getSizeInBits();
2548 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2549 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2550 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2551 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2552 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2553 // Compute the high part as N1.
2554 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2555 DAG.getConstant(SimpleSize, DL,
2556 getShiftAmountTy(Lo.getValueType())));
2557 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2558 // Compute the low part as N0.
2559 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2560 return CombineTo(N, Lo, Hi);
2567 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2568 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2571 EVT VT = N->getValueType(0);
2574 // If the type is twice as wide is legal, transform the mulhu to a wider
2575 // multiply plus a shift.
2576 if (VT.isSimple() && !VT.isVector()) {
2577 MVT Simple = VT.getSimpleVT();
2578 unsigned SimpleSize = Simple.getSizeInBits();
2579 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2580 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2581 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2582 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2583 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2584 // Compute the high part as N1.
2585 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2586 DAG.getConstant(SimpleSize, DL,
2587 getShiftAmountTy(Lo.getValueType())));
2588 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2589 // Compute the low part as N0.
2590 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2591 return CombineTo(N, Lo, Hi);
2598 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2599 // (smulo x, 2) -> (saddo x, x)
2600 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2601 if (C2->getAPIntValue() == 2)
2602 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2603 N->getOperand(0), N->getOperand(0));
2608 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2609 // (umulo x, 2) -> (uaddo x, x)
2610 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2611 if (C2->getAPIntValue() == 2)
2612 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2613 N->getOperand(0), N->getOperand(0));
2618 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2619 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2625 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2626 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2632 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2633 SDValue N0 = N->getOperand(0);
2634 SDValue N1 = N->getOperand(1);
2635 EVT VT = N0.getValueType();
2639 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2642 // fold (add c1, c2) -> c1+c2
2643 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2644 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2646 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2648 // canonicalize constant to RHS
2649 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2650 !isConstantIntBuildVectorOrConstantInt(N1))
2651 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2656 /// If this is a binary operator with two operands of the same opcode, try to
2658 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2659 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2660 EVT VT = N0.getValueType();
2661 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2663 // Bail early if none of these transforms apply.
2664 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2666 // For each of OP in AND/OR/XOR:
2667 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2668 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2669 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2670 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2671 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2673 // do not sink logical op inside of a vector extend, since it may combine
2675 EVT Op0VT = N0.getOperand(0).getValueType();
2676 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2677 N0.getOpcode() == ISD::SIGN_EXTEND ||
2678 N0.getOpcode() == ISD::BSWAP ||
2679 // Avoid infinite looping with PromoteIntBinOp.
2680 (N0.getOpcode() == ISD::ANY_EXTEND &&
2681 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2682 (N0.getOpcode() == ISD::TRUNCATE &&
2683 (!TLI.isZExtFree(VT, Op0VT) ||
2684 !TLI.isTruncateFree(Op0VT, VT)) &&
2685 TLI.isTypeLegal(Op0VT))) &&
2687 Op0VT == N1.getOperand(0).getValueType() &&
2688 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2689 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2690 N0.getOperand(0).getValueType(),
2691 N0.getOperand(0), N1.getOperand(0));
2692 AddToWorklist(ORNode.getNode());
2693 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2696 // For each of OP in SHL/SRL/SRA/AND...
2697 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2698 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2699 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2700 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2701 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2702 N0.getOperand(1) == N1.getOperand(1)) {
2703 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2704 N0.getOperand(0).getValueType(),
2705 N0.getOperand(0), N1.getOperand(0));
2706 AddToWorklist(ORNode.getNode());
2707 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2708 ORNode, N0.getOperand(1));
2711 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2712 // Only perform this optimization after type legalization and before
2713 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2714 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2715 // we don't want to undo this promotion.
2716 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2718 if ((N0.getOpcode() == ISD::BITCAST ||
2719 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2720 Level == AfterLegalizeTypes) {
2721 SDValue In0 = N0.getOperand(0);
2722 SDValue In1 = N1.getOperand(0);
2723 EVT In0Ty = In0.getValueType();
2724 EVT In1Ty = In1.getValueType();
2726 // If both incoming values are integers, and the original types are the
2728 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2729 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2730 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2731 AddToWorklist(Op.getNode());
2736 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2737 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2738 // If both shuffles use the same mask, and both shuffle within a single
2739 // vector, then it is worthwhile to move the swizzle after the operation.
2740 // The type-legalizer generates this pattern when loading illegal
2741 // vector types from memory. In many cases this allows additional shuffle
2743 // There are other cases where moving the shuffle after the xor/and/or
2744 // is profitable even if shuffles don't perform a swizzle.
2745 // If both shuffles use the same mask, and both shuffles have the same first
2746 // or second operand, then it might still be profitable to move the shuffle
2747 // after the xor/and/or operation.
2748 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2749 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2750 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2752 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2753 "Inputs to shuffles are not the same type");
2755 // Check that both shuffles use the same mask. The masks are known to be of
2756 // the same length because the result vector type is the same.
2757 // Check also that shuffles have only one use to avoid introducing extra
2759 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2760 SVN0->getMask().equals(SVN1->getMask())) {
2761 SDValue ShOp = N0->getOperand(1);
2763 // Don't try to fold this node if it requires introducing a
2764 // build vector of all zeros that might be illegal at this stage.
2765 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2767 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2772 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2773 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2774 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2775 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2776 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2777 N0->getOperand(0), N1->getOperand(0));
2778 AddToWorklist(NewNode.getNode());
2779 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2780 &SVN0->getMask()[0]);
2783 // Don't try to fold this node if it requires introducing a
2784 // build vector of all zeros that might be illegal at this stage.
2785 ShOp = N0->getOperand(0);
2786 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2788 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2793 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2794 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2795 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2796 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2797 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2798 N0->getOperand(1), N1->getOperand(1));
2799 AddToWorklist(NewNode.getNode());
2800 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2801 &SVN0->getMask()[0]);
2809 /// This contains all DAGCombine rules which reduce two values combined by
2810 /// an And operation to a single value. This makes them reusable in the context
2811 /// of visitSELECT(). Rules involving constants are not included as
2812 /// visitSELECT() already handles those cases.
2813 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2814 SDNode *LocReference) {
2815 EVT VT = N1.getValueType();
2817 // fold (and x, undef) -> 0
2818 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2819 return DAG.getConstant(0, SDLoc(LocReference), VT);
2820 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2821 SDValue LL, LR, RL, RR, CC0, CC1;
2822 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2823 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2824 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2826 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2827 LL.getValueType().isInteger()) {
2828 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2829 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2830 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2831 LR.getValueType(), LL, RL);
2832 AddToWorklist(ORNode.getNode());
2833 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2835 if (isAllOnesConstant(LR)) {
2836 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2837 if (Op1 == ISD::SETEQ) {
2838 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2839 LR.getValueType(), LL, RL);
2840 AddToWorklist(ANDNode.getNode());
2841 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2843 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2844 if (Op1 == ISD::SETGT) {
2845 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2846 LR.getValueType(), LL, RL);
2847 AddToWorklist(ORNode.getNode());
2848 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2852 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2853 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2854 Op0 == Op1 && LL.getValueType().isInteger() &&
2855 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2856 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2858 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2859 LL, DAG.getConstant(1, DL,
2860 LL.getValueType()));
2861 AddToWorklist(ADDNode.getNode());
2862 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2863 DAG.getConstant(2, DL, LL.getValueType()),
2866 // canonicalize equivalent to ll == rl
2867 if (LL == RR && LR == RL) {
2868 Op1 = ISD::getSetCCSwappedOperands(Op1);
2871 if (LL == RL && LR == RR) {
2872 bool isInteger = LL.getValueType().isInteger();
2873 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2874 if (Result != ISD::SETCC_INVALID &&
2875 (!LegalOperations ||
2876 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2877 TLI.isOperationLegal(ISD::SETCC,
2878 getSetCCResultType(N0.getSimpleValueType())))))
2879 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2884 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2885 VT.getSizeInBits() <= 64) {
2886 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2887 APInt ADDC = ADDI->getAPIntValue();
2888 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2889 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2890 // immediate for an add, but it is legal if its top c2 bits are set,
2891 // transform the ADD so the immediate doesn't need to be materialized
2893 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2894 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2895 SRLI->getZExtValue());
2896 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2898 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2901 DAG.getNode(ISD::ADD, DL, VT,
2902 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2903 CombineTo(N0.getNode(), NewAdd);
2904 // Return N so it doesn't get rechecked!
2905 return SDValue(LocReference, 0);
2916 SDValue DAGCombiner::visitAND(SDNode *N) {
2917 SDValue N0 = N->getOperand(0);
2918 SDValue N1 = N->getOperand(1);
2919 EVT VT = N1.getValueType();
2922 if (VT.isVector()) {
2923 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2926 // fold (and x, 0) -> 0, vector edition
2927 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2928 // do not return N0, because undef node may exist in N0
2929 return DAG.getConstant(
2930 APInt::getNullValue(
2931 N0.getValueType().getScalarType().getSizeInBits()),
2932 SDLoc(N), N0.getValueType());
2933 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2934 // do not return N1, because undef node may exist in N1
2935 return DAG.getConstant(
2936 APInt::getNullValue(
2937 N1.getValueType().getScalarType().getSizeInBits()),
2938 SDLoc(N), N1.getValueType());
2940 // fold (and x, -1) -> x, vector edition
2941 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2943 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2947 // fold (and c1, c2) -> c1&c2
2948 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2949 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2950 if (N0C && N1C && !N1C->isOpaque())
2951 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2952 // canonicalize constant to RHS
2953 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2954 !isConstantIntBuildVectorOrConstantInt(N1))
2955 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2956 // fold (and x, -1) -> x
2957 if (isAllOnesConstant(N1))
2959 // if (and x, c) is known to be zero, return 0
2960 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2961 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2962 APInt::getAllOnesValue(BitWidth)))
2963 return DAG.getConstant(0, SDLoc(N), VT);
2965 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2967 // fold (and (or x, C), D) -> D if (C & D) == D
2968 if (N1C && N0.getOpcode() == ISD::OR)
2969 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2970 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2972 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2973 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2974 SDValue N0Op0 = N0.getOperand(0);
2975 APInt Mask = ~N1C->getAPIntValue();
2976 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2977 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2978 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2979 N0.getValueType(), N0Op0);
2981 // Replace uses of the AND with uses of the Zero extend node.
2984 // We actually want to replace all uses of the any_extend with the
2985 // zero_extend, to avoid duplicating things. This will later cause this
2986 // AND to be folded.
2987 CombineTo(N0.getNode(), Zext);
2988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2991 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2992 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2993 // already be zero by virtue of the width of the base type of the load.
2995 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2997 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2998 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2999 N0.getOpcode() == ISD::LOAD) {
3000 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3001 N0 : N0.getOperand(0) );
3003 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3004 // This can be a pure constant or a vector splat, in which case we treat the
3005 // vector as a scalar and use the splat value.
3006 APInt Constant = APInt::getNullValue(1);
3007 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3008 Constant = C->getAPIntValue();
3009 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3010 APInt SplatValue, SplatUndef;
3011 unsigned SplatBitSize;
3013 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3014 SplatBitSize, HasAnyUndefs);
3016 // Undef bits can contribute to a possible optimisation if set, so
3018 SplatValue |= SplatUndef;
3020 // The splat value may be something like "0x00FFFFFF", which means 0 for
3021 // the first vector value and FF for the rest, repeating. We need a mask
3022 // that will apply equally to all members of the vector, so AND all the
3023 // lanes of the constant together.
3024 EVT VT = Vector->getValueType(0);
3025 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3027 // If the splat value has been compressed to a bitlength lower
3028 // than the size of the vector lane, we need to re-expand it to
3030 if (BitWidth > SplatBitSize)
3031 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3032 SplatBitSize < BitWidth;
3033 SplatBitSize = SplatBitSize * 2)
3034 SplatValue |= SplatValue.shl(SplatBitSize);
3036 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3037 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3038 if (SplatBitSize % BitWidth == 0) {
3039 Constant = APInt::getAllOnesValue(BitWidth);
3040 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3041 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3046 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3047 // actually legal and isn't going to get expanded, else this is a false
3049 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3050 Load->getValueType(0),
3051 Load->getMemoryVT());
3053 // Resize the constant to the same size as the original memory access before
3054 // extension. If it is still the AllOnesValue then this AND is completely
3057 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3060 switch (Load->getExtensionType()) {
3061 default: B = false; break;
3062 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3064 case ISD::NON_EXTLOAD: B = true; break;
3067 if (B && Constant.isAllOnesValue()) {
3068 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3069 // preserve semantics once we get rid of the AND.
3070 SDValue NewLoad(Load, 0);
3071 if (Load->getExtensionType() == ISD::EXTLOAD) {
3072 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3073 Load->getValueType(0), SDLoc(Load),
3074 Load->getChain(), Load->getBasePtr(),
3075 Load->getOffset(), Load->getMemoryVT(),
3076 Load->getMemOperand());
3077 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3078 if (Load->getNumValues() == 3) {
3079 // PRE/POST_INC loads have 3 values.
3080 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3081 NewLoad.getValue(2) };
3082 CombineTo(Load, To, 3, true);
3084 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3088 // Fold the AND away, taking care not to fold to the old load node if we
3090 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3092 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3096 // fold (and (load x), 255) -> (zextload x, i8)
3097 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3098 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3099 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3100 (N0.getOpcode() == ISD::ANY_EXTEND &&
3101 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3102 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3103 LoadSDNode *LN0 = HasAnyExt
3104 ? cast<LoadSDNode>(N0.getOperand(0))
3105 : cast<LoadSDNode>(N0);
3106 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3107 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3108 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3109 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3110 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3111 EVT LoadedVT = LN0->getMemoryVT();
3112 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3114 if (ExtVT == LoadedVT &&
3115 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3119 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3120 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3121 LN0->getMemOperand());
3123 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3124 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3127 // Do not change the width of a volatile load.
3128 // Do not generate loads of non-round integer types since these can
3129 // be expensive (and would be wrong if the type is not byte sized).
3130 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3131 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3133 EVT PtrType = LN0->getOperand(1).getValueType();
3135 unsigned Alignment = LN0->getAlignment();
3136 SDValue NewPtr = LN0->getBasePtr();
3138 // For big endian targets, we need to add an offset to the pointer
3139 // to load the correct bytes. For little endian systems, we merely
3140 // need to read fewer bytes from the same pointer.
3141 if (DAG.getDataLayout().isBigEndian()) {
3142 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3143 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3144 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3146 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3147 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3148 Alignment = MinAlign(Alignment, PtrOff);
3151 AddToWorklist(NewPtr.getNode());
3154 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3155 LN0->getChain(), NewPtr,
3156 LN0->getPointerInfo(),
3157 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3158 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3160 CombineTo(LN0, Load, Load.getValue(1));
3161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3167 if (SDValue Combined = visitANDLike(N0, N1, N))
3170 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3171 if (N0.getOpcode() == N1.getOpcode())
3172 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3175 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3176 // fold (and (sra)) -> (and (srl)) when possible.
3177 if (!VT.isVector() &&
3178 SimplifyDemandedBits(SDValue(N, 0)))
3179 return SDValue(N, 0);
3181 // fold (zext_inreg (extload x)) -> (zextload x)
3182 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3184 EVT MemVT = LN0->getMemoryVT();
3185 // If we zero all the possible extended bits, then we can turn this into
3186 // a zextload if we are running before legalize or the operation is legal.
3187 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3188 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3189 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3190 ((!LegalOperations && !LN0->isVolatile()) ||
3191 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3192 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3193 LN0->getChain(), LN0->getBasePtr(),
3194 MemVT, LN0->getMemOperand());
3196 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3197 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3200 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3201 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3203 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3204 EVT MemVT = LN0->getMemoryVT();
3205 // If we zero all the possible extended bits, then we can turn this into
3206 // a zextload if we are running before legalize or the operation is legal.
3207 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3208 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3209 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3210 ((!LegalOperations && !LN0->isVolatile()) ||
3211 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3212 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3213 LN0->getChain(), LN0->getBasePtr(),
3214 MemVT, LN0->getMemOperand());
3216 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3217 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3220 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3221 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3222 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3223 N0.getOperand(1), false);
3224 if (BSwap.getNode())
3231 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3232 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3233 bool DemandHighBits) {
3234 if (!LegalOperations)
3237 EVT VT = N->getValueType(0);
3238 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3240 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3243 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3244 bool LookPassAnd0 = false;
3245 bool LookPassAnd1 = false;
3246 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3248 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3250 if (N0.getOpcode() == ISD::AND) {
3251 if (!N0.getNode()->hasOneUse())
3253 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3254 if (!N01C || N01C->getZExtValue() != 0xFF00)
3256 N0 = N0.getOperand(0);
3257 LookPassAnd0 = true;
3260 if (N1.getOpcode() == ISD::AND) {
3261 if (!N1.getNode()->hasOneUse())
3263 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3264 if (!N11C || N11C->getZExtValue() != 0xFF)
3266 N1 = N1.getOperand(0);
3267 LookPassAnd1 = true;
3270 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3272 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3274 if (!N0.getNode()->hasOneUse() ||
3275 !N1.getNode()->hasOneUse())
3278 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3279 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3282 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3285 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3286 SDValue N00 = N0->getOperand(0);
3287 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3288 if (!N00.getNode()->hasOneUse())
3290 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3291 if (!N001C || N001C->getZExtValue() != 0xFF)
3293 N00 = N00.getOperand(0);
3294 LookPassAnd0 = true;
3297 SDValue N10 = N1->getOperand(0);
3298 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3299 if (!N10.getNode()->hasOneUse())
3301 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3302 if (!N101C || N101C->getZExtValue() != 0xFF00)
3304 N10 = N10.getOperand(0);
3305 LookPassAnd1 = true;
3311 // Make sure everything beyond the low halfword gets set to zero since the SRL
3312 // 16 will clear the top bits.
3313 unsigned OpSizeInBits = VT.getSizeInBits();
3314 if (DemandHighBits && OpSizeInBits > 16) {
3315 // If the left-shift isn't masked out then the only way this is a bswap is
3316 // if all bits beyond the low 8 are 0. In that case the entire pattern
3317 // reduces to a left shift anyway: leave it for other parts of the combiner.
3321 // However, if the right shift isn't masked out then it might be because
3322 // it's not needed. See if we can spot that too.
3323 if (!LookPassAnd1 &&
3324 !DAG.MaskedValueIsZero(
3325 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3329 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3330 if (OpSizeInBits > 16) {
3332 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3333 DAG.getConstant(OpSizeInBits - 16, DL,
3334 getShiftAmountTy(VT)));
3339 /// Return true if the specified node is an element that makes up a 32-bit
3340 /// packed halfword byteswap.
3341 /// ((x & 0x000000ff) << 8) |
3342 /// ((x & 0x0000ff00) >> 8) |
3343 /// ((x & 0x00ff0000) << 8) |
3344 /// ((x & 0xff000000) >> 8)
3345 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3346 if (!N.getNode()->hasOneUse())
3349 unsigned Opc = N.getOpcode();
3350 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3358 switch (N1C->getZExtValue()) {
3361 case 0xFF: Num = 0; break;
3362 case 0xFF00: Num = 1; break;
3363 case 0xFF0000: Num = 2; break;
3364 case 0xFF000000: Num = 3; break;
3367 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3368 SDValue N0 = N.getOperand(0);
3369 if (Opc == ISD::AND) {
3370 if (Num == 0 || Num == 2) {
3372 // (x >> 8) & 0xff0000
3373 if (N0.getOpcode() != ISD::SRL)
3375 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3376 if (!C || C->getZExtValue() != 8)
3379 // (x << 8) & 0xff00
3380 // (x << 8) & 0xff000000
3381 if (N0.getOpcode() != ISD::SHL)
3383 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3384 if (!C || C->getZExtValue() != 8)
3387 } else if (Opc == ISD::SHL) {
3389 // (x & 0xff0000) << 8
3390 if (Num != 0 && Num != 2)
3392 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3393 if (!C || C->getZExtValue() != 8)
3395 } else { // Opc == ISD::SRL
3396 // (x & 0xff00) >> 8
3397 // (x & 0xff000000) >> 8
3398 if (Num != 1 && Num != 3)
3400 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3401 if (!C || C->getZExtValue() != 8)
3408 Parts[Num] = N0.getOperand(0).getNode();
3412 /// Match a 32-bit packed halfword bswap. That is
3413 /// ((x & 0x000000ff) << 8) |
3414 /// ((x & 0x0000ff00) >> 8) |
3415 /// ((x & 0x00ff0000) << 8) |
3416 /// ((x & 0xff000000) >> 8)
3417 /// => (rotl (bswap x), 16)
3418 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3419 if (!LegalOperations)
3422 EVT VT = N->getValueType(0);
3425 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3429 // (or (or (and), (and)), (or (and), (and)))
3430 // (or (or (or (and), (and)), (and)), (and))
3431 if (N0.getOpcode() != ISD::OR)
3433 SDValue N00 = N0.getOperand(0);
3434 SDValue N01 = N0.getOperand(1);
3435 SDNode *Parts[4] = {};
3437 if (N1.getOpcode() == ISD::OR &&
3438 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3439 // (or (or (and), (and)), (or (and), (and)))
3440 SDValue N000 = N00.getOperand(0);
3441 if (!isBSwapHWordElement(N000, Parts))
3444 SDValue N001 = N00.getOperand(1);
3445 if (!isBSwapHWordElement(N001, Parts))
3447 SDValue N010 = N01.getOperand(0);
3448 if (!isBSwapHWordElement(N010, Parts))
3450 SDValue N011 = N01.getOperand(1);
3451 if (!isBSwapHWordElement(N011, Parts))
3454 // (or (or (or (and), (and)), (and)), (and))
3455 if (!isBSwapHWordElement(N1, Parts))
3457 if (!isBSwapHWordElement(N01, Parts))
3459 if (N00.getOpcode() != ISD::OR)
3461 SDValue N000 = N00.getOperand(0);
3462 if (!isBSwapHWordElement(N000, Parts))
3464 SDValue N001 = N00.getOperand(1);
3465 if (!isBSwapHWordElement(N001, Parts))
3469 // Make sure the parts are all coming from the same node.
3470 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3474 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3475 SDValue(Parts[0], 0));
3477 // Result of the bswap should be rotated by 16. If it's not legal, then
3478 // do (x << 16) | (x >> 16).
3479 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3480 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3481 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3482 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3483 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3484 return DAG.getNode(ISD::OR, DL, VT,
3485 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3486 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3489 /// This contains all DAGCombine rules which reduce two values combined by
3490 /// an Or operation to a single value \see visitANDLike().
3491 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3492 EVT VT = N1.getValueType();
3493 // fold (or x, undef) -> -1
3494 if (!LegalOperations &&
3495 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3496 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3497 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3498 SDLoc(LocReference), VT);
3500 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3501 SDValue LL, LR, RL, RR, CC0, CC1;
3502 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3503 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3504 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3506 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3507 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3508 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3509 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3510 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3511 LR.getValueType(), LL, RL);
3512 AddToWorklist(ORNode.getNode());
3513 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3515 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3516 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3517 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3518 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3519 LR.getValueType(), LL, RL);
3520 AddToWorklist(ANDNode.getNode());
3521 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3524 // canonicalize equivalent to ll == rl
3525 if (LL == RR && LR == RL) {
3526 Op1 = ISD::getSetCCSwappedOperands(Op1);
3529 if (LL == RL && LR == RR) {
3530 bool isInteger = LL.getValueType().isInteger();
3531 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3532 if (Result != ISD::SETCC_INVALID &&
3533 (!LegalOperations ||
3534 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3535 TLI.isOperationLegal(ISD::SETCC,
3536 getSetCCResultType(N0.getValueType())))))
3537 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3542 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3543 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3544 // Don't increase # computations.
3545 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3546 // We can only do this xform if we know that bits from X that are set in C2
3547 // but not in C1 are already zero. Likewise for Y.
3548 if (const ConstantSDNode *N0O1C =
3549 getAsNonOpaqueConstant(N0.getOperand(1))) {
3550 if (const ConstantSDNode *N1O1C =
3551 getAsNonOpaqueConstant(N1.getOperand(1))) {
3552 // We can only do this xform if we know that bits from X that are set in
3553 // C2 but not in C1 are already zero. Likewise for Y.
3554 const APInt &LHSMask = N0O1C->getAPIntValue();
3555 const APInt &RHSMask = N1O1C->getAPIntValue();
3557 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3558 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3559 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3560 N0.getOperand(0), N1.getOperand(0));
3561 SDLoc DL(LocReference);
3562 return DAG.getNode(ISD::AND, DL, VT, X,
3563 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3569 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3570 if (N0.getOpcode() == ISD::AND &&
3571 N1.getOpcode() == ISD::AND &&
3572 N0.getOperand(0) == N1.getOperand(0) &&
3573 // Don't increase # computations.
3574 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3575 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3576 N0.getOperand(1), N1.getOperand(1));
3577 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3583 SDValue DAGCombiner::visitOR(SDNode *N) {
3584 SDValue N0 = N->getOperand(0);
3585 SDValue N1 = N->getOperand(1);
3586 EVT VT = N1.getValueType();
3589 if (VT.isVector()) {
3590 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3593 // fold (or x, 0) -> x, vector edition
3594 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3596 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3599 // fold (or x, -1) -> -1, vector edition
3600 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3601 // do not return N0, because undef node may exist in N0
3602 return DAG.getConstant(
3603 APInt::getAllOnesValue(
3604 N0.getValueType().getScalarType().getSizeInBits()),
3605 SDLoc(N), N0.getValueType());
3606 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3607 // do not return N1, because undef node may exist in N1
3608 return DAG.getConstant(
3609 APInt::getAllOnesValue(
3610 N1.getValueType().getScalarType().getSizeInBits()),
3611 SDLoc(N), N1.getValueType());
3613 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3614 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3615 // Do this only if the resulting shuffle is legal.
3616 if (isa<ShuffleVectorSDNode>(N0) &&
3617 isa<ShuffleVectorSDNode>(N1) &&
3618 // Avoid folding a node with illegal type.
3619 TLI.isTypeLegal(VT) &&
3620 N0->getOperand(1) == N1->getOperand(1) &&
3621 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3622 bool CanFold = true;
3623 unsigned NumElts = VT.getVectorNumElements();
3624 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3625 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3626 // We construct two shuffle masks:
3627 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3628 // and N1 as the second operand.
3629 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3630 // and N0 as the second operand.
3631 // We do this because OR is commutable and therefore there might be
3632 // two ways to fold this node into a shuffle.
3633 SmallVector<int,4> Mask1;
3634 SmallVector<int,4> Mask2;
3636 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3637 int M0 = SV0->getMaskElt(i);
3638 int M1 = SV1->getMaskElt(i);
3640 // Both shuffle indexes are undef. Propagate Undef.
3641 if (M0 < 0 && M1 < 0) {
3642 Mask1.push_back(M0);
3643 Mask2.push_back(M0);
3647 if (M0 < 0 || M1 < 0 ||
3648 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3649 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3654 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3655 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3659 // Fold this sequence only if the resulting shuffle is 'legal'.
3660 if (TLI.isShuffleMaskLegal(Mask1, VT))
3661 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3662 N1->getOperand(0), &Mask1[0]);
3663 if (TLI.isShuffleMaskLegal(Mask2, VT))
3664 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3665 N0->getOperand(0), &Mask2[0]);
3670 // fold (or c1, c2) -> c1|c2
3671 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3673 if (N0C && N1C && !N1C->isOpaque())
3674 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3675 // canonicalize constant to RHS
3676 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3677 !isConstantIntBuildVectorOrConstantInt(N1))
3678 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3679 // fold (or x, 0) -> x
3680 if (isNullConstant(N1))
3682 // fold (or x, -1) -> -1
3683 if (isAllOnesConstant(N1))
3685 // fold (or x, c) -> c iff (x & ~c) == 0
3686 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3689 if (SDValue Combined = visitORLike(N0, N1, N))
3692 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3693 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3695 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3699 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3701 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3702 // iff (c1 & c2) == 0.
3703 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3704 isa<ConstantSDNode>(N0.getOperand(1))) {
3705 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3706 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3707 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3710 ISD::AND, SDLoc(N), VT,
3711 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3715 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3716 if (N0.getOpcode() == N1.getOpcode())
3717 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3720 // See if this is some rotate idiom.
3721 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3722 return SDValue(Rot, 0);
3724 // Simplify the operands using demanded-bits information.
3725 if (!VT.isVector() &&
3726 SimplifyDemandedBits(SDValue(N, 0)))
3727 return SDValue(N, 0);
3732 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3733 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3734 if (Op.getOpcode() == ISD::AND) {
3735 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3736 Mask = Op.getOperand(1);
3737 Op = Op.getOperand(0);
3743 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3751 // Return true if we can prove that, whenever Neg and Pos are both in the
3752 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3753 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3755 // (or (shift1 X, Neg), (shift2 X, Pos))
3757 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3758 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3759 // to consider shift amounts with defined behavior.
3760 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3761 // If OpSize is a power of 2 then:
3763 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3764 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3766 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3767 // for the stronger condition:
3769 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3771 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3772 // we can just replace Neg with Neg' for the rest of the function.
3774 // In other cases we check for the even stronger condition:
3776 // Neg == OpSize - Pos [B]
3778 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3779 // behavior if Pos == 0 (and consequently Neg == OpSize).
3781 // We could actually use [A] whenever OpSize is a power of 2, but the
3782 // only extra cases that it would match are those uninteresting ones
3783 // where Neg and Pos are never in range at the same time. E.g. for
3784 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3785 // as well as (sub 32, Pos), but:
3787 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3789 // always invokes undefined behavior for 32-bit X.
3791 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3792 unsigned MaskLoBits = 0;
3793 if (Neg.getOpcode() == ISD::AND &&
3794 isPowerOf2_64(OpSize) &&
3795 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3796 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3797 Neg = Neg.getOperand(0);
3798 MaskLoBits = Log2_64(OpSize);
3801 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3802 if (Neg.getOpcode() != ISD::SUB)
3804 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3807 SDValue NegOp1 = Neg.getOperand(1);
3809 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3810 // Pos'. The truncation is redundant for the purpose of the equality.
3812 Pos.getOpcode() == ISD::AND &&
3813 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3814 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3815 Pos = Pos.getOperand(0);
3817 // The condition we need is now:
3819 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3821 // If NegOp1 == Pos then we need:
3823 // OpSize & Mask == NegC & Mask
3825 // (because "x & Mask" is a truncation and distributes through subtraction).
3828 Width = NegC->getAPIntValue();
3829 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3830 // Then the condition we want to prove becomes:
3832 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3834 // which, again because "x & Mask" is a truncation, becomes:
3836 // NegC & Mask == (OpSize - PosC) & Mask
3837 // OpSize & Mask == (NegC + PosC) & Mask
3838 else if (Pos.getOpcode() == ISD::ADD &&
3839 Pos.getOperand(0) == NegOp1 &&
3840 Pos.getOperand(1).getOpcode() == ISD::Constant)
3841 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3842 NegC->getAPIntValue());
3846 // Now we just need to check that OpSize & Mask == Width & Mask.
3848 // Opsize & Mask is 0 since Mask is Opsize - 1.
3849 return Width.getLoBits(MaskLoBits) == 0;
3850 return Width == OpSize;
3853 // A subroutine of MatchRotate used once we have found an OR of two opposite
3854 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3855 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3856 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3857 // Neg with outer conversions stripped away.
3858 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3859 SDValue Neg, SDValue InnerPos,
3860 SDValue InnerNeg, unsigned PosOpcode,
3861 unsigned NegOpcode, SDLoc DL) {
3862 // fold (or (shl x, (*ext y)),
3863 // (srl x, (*ext (sub 32, y)))) ->
3864 // (rotl x, y) or (rotr x, (sub 32, y))
3866 // fold (or (shl x, (*ext (sub 32, y))),
3867 // (srl x, (*ext y))) ->
3868 // (rotr x, y) or (rotl x, (sub 32, y))
3869 EVT VT = Shifted.getValueType();
3870 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3871 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3872 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3873 HasPos ? Pos : Neg).getNode();
3879 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3880 // idioms for rotate, and if the target supports rotation instructions, generate
3882 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3883 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3884 EVT VT = LHS.getValueType();
3885 if (!TLI.isTypeLegal(VT)) return nullptr;
3887 // The target must have at least one rotate flavor.
3888 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3889 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3890 if (!HasROTL && !HasROTR) return nullptr;
3892 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3893 SDValue LHSShift; // The shift.
3894 SDValue LHSMask; // AND value if any.
3895 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3896 return nullptr; // Not part of a rotate.
3898 SDValue RHSShift; // The shift.
3899 SDValue RHSMask; // AND value if any.
3900 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3901 return nullptr; // Not part of a rotate.
3903 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3904 return nullptr; // Not shifting the same value.
3906 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3907 return nullptr; // Shifts must disagree.
3909 // Canonicalize shl to left side in a shl/srl pair.
3910 if (RHSShift.getOpcode() == ISD::SHL) {
3911 std::swap(LHS, RHS);
3912 std::swap(LHSShift, RHSShift);
3913 std::swap(LHSMask , RHSMask );
3916 unsigned OpSizeInBits = VT.getSizeInBits();
3917 SDValue LHSShiftArg = LHSShift.getOperand(0);
3918 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3919 SDValue RHSShiftArg = RHSShift.getOperand(0);
3920 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3922 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3923 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3924 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3925 RHSShiftAmt.getOpcode() == ISD::Constant) {
3926 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3927 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3928 if ((LShVal + RShVal) != OpSizeInBits)
3931 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3932 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3934 // If there is an AND of either shifted operand, apply it to the result.
3935 if (LHSMask.getNode() || RHSMask.getNode()) {
3936 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3938 if (LHSMask.getNode()) {
3939 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3940 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3942 if (RHSMask.getNode()) {
3943 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3944 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3947 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3950 return Rot.getNode();
3953 // If there is a mask here, and we have a variable shift, we can't be sure
3954 // that we're masking out the right stuff.
3955 if (LHSMask.getNode() || RHSMask.getNode())
3958 // If the shift amount is sign/zext/any-extended just peel it off.
3959 SDValue LExtOp0 = LHSShiftAmt;
3960 SDValue RExtOp0 = RHSShiftAmt;
3961 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3962 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3963 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3964 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3965 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3966 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3967 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3968 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3969 LExtOp0 = LHSShiftAmt.getOperand(0);
3970 RExtOp0 = RHSShiftAmt.getOperand(0);
3973 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3974 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3978 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3979 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3986 SDValue DAGCombiner::visitXOR(SDNode *N) {
3987 SDValue N0 = N->getOperand(0);
3988 SDValue N1 = N->getOperand(1);
3989 EVT VT = N0.getValueType();
3992 if (VT.isVector()) {
3993 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3996 // fold (xor x, 0) -> x, vector edition
3997 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3999 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4003 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4004 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4005 return DAG.getConstant(0, SDLoc(N), VT);
4006 // fold (xor x, undef) -> undef
4007 if (N0.getOpcode() == ISD::UNDEF)
4009 if (N1.getOpcode() == ISD::UNDEF)
4011 // fold (xor c1, c2) -> c1^c2
4012 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4013 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4015 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4016 // canonicalize constant to RHS
4017 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4018 !isConstantIntBuildVectorOrConstantInt(N1))
4019 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4020 // fold (xor x, 0) -> x
4021 if (isNullConstant(N1))
4024 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4027 // fold !(x cc y) -> (x !cc y)
4028 SDValue LHS, RHS, CC;
4029 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4030 bool isInt = LHS.getValueType().isInteger();
4031 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4034 if (!LegalOperations ||
4035 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4036 switch (N0.getOpcode()) {
4038 llvm_unreachable("Unhandled SetCC Equivalent!");
4040 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4041 case ISD::SELECT_CC:
4042 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4043 N0.getOperand(3), NotCC);
4048 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4049 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4050 N0.getNode()->hasOneUse() &&
4051 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4052 SDValue V = N0.getOperand(0);
4054 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4055 DAG.getConstant(1, DL, V.getValueType()));
4056 AddToWorklist(V.getNode());
4057 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4060 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4061 if (isOneConstant(N1) && VT == MVT::i1 &&
4062 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4063 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4064 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4065 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4066 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4067 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4068 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4069 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4072 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4073 if (isAllOnesConstant(N1) &&
4074 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4075 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4076 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4077 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4078 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4079 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4080 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4081 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4084 // fold (xor (and x, y), y) -> (and (not x), y)
4085 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4086 N0->getOperand(1) == N1) {
4087 SDValue X = N0->getOperand(0);
4088 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4089 AddToWorklist(NotX.getNode());
4090 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4092 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4093 if (N1C && N0.getOpcode() == ISD::XOR) {
4094 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4096 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4097 DAG.getConstant(N1C->getAPIntValue() ^
4098 N00C->getAPIntValue(), DL, VT));
4100 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4102 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4103 DAG.getConstant(N1C->getAPIntValue() ^
4104 N01C->getAPIntValue(), DL, VT));
4107 // fold (xor x, x) -> 0
4109 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4111 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4112 // Here is a concrete example of this equivalence:
4114 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4115 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4119 // i16 ~1 == 0b1111111111111110
4120 // i16 rol(~1, 14) == 0b1011111111111111
4122 // Some additional tips to help conceptualize this transform:
4123 // - Try to see the operation as placing a single zero in a value of all ones.
4124 // - There exists no value for x which would allow the result to contain zero.
4125 // - Values of x larger than the bitwidth are undefined and do not require a
4126 // consistent result.
4127 // - Pushing the zero left requires shifting one bits in from the right.
4128 // A rotate left of ~1 is a nice way of achieving the desired result.
4129 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4130 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4132 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4136 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4137 if (N0.getOpcode() == N1.getOpcode())
4138 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4141 // Simplify the expression using non-local knowledge.
4142 if (!VT.isVector() &&
4143 SimplifyDemandedBits(SDValue(N, 0)))
4144 return SDValue(N, 0);
4149 /// Handle transforms common to the three shifts, when the shift amount is a
4151 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4152 SDNode *LHS = N->getOperand(0).getNode();
4153 if (!LHS->hasOneUse()) return SDValue();
4155 // We want to pull some binops through shifts, so that we have (and (shift))
4156 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4157 // thing happens with address calculations, so it's important to canonicalize
4159 bool HighBitSet = false; // Can we transform this if the high bit is set?
4161 switch (LHS->getOpcode()) {
4162 default: return SDValue();
4165 HighBitSet = false; // We can only transform sra if the high bit is clear.
4168 HighBitSet = true; // We can only transform sra if the high bit is set.
4171 if (N->getOpcode() != ISD::SHL)
4172 return SDValue(); // only shl(add) not sr[al](add).
4173 HighBitSet = false; // We can only transform sra if the high bit is clear.
4177 // We require the RHS of the binop to be a constant and not opaque as well.
4178 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4179 if (!BinOpCst) return SDValue();
4181 // FIXME: disable this unless the input to the binop is a shift by a constant.
4182 // If it is not a shift, it pessimizes some common cases like:
4184 // void foo(int *X, int i) { X[i & 1235] = 1; }
4185 // int bar(int *X, int i) { return X[i & 255]; }
4186 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4187 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4188 BinOpLHSVal->getOpcode() != ISD::SRA &&
4189 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4190 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4193 EVT VT = N->getValueType(0);
4195 // If this is a signed shift right, and the high bit is modified by the
4196 // logical operation, do not perform the transformation. The highBitSet
4197 // boolean indicates the value of the high bit of the constant which would
4198 // cause it to be modified for this operation.
4199 if (N->getOpcode() == ISD::SRA) {
4200 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4201 if (BinOpRHSSignSet != HighBitSet)
4205 if (!TLI.isDesirableToCommuteWithShift(LHS))
4208 // Fold the constants, shifting the binop RHS by the shift amount.
4209 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4211 LHS->getOperand(1), N->getOperand(1));
4212 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4214 // Create the new shift.
4215 SDValue NewShift = DAG.getNode(N->getOpcode(),
4216 SDLoc(LHS->getOperand(0)),
4217 VT, LHS->getOperand(0), N->getOperand(1));
4219 // Create the new binop.
4220 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4223 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4224 assert(N->getOpcode() == ISD::TRUNCATE);
4225 assert(N->getOperand(0).getOpcode() == ISD::AND);
4227 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4228 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4229 SDValue N01 = N->getOperand(0).getOperand(1);
4231 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4232 if (!N01C->isOpaque()) {
4233 EVT TruncVT = N->getValueType(0);
4234 SDValue N00 = N->getOperand(0).getOperand(0);
4235 APInt TruncC = N01C->getAPIntValue();
4236 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4239 return DAG.getNode(ISD::AND, DL, TruncVT,
4240 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4241 DAG.getConstant(TruncC, DL, TruncVT));
4249 SDValue DAGCombiner::visitRotate(SDNode *N) {
4250 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4251 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4252 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4253 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4254 if (NewOp1.getNode())
4255 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4256 N->getOperand(0), NewOp1);
4261 SDValue DAGCombiner::visitSHL(SDNode *N) {
4262 SDValue N0 = N->getOperand(0);
4263 SDValue N1 = N->getOperand(1);
4264 EVT VT = N0.getValueType();
4265 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4269 if (VT.isVector()) {
4270 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4273 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4274 // If setcc produces all-one true value then:
4275 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4276 if (N1CV && N1CV->isConstant()) {
4277 if (N0.getOpcode() == ISD::AND) {
4278 SDValue N00 = N0->getOperand(0);
4279 SDValue N01 = N0->getOperand(1);
4280 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4282 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4283 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4284 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4285 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4287 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4290 N1C = isConstOrConstSplat(N1);
4295 // fold (shl c1, c2) -> c1<<c2
4296 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4297 if (N0C && N1C && !N1C->isOpaque())
4298 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4299 // fold (shl 0, x) -> 0
4300 if (isNullConstant(N0))
4302 // fold (shl x, c >= size(x)) -> undef
4303 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4304 return DAG.getUNDEF(VT);
4305 // fold (shl x, 0) -> x
4306 if (N1C && N1C->isNullValue())
4308 // fold (shl undef, x) -> 0
4309 if (N0.getOpcode() == ISD::UNDEF)
4310 return DAG.getConstant(0, SDLoc(N), VT);
4311 // if (shl x, c) is known to be zero, return 0
4312 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4313 APInt::getAllOnesValue(OpSizeInBits)))
4314 return DAG.getConstant(0, SDLoc(N), VT);
4315 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4316 if (N1.getOpcode() == ISD::TRUNCATE &&
4317 N1.getOperand(0).getOpcode() == ISD::AND) {
4318 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4319 if (NewOp1.getNode())
4320 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4323 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4324 return SDValue(N, 0);
4326 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4327 if (N1C && N0.getOpcode() == ISD::SHL) {
4328 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329 uint64_t c1 = N0C1->getZExtValue();
4330 uint64_t c2 = N1C->getZExtValue();
4332 if (c1 + c2 >= OpSizeInBits)
4333 return DAG.getConstant(0, DL, VT);
4334 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4335 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4339 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4340 // For this to be valid, the second form must not preserve any of the bits
4341 // that are shifted out by the inner shift in the first form. This means
4342 // the outer shift size must be >= the number of bits added by the ext.
4343 // As a corollary, we don't care what kind of ext it is.
4344 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4345 N0.getOpcode() == ISD::ANY_EXTEND ||
4346 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4347 N0.getOperand(0).getOpcode() == ISD::SHL) {
4348 SDValue N0Op0 = N0.getOperand(0);
4349 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4350 uint64_t c1 = N0Op0C1->getZExtValue();
4351 uint64_t c2 = N1C->getZExtValue();
4352 EVT InnerShiftVT = N0Op0.getValueType();
4353 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4354 if (c2 >= OpSizeInBits - InnerShiftSize) {
4356 if (c1 + c2 >= OpSizeInBits)
4357 return DAG.getConstant(0, DL, VT);
4358 return DAG.getNode(ISD::SHL, DL, VT,
4359 DAG.getNode(N0.getOpcode(), DL, VT,
4360 N0Op0->getOperand(0)),
4361 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4366 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4367 // Only fold this if the inner zext has no other uses to avoid increasing
4368 // the total number of instructions.
4369 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4370 N0.getOperand(0).getOpcode() == ISD::SRL) {
4371 SDValue N0Op0 = N0.getOperand(0);
4372 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4373 uint64_t c1 = N0Op0C1->getZExtValue();
4374 if (c1 < VT.getScalarSizeInBits()) {
4375 uint64_t c2 = N1C->getZExtValue();
4377 SDValue NewOp0 = N0.getOperand(0);
4378 EVT CountVT = NewOp0.getOperand(1).getValueType();
4380 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4382 DAG.getConstant(c2, DL, CountVT));
4383 AddToWorklist(NewSHL.getNode());
4384 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4390 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4391 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4392 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4393 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4394 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4395 uint64_t C1 = N0C1->getZExtValue();
4396 uint64_t C2 = N1C->getZExtValue();
4399 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4400 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4401 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4402 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4406 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4407 // (and (srl x, (sub c1, c2), MASK)
4408 // Only fold this if the inner shift has no other uses -- if it does, folding
4409 // this will increase the total number of instructions.
4410 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4411 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4412 uint64_t c1 = N0C1->getZExtValue();
4413 if (c1 < OpSizeInBits) {
4414 uint64_t c2 = N1C->getZExtValue();
4415 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4418 Mask = Mask.shl(c2 - c1);
4420 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4421 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4423 Mask = Mask.lshr(c1 - c2);
4425 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4426 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4429 return DAG.getNode(ISD::AND, DL, VT, Shift,
4430 DAG.getConstant(Mask, DL, VT));
4434 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4435 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4436 unsigned BitSize = VT.getScalarSizeInBits();
4438 SDValue HiBitsMask =
4439 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4440 BitSize - N1C->getZExtValue()),
4442 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4446 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4447 // Variant of version done on multiply, except mul by a power of 2 is turned
4450 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4451 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4452 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4453 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4454 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4455 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4458 if (N1C && !N1C->isOpaque())
4459 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4465 SDValue DAGCombiner::visitSRA(SDNode *N) {
4466 SDValue N0 = N->getOperand(0);
4467 SDValue N1 = N->getOperand(1);
4468 EVT VT = N0.getValueType();
4469 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4472 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4473 if (VT.isVector()) {
4474 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4477 N1C = isConstOrConstSplat(N1);
4480 // fold (sra c1, c2) -> (sra c1, c2)
4481 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4482 if (N0C && N1C && !N1C->isOpaque())
4483 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4484 // fold (sra 0, x) -> 0
4485 if (isNullConstant(N0))
4487 // fold (sra -1, x) -> -1
4488 if (isAllOnesConstant(N0))
4490 // fold (sra x, (setge c, size(x))) -> undef
4491 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4492 return DAG.getUNDEF(VT);
4493 // fold (sra x, 0) -> x
4494 if (N1C && N1C->isNullValue())
4496 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4498 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4499 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4500 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4502 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4503 ExtVT, VT.getVectorNumElements());
4504 if ((!LegalOperations ||
4505 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4506 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4507 N0.getOperand(0), DAG.getValueType(ExtVT));
4510 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4511 if (N1C && N0.getOpcode() == ISD::SRA) {
4512 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4513 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4514 if (Sum >= OpSizeInBits)
4515 Sum = OpSizeInBits - 1;
4517 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4518 DAG.getConstant(Sum, DL, N1.getValueType()));
4522 // fold (sra (shl X, m), (sub result_size, n))
4523 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4524 // result_size - n != m.
4525 // If truncate is free for the target sext(shl) is likely to result in better
4527 if (N0.getOpcode() == ISD::SHL && N1C) {
4528 // Get the two constanst of the shifts, CN0 = m, CN = n.
4529 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4531 LLVMContext &Ctx = *DAG.getContext();
4532 // Determine what the truncate's result bitsize and type would be.
4533 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4536 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4538 // Determine the residual right-shift amount.
4539 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4541 // If the shift is not a no-op (in which case this should be just a sign
4542 // extend already), the truncated to type is legal, sign_extend is legal
4543 // on that type, and the truncate to that type is both legal and free,
4544 // perform the transform.
4545 if ((ShiftAmt > 0) &&
4546 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4547 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4548 TLI.isTruncateFree(VT, TruncVT)) {
4551 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4552 getShiftAmountTy(N0.getOperand(0).getValueType()));
4553 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4554 N0.getOperand(0), Amt);
4555 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4557 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4558 N->getValueType(0), Trunc);
4563 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4564 if (N1.getOpcode() == ISD::TRUNCATE &&
4565 N1.getOperand(0).getOpcode() == ISD::AND) {
4566 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4567 if (NewOp1.getNode())
4568 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4571 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4572 // if c1 is equal to the number of bits the trunc removes
4573 if (N0.getOpcode() == ISD::TRUNCATE &&
4574 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4575 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4576 N0.getOperand(0).hasOneUse() &&
4577 N0.getOperand(0).getOperand(1).hasOneUse() &&
4579 SDValue N0Op0 = N0.getOperand(0);
4580 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4581 unsigned LargeShiftVal = LargeShift->getZExtValue();
4582 EVT LargeVT = N0Op0.getValueType();
4584 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4587 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4588 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4589 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4590 N0Op0.getOperand(0), Amt);
4591 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4596 // Simplify, based on bits shifted out of the LHS.
4597 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4598 return SDValue(N, 0);
4601 // If the sign bit is known to be zero, switch this to a SRL.
4602 if (DAG.SignBitIsZero(N0))
4603 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4605 if (N1C && !N1C->isOpaque())
4606 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4612 SDValue DAGCombiner::visitSRL(SDNode *N) {
4613 SDValue N0 = N->getOperand(0);
4614 SDValue N1 = N->getOperand(1);
4615 EVT VT = N0.getValueType();
4616 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4619 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4620 if (VT.isVector()) {
4621 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4624 N1C = isConstOrConstSplat(N1);
4627 // fold (srl c1, c2) -> c1 >>u c2
4628 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4629 if (N0C && N1C && !N1C->isOpaque())
4630 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4631 // fold (srl 0, x) -> 0
4632 if (isNullConstant(N0))
4634 // fold (srl x, c >= size(x)) -> undef
4635 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4636 return DAG.getUNDEF(VT);
4637 // fold (srl x, 0) -> x
4638 if (N1C && N1C->isNullValue())
4640 // if (srl x, c) is known to be zero, return 0
4641 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4642 APInt::getAllOnesValue(OpSizeInBits)))
4643 return DAG.getConstant(0, SDLoc(N), VT);
4645 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4646 if (N1C && N0.getOpcode() == ISD::SRL) {
4647 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4648 uint64_t c1 = N01C->getZExtValue();
4649 uint64_t c2 = N1C->getZExtValue();
4651 if (c1 + c2 >= OpSizeInBits)
4652 return DAG.getConstant(0, DL, VT);
4653 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4654 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4658 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4659 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4660 N0.getOperand(0).getOpcode() == ISD::SRL &&
4661 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4663 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4664 uint64_t c2 = N1C->getZExtValue();
4665 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4666 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4667 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4668 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4669 if (c1 + OpSizeInBits == InnerShiftSize) {
4671 if (c1 + c2 >= InnerShiftSize)
4672 return DAG.getConstant(0, DL, VT);
4673 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4674 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4675 N0.getOperand(0)->getOperand(0),
4676 DAG.getConstant(c1 + c2, DL,
4681 // fold (srl (shl x, c), c) -> (and x, cst2)
4682 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4683 unsigned BitSize = N0.getScalarValueSizeInBits();
4684 if (BitSize <= 64) {
4685 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4687 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4688 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4692 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4693 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4694 // Shifting in all undef bits?
4695 EVT SmallVT = N0.getOperand(0).getValueType();
4696 unsigned BitSize = SmallVT.getScalarSizeInBits();
4697 if (N1C->getZExtValue() >= BitSize)
4698 return DAG.getUNDEF(VT);
4700 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4701 uint64_t ShiftAmt = N1C->getZExtValue();
4703 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4705 DAG.getConstant(ShiftAmt, DL0,
4706 getShiftAmountTy(SmallVT)));
4707 AddToWorklist(SmallShift.getNode());
4708 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4710 return DAG.getNode(ISD::AND, DL, VT,
4711 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4712 DAG.getConstant(Mask, DL, VT));
4716 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4717 // bit, which is unmodified by sra.
4718 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4719 if (N0.getOpcode() == ISD::SRA)
4720 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4723 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4724 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4725 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4726 APInt KnownZero, KnownOne;
4727 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4729 // If any of the input bits are KnownOne, then the input couldn't be all
4730 // zeros, thus the result of the srl will always be zero.
4731 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4733 // If all of the bits input the to ctlz node are known to be zero, then
4734 // the result of the ctlz is "32" and the result of the shift is one.
4735 APInt UnknownBits = ~KnownZero;
4736 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4738 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4739 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4740 // Okay, we know that only that the single bit specified by UnknownBits
4741 // could be set on input to the CTLZ node. If this bit is set, the SRL
4742 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4743 // to an SRL/XOR pair, which is likely to simplify more.
4744 unsigned ShAmt = UnknownBits.countTrailingZeros();
4745 SDValue Op = N0.getOperand(0);
4749 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4750 DAG.getConstant(ShAmt, DL,
4751 getShiftAmountTy(Op.getValueType())));
4752 AddToWorklist(Op.getNode());
4756 return DAG.getNode(ISD::XOR, DL, VT,
4757 Op, DAG.getConstant(1, DL, VT));
4761 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4762 if (N1.getOpcode() == ISD::TRUNCATE &&
4763 N1.getOperand(0).getOpcode() == ISD::AND) {
4764 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4765 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4768 // fold operands of srl based on knowledge that the low bits are not
4770 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4771 return SDValue(N, 0);
4773 if (N1C && !N1C->isOpaque())
4774 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4777 // Attempt to convert a srl of a load into a narrower zero-extending load.
4778 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4781 // Here is a common situation. We want to optimize:
4784 // %b = and i32 %a, 2
4785 // %c = srl i32 %b, 1
4786 // brcond i32 %c ...
4792 // %c = setcc eq %b, 0
4795 // However when after the source operand of SRL is optimized into AND, the SRL
4796 // itself may not be optimized further. Look for it and add the BRCOND into
4798 if (N->hasOneUse()) {
4799 SDNode *Use = *N->use_begin();
4800 if (Use->getOpcode() == ISD::BRCOND)
4802 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4803 // Also look pass the truncate.
4804 Use = *Use->use_begin();
4805 if (Use->getOpcode() == ISD::BRCOND)
4813 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4814 SDValue N0 = N->getOperand(0);
4815 EVT VT = N->getValueType(0);
4817 // fold (bswap c1) -> c2
4818 if (isConstantIntBuildVectorOrConstantInt(N0))
4819 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4820 // fold (bswap (bswap x)) -> x
4821 if (N0.getOpcode() == ISD::BSWAP)
4822 return N0->getOperand(0);
4826 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4827 SDValue N0 = N->getOperand(0);
4828 EVT VT = N->getValueType(0);
4830 // fold (ctlz c1) -> c2
4831 if (isConstantIntBuildVectorOrConstantInt(N0))
4832 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4836 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4837 SDValue N0 = N->getOperand(0);
4838 EVT VT = N->getValueType(0);
4840 // fold (ctlz_zero_undef c1) -> c2
4841 if (isConstantIntBuildVectorOrConstantInt(N0))
4842 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4846 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4847 SDValue N0 = N->getOperand(0);
4848 EVT VT = N->getValueType(0);
4850 // fold (cttz c1) -> c2
4851 if (isConstantIntBuildVectorOrConstantInt(N0))
4852 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4856 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4857 SDValue N0 = N->getOperand(0);
4858 EVT VT = N->getValueType(0);
4860 // fold (cttz_zero_undef c1) -> c2
4861 if (isConstantIntBuildVectorOrConstantInt(N0))
4862 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4866 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4867 SDValue N0 = N->getOperand(0);
4868 EVT VT = N->getValueType(0);
4870 // fold (ctpop c1) -> c2
4871 if (isConstantIntBuildVectorOrConstantInt(N0))
4872 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4877 /// \brief Generate Min/Max node
4878 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4879 SDValue True, SDValue False,
4880 ISD::CondCode CC, const TargetLowering &TLI,
4881 SelectionDAG &DAG) {
4882 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4892 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4893 if (TLI.isOperationLegal(Opcode, VT))
4894 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4903 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4904 if (TLI.isOperationLegal(Opcode, VT))
4905 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4913 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4914 SDValue N0 = N->getOperand(0);
4915 SDValue N1 = N->getOperand(1);
4916 SDValue N2 = N->getOperand(2);
4917 EVT VT = N->getValueType(0);
4918 EVT VT0 = N0.getValueType();
4920 // fold (select C, X, X) -> X
4923 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4924 // fold (select true, X, Y) -> X
4925 // fold (select false, X, Y) -> Y
4926 return !N0C->isNullValue() ? N1 : N2;
4928 // fold (select C, 1, X) -> (or C, X)
4929 if (VT == MVT::i1 && isOneConstant(N1))
4930 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4931 // fold (select C, 0, 1) -> (xor C, 1)
4932 // We can't do this reliably if integer based booleans have different contents
4933 // to floating point based booleans. This is because we can't tell whether we
4934 // have an integer-based boolean or a floating-point-based boolean unless we
4935 // can find the SETCC that produced it and inspect its operands. This is
4936 // fairly easy if C is the SETCC node, but it can potentially be
4937 // undiscoverable (or not reasonably discoverable). For example, it could be
4938 // in another basic block or it could require searching a complicated
4940 if (VT.isInteger() &&
4941 (VT0 == MVT::i1 || (VT0.isInteger() &&
4942 TLI.getBooleanContents(false, false) ==
4943 TLI.getBooleanContents(false, true) &&
4944 TLI.getBooleanContents(false, false) ==
4945 TargetLowering::ZeroOrOneBooleanContent)) &&
4946 isNullConstant(N1) && isOneConstant(N2)) {
4950 return DAG.getNode(ISD::XOR, DL, VT0,
4951 N0, DAG.getConstant(1, DL, VT0));
4954 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4955 N0, DAG.getConstant(1, DL0, VT0));
4956 AddToWorklist(XORNode.getNode());
4958 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4959 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4961 // fold (select C, 0, X) -> (and (not C), X)
4962 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4963 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4964 AddToWorklist(NOTNode.getNode());
4965 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4967 // fold (select C, X, 1) -> (or (not C), X)
4968 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4969 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4970 AddToWorklist(NOTNode.getNode());
4971 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4973 // fold (select C, X, 0) -> (and C, X)
4974 if (VT == MVT::i1 && isNullConstant(N2))
4975 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4976 // fold (select X, X, Y) -> (or X, Y)
4977 // fold (select X, 1, Y) -> (or X, Y)
4978 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4979 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4980 // fold (select X, Y, X) -> (and X, Y)
4981 // fold (select X, Y, 0) -> (and X, Y)
4982 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4983 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4985 // If we can fold this based on the true/false value, do so.
4986 if (SimplifySelectOps(N, N1, N2))
4987 return SDValue(N, 0); // Don't revisit N.
4989 if (VT0 == MVT::i1) {
4990 // The code in this block deals with the following 2 equivalences:
4991 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4992 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
4993 // The target can specify its prefered form with the
4994 // shouldNormalizeToSelectSequence() callback. However we always transform
4995 // to the right anyway if we find the inner select exists in the DAG anyway
4996 // and we always transform to the left side if we know that we can further
4997 // optimize the combination of the conditions.
4998 bool normalizeToSequence
4999 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5000 // select (and Cond0, Cond1), X, Y
5001 // -> select Cond0, (select Cond1, X, Y), Y
5002 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5003 SDValue Cond0 = N0->getOperand(0);
5004 SDValue Cond1 = N0->getOperand(1);
5005 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5006 N1.getValueType(), Cond1, N1, N2);
5007 if (normalizeToSequence || !InnerSelect.use_empty())
5008 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5011 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5012 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5013 SDValue Cond0 = N0->getOperand(0);
5014 SDValue Cond1 = N0->getOperand(1);
5015 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5016 N1.getValueType(), Cond1, N1, N2);
5017 if (normalizeToSequence || !InnerSelect.use_empty())
5018 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5022 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5023 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5024 SDValue N1_0 = N1->getOperand(0);
5025 SDValue N1_1 = N1->getOperand(1);
5026 SDValue N1_2 = N1->getOperand(2);
5027 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5028 // Create the actual and node if we can generate good code for it.
5029 if (!normalizeToSequence) {
5030 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5032 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5035 // Otherwise see if we can optimize the "and" to a better pattern.
5036 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5037 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5041 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5042 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5043 SDValue N2_0 = N2->getOperand(0);
5044 SDValue N2_1 = N2->getOperand(1);
5045 SDValue N2_2 = N2->getOperand(2);
5046 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5047 // Create the actual or node if we can generate good code for it.
5048 if (!normalizeToSequence) {
5049 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5051 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5054 // Otherwise see if we can optimize to a better pattern.
5055 if (SDValue Combined = visitORLike(N0, N2_0, N))
5056 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5062 // fold selects based on a setcc into other things, such as min/max/abs
5063 if (N0.getOpcode() == ISD::SETCC) {
5064 // select x, y (fcmp lt x, y) -> fminnum x, y
5065 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5067 // This is OK if we don't care about what happens if either operand is a
5071 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5072 // no signed zeros as well as no nans.
5073 const TargetOptions &Options = DAG.getTarget().Options;
5074 if (Options.UnsafeFPMath &&
5075 VT.isFloatingPoint() && N0.hasOneUse() &&
5076 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5077 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5079 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5080 N0.getOperand(1), N1, N2, CC,
5085 if ((!LegalOperations &&
5086 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5087 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5088 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5089 N0.getOperand(0), N0.getOperand(1),
5090 N1, N2, N0.getOperand(2));
5091 return SimplifySelect(SDLoc(N), N0, N1, N2);
5098 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5101 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5103 // Split the inputs.
5104 SDValue Lo, Hi, LL, LH, RL, RH;
5105 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5106 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5108 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5109 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5111 return std::make_pair(Lo, Hi);
5114 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5115 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5116 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5118 SDValue Cond = N->getOperand(0);
5119 SDValue LHS = N->getOperand(1);
5120 SDValue RHS = N->getOperand(2);
5121 EVT VT = N->getValueType(0);
5122 int NumElems = VT.getVectorNumElements();
5123 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5124 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5125 Cond.getOpcode() == ISD::BUILD_VECTOR);
5127 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5128 // binary ones here.
5129 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5132 // We're sure we have an even number of elements due to the
5133 // concat_vectors we have as arguments to vselect.
5134 // Skip BV elements until we find one that's not an UNDEF
5135 // After we find an UNDEF element, keep looping until we get to half the
5136 // length of the BV and see if all the non-undef nodes are the same.
5137 ConstantSDNode *BottomHalf = nullptr;
5138 for (int i = 0; i < NumElems / 2; ++i) {
5139 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5142 if (BottomHalf == nullptr)
5143 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5144 else if (Cond->getOperand(i).getNode() != BottomHalf)
5148 // Do the same for the second half of the BuildVector
5149 ConstantSDNode *TopHalf = nullptr;
5150 for (int i = NumElems / 2; i < NumElems; ++i) {
5151 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5154 if (TopHalf == nullptr)
5155 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5156 else if (Cond->getOperand(i).getNode() != TopHalf)
5160 assert(TopHalf && BottomHalf &&
5161 "One half of the selector was all UNDEFs and the other was all the "
5162 "same value. This should have been addressed before this function.");
5164 ISD::CONCAT_VECTORS, dl, VT,
5165 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5166 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5169 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5171 if (Level >= AfterLegalizeTypes)
5174 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5175 SDValue Mask = MSC->getMask();
5176 SDValue Data = MSC->getValue();
5179 // If the MSCATTER data type requires splitting and the mask is provided by a
5180 // SETCC, then split both nodes and its operands before legalization. This
5181 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5182 // and enables future optimizations (e.g. min/max pattern matching on X86).
5183 if (Mask.getOpcode() != ISD::SETCC)
5186 // Check if any splitting is required.
5187 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5188 TargetLowering::TypeSplitVector)
5190 SDValue MaskLo, MaskHi, Lo, Hi;
5191 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5194 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5196 SDValue Chain = MSC->getChain();
5198 EVT MemoryVT = MSC->getMemoryVT();
5199 unsigned Alignment = MSC->getOriginalAlignment();
5201 EVT LoMemVT, HiMemVT;
5202 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5204 SDValue DataLo, DataHi;
5205 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5207 SDValue BasePtr = MSC->getBasePtr();
5208 SDValue IndexLo, IndexHi;
5209 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5211 MachineMemOperand *MMO = DAG.getMachineFunction().
5212 getMachineMemOperand(MSC->getPointerInfo(),
5213 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5214 Alignment, MSC->getAAInfo(), MSC->getRanges());
5216 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5217 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5220 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5221 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5224 AddToWorklist(Lo.getNode());
5225 AddToWorklist(Hi.getNode());
5227 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5230 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5232 if (Level >= AfterLegalizeTypes)
5235 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5236 SDValue Mask = MST->getMask();
5237 SDValue Data = MST->getValue();
5240 // If the MSTORE data type requires splitting and the mask is provided by a
5241 // SETCC, then split both nodes and its operands before legalization. This
5242 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5243 // and enables future optimizations (e.g. min/max pattern matching on X86).
5244 if (Mask.getOpcode() == ISD::SETCC) {
5246 // Check if any splitting is required.
5247 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5248 TargetLowering::TypeSplitVector)
5251 SDValue MaskLo, MaskHi, Lo, Hi;
5252 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5255 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5257 SDValue Chain = MST->getChain();
5258 SDValue Ptr = MST->getBasePtr();
5260 EVT MemoryVT = MST->getMemoryVT();
5261 unsigned Alignment = MST->getOriginalAlignment();
5263 // if Alignment is equal to the vector size,
5264 // take the half of it for the second part
5265 unsigned SecondHalfAlignment =
5266 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5267 Alignment/2 : Alignment;
5269 EVT LoMemVT, HiMemVT;
5270 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5272 SDValue DataLo, DataHi;
5273 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5275 MachineMemOperand *MMO = DAG.getMachineFunction().
5276 getMachineMemOperand(MST->getPointerInfo(),
5277 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5278 Alignment, MST->getAAInfo(), MST->getRanges());
5280 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5281 MST->isTruncatingStore());
5283 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5284 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5285 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5287 MMO = DAG.getMachineFunction().
5288 getMachineMemOperand(MST->getPointerInfo(),
5289 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5290 SecondHalfAlignment, MST->getAAInfo(),
5293 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5294 MST->isTruncatingStore());
5296 AddToWorklist(Lo.getNode());
5297 AddToWorklist(Hi.getNode());
5299 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5304 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5306 if (Level >= AfterLegalizeTypes)
5309 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5310 SDValue Mask = MGT->getMask();
5313 // If the MGATHER result requires splitting and the mask is provided by a
5314 // SETCC, then split both nodes and its operands before legalization. This
5315 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5316 // and enables future optimizations (e.g. min/max pattern matching on X86).
5318 if (Mask.getOpcode() != ISD::SETCC)
5321 EVT VT = N->getValueType(0);
5323 // Check if any splitting is required.
5324 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5325 TargetLowering::TypeSplitVector)
5328 SDValue MaskLo, MaskHi, Lo, Hi;
5329 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5331 SDValue Src0 = MGT->getValue();
5332 SDValue Src0Lo, Src0Hi;
5333 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5336 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5338 SDValue Chain = MGT->getChain();
5339 EVT MemoryVT = MGT->getMemoryVT();
5340 unsigned Alignment = MGT->getOriginalAlignment();
5342 EVT LoMemVT, HiMemVT;
5343 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5345 SDValue BasePtr = MGT->getBasePtr();
5346 SDValue Index = MGT->getIndex();
5347 SDValue IndexLo, IndexHi;
5348 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5350 MachineMemOperand *MMO = DAG.getMachineFunction().
5351 getMachineMemOperand(MGT->getPointerInfo(),
5352 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5353 Alignment, MGT->getAAInfo(), MGT->getRanges());
5355 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5356 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5359 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5360 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5363 AddToWorklist(Lo.getNode());
5364 AddToWorklist(Hi.getNode());
5366 // Build a factor node to remember that this load is independent of the
5368 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5371 // Legalized the chain result - switch anything that used the old chain to
5373 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5375 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5377 SDValue RetOps[] = { GatherRes, Chain };
5378 return DAG.getMergeValues(RetOps, DL);
5381 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5383 if (Level >= AfterLegalizeTypes)
5386 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5387 SDValue Mask = MLD->getMask();
5390 // If the MLOAD result requires splitting and the mask is provided by a
5391 // SETCC, then split both nodes and its operands before legalization. This
5392 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5393 // and enables future optimizations (e.g. min/max pattern matching on X86).
5395 if (Mask.getOpcode() == ISD::SETCC) {
5396 EVT VT = N->getValueType(0);
5398 // Check if any splitting is required.
5399 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5400 TargetLowering::TypeSplitVector)
5403 SDValue MaskLo, MaskHi, Lo, Hi;
5404 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5406 SDValue Src0 = MLD->getSrc0();
5407 SDValue Src0Lo, Src0Hi;
5408 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5411 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5413 SDValue Chain = MLD->getChain();
5414 SDValue Ptr = MLD->getBasePtr();
5415 EVT MemoryVT = MLD->getMemoryVT();
5416 unsigned Alignment = MLD->getOriginalAlignment();
5418 // if Alignment is equal to the vector size,
5419 // take the half of it for the second part
5420 unsigned SecondHalfAlignment =
5421 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5422 Alignment/2 : Alignment;
5424 EVT LoMemVT, HiMemVT;
5425 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5427 MachineMemOperand *MMO = DAG.getMachineFunction().
5428 getMachineMemOperand(MLD->getPointerInfo(),
5429 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5430 Alignment, MLD->getAAInfo(), MLD->getRanges());
5432 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5435 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5436 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5437 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5439 MMO = DAG.getMachineFunction().
5440 getMachineMemOperand(MLD->getPointerInfo(),
5441 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5442 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5444 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5447 AddToWorklist(Lo.getNode());
5448 AddToWorklist(Hi.getNode());
5450 // Build a factor node to remember that this load is independent of the
5452 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5455 // Legalized the chain result - switch anything that used the old chain to
5457 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5459 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5461 SDValue RetOps[] = { LoadRes, Chain };
5462 return DAG.getMergeValues(RetOps, DL);
5467 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5468 SDValue N0 = N->getOperand(0);
5469 SDValue N1 = N->getOperand(1);
5470 SDValue N2 = N->getOperand(2);
5473 // Canonicalize integer abs.
5474 // vselect (setg[te] X, 0), X, -X ->
5475 // vselect (setgt X, -1), X, -X ->
5476 // vselect (setl[te] X, 0), -X, X ->
5477 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5478 if (N0.getOpcode() == ISD::SETCC) {
5479 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5480 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5482 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5484 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5485 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5486 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5487 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5488 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5489 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5490 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5493 EVT VT = LHS.getValueType();
5494 SDValue Shift = DAG.getNode(
5495 ISD::SRA, DL, VT, LHS,
5496 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5497 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5498 AddToWorklist(Shift.getNode());
5499 AddToWorklist(Add.getNode());
5500 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5504 if (SimplifySelectOps(N, N1, N2))
5505 return SDValue(N, 0); // Don't revisit N.
5507 // If the VSELECT result requires splitting and the mask is provided by a
5508 // SETCC, then split both nodes and its operands before legalization. This
5509 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5510 // and enables future optimizations (e.g. min/max pattern matching on X86).
5511 if (N0.getOpcode() == ISD::SETCC) {
5512 EVT VT = N->getValueType(0);
5514 // Check if any splitting is required.
5515 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5516 TargetLowering::TypeSplitVector)
5519 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5520 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5521 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5522 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5524 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5525 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5527 // Add the new VSELECT nodes to the work list in case they need to be split
5529 AddToWorklist(Lo.getNode());
5530 AddToWorklist(Hi.getNode());
5532 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5535 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5536 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5538 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5539 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5542 // The ConvertSelectToConcatVector function is assuming both the above
5543 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5545 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5546 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5547 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5548 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5555 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5556 SDValue N0 = N->getOperand(0);
5557 SDValue N1 = N->getOperand(1);
5558 SDValue N2 = N->getOperand(2);
5559 SDValue N3 = N->getOperand(3);
5560 SDValue N4 = N->getOperand(4);
5561 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5563 // fold select_cc lhs, rhs, x, x, cc -> x
5567 // Determine if the condition we're dealing with is constant
5568 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5569 N0, N1, CC, SDLoc(N), false);
5570 if (SCC.getNode()) {
5571 AddToWorklist(SCC.getNode());
5573 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5574 if (!SCCC->isNullValue())
5575 return N2; // cond always true -> true val
5577 return N3; // cond always false -> false val
5578 } else if (SCC->getOpcode() == ISD::UNDEF) {
5579 // When the condition is UNDEF, just return the first operand. This is
5580 // coherent the DAG creation, no setcc node is created in this case
5582 } else if (SCC.getOpcode() == ISD::SETCC) {
5583 // Fold to a simpler select_cc
5584 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5585 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5590 // If we can fold this based on the true/false value, do so.
5591 if (SimplifySelectOps(N, N2, N3))
5592 return SDValue(N, 0); // Don't revisit N.
5594 // fold select_cc into other things, such as min/max/abs
5595 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5598 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5599 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5600 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5604 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5605 /// a build_vector of constants.
5606 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5607 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5608 /// Vector extends are not folded if operations are legal; this is to
5609 /// avoid introducing illegal build_vector dag nodes.
5610 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5611 SelectionDAG &DAG, bool LegalTypes,
5612 bool LegalOperations) {
5613 unsigned Opcode = N->getOpcode();
5614 SDValue N0 = N->getOperand(0);
5615 EVT VT = N->getValueType(0);
5617 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5618 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5619 && "Expected EXTEND dag node in input!");
5621 // fold (sext c1) -> c1
5622 // fold (zext c1) -> c1
5623 // fold (aext c1) -> c1
5624 if (isa<ConstantSDNode>(N0))
5625 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5627 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5628 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5629 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5630 EVT SVT = VT.getScalarType();
5631 if (!(VT.isVector() &&
5632 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5633 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5636 // We can fold this node into a build_vector.
5637 unsigned VTBits = SVT.getSizeInBits();
5638 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5639 SmallVector<SDValue, 8> Elts;
5640 unsigned NumElts = VT.getVectorNumElements();
5643 for (unsigned i=0; i != NumElts; ++i) {
5644 SDValue Op = N0->getOperand(i);
5645 if (Op->getOpcode() == ISD::UNDEF) {
5646 Elts.push_back(DAG.getUNDEF(SVT));
5651 // Get the constant value and if needed trunc it to the size of the type.
5652 // Nodes like build_vector might have constants wider than the scalar type.
5653 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5654 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5655 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5657 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5660 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5663 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5664 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5665 // transformation. Returns true if extension are possible and the above
5666 // mentioned transformation is profitable.
5667 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5669 SmallVectorImpl<SDNode *> &ExtendNodes,
5670 const TargetLowering &TLI) {
5671 bool HasCopyToRegUses = false;
5672 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5673 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5674 UE = N0.getNode()->use_end();
5679 if (UI.getUse().getResNo() != N0.getResNo())
5681 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5682 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5683 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5684 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5685 // Sign bits will be lost after a zext.
5688 for (unsigned i = 0; i != 2; ++i) {
5689 SDValue UseOp = User->getOperand(i);
5692 if (!isa<ConstantSDNode>(UseOp))
5697 ExtendNodes.push_back(User);
5700 // If truncates aren't free and there are users we can't
5701 // extend, it isn't worthwhile.
5704 // Remember if this value is live-out.
5705 if (User->getOpcode() == ISD::CopyToReg)
5706 HasCopyToRegUses = true;
5709 if (HasCopyToRegUses) {
5710 bool BothLiveOut = false;
5711 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5713 SDUse &Use = UI.getUse();
5714 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5720 // Both unextended and extended values are live out. There had better be
5721 // a good reason for the transformation.
5722 return ExtendNodes.size();
5727 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5728 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5729 ISD::NodeType ExtType) {
5730 // Extend SetCC uses if necessary.
5731 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5732 SDNode *SetCC = SetCCs[i];
5733 SmallVector<SDValue, 4> Ops;
5735 for (unsigned j = 0; j != 2; ++j) {
5736 SDValue SOp = SetCC->getOperand(j);
5738 Ops.push_back(ExtLoad);
5740 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5743 Ops.push_back(SetCC->getOperand(2));
5744 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5748 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5749 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5750 SDValue N0 = N->getOperand(0);
5751 EVT DstVT = N->getValueType(0);
5752 EVT SrcVT = N0.getValueType();
5754 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5755 N->getOpcode() == ISD::ZERO_EXTEND) &&
5756 "Unexpected node type (not an extend)!");
5758 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5759 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5760 // (v8i32 (sext (v8i16 (load x))))
5762 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5763 // (v4i32 (sextload (x + 16)))))
5764 // Where uses of the original load, i.e.:
5766 // are replaced with:
5768 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5769 // (v4i32 (sextload (x + 16)))))))
5771 // This combine is only applicable to illegal, but splittable, vectors.
5772 // All legal types, and illegal non-vector types, are handled elsewhere.
5773 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5775 if (N0->getOpcode() != ISD::LOAD)
5778 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5780 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5781 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5782 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5785 SmallVector<SDNode *, 4> SetCCs;
5786 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5789 ISD::LoadExtType ExtType =
5790 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5792 // Try to split the vector types to get down to legal types.
5793 EVT SplitSrcVT = SrcVT;
5794 EVT SplitDstVT = DstVT;
5795 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5796 SplitSrcVT.getVectorNumElements() > 1) {
5797 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5798 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5801 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5805 const unsigned NumSplits =
5806 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5807 const unsigned Stride = SplitSrcVT.getStoreSize();
5808 SmallVector<SDValue, 4> Loads;
5809 SmallVector<SDValue, 4> Chains;
5811 SDValue BasePtr = LN0->getBasePtr();
5812 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5813 const unsigned Offset = Idx * Stride;
5814 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5816 SDValue SplitLoad = DAG.getExtLoad(
5817 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5818 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5819 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5820 Align, LN0->getAAInfo());
5822 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5823 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5825 Loads.push_back(SplitLoad.getValue(0));
5826 Chains.push_back(SplitLoad.getValue(1));
5829 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5830 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5832 CombineTo(N, NewValue);
5834 // Replace uses of the original load (before extension)
5835 // with a truncate of the concatenated sextloaded vectors.
5837 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5838 CombineTo(N0.getNode(), Trunc, NewChain);
5839 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5840 (ISD::NodeType)N->getOpcode());
5841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5844 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5845 SDValue N0 = N->getOperand(0);
5846 EVT VT = N->getValueType(0);
5848 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5850 return SDValue(Res, 0);
5852 // fold (sext (sext x)) -> (sext x)
5853 // fold (sext (aext x)) -> (sext x)
5854 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5855 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5858 if (N0.getOpcode() == ISD::TRUNCATE) {
5859 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5860 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5861 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5862 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5863 if (NarrowLoad.getNode() != N0.getNode()) {
5864 CombineTo(N0.getNode(), NarrowLoad);
5865 // CombineTo deleted the truncate, if needed, but not what's under it.
5868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5871 // See if the value being truncated is already sign extended. If so, just
5872 // eliminate the trunc/sext pair.
5873 SDValue Op = N0.getOperand(0);
5874 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5875 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5876 unsigned DestBits = VT.getScalarType().getSizeInBits();
5877 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5879 if (OpBits == DestBits) {
5880 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5881 // bits, it is already ready.
5882 if (NumSignBits > DestBits-MidBits)
5884 } else if (OpBits < DestBits) {
5885 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5886 // bits, just sext from i32.
5887 if (NumSignBits > OpBits-MidBits)
5888 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5890 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5891 // bits, just truncate to i32.
5892 if (NumSignBits > OpBits-MidBits)
5893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5896 // fold (sext (truncate x)) -> (sextinreg x).
5897 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5898 N0.getValueType())) {
5899 if (OpBits < DestBits)
5900 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5901 else if (OpBits > DestBits)
5902 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5903 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5904 DAG.getValueType(N0.getValueType()));
5908 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5909 // Only generate vector extloads when 1) they're legal, and 2) they are
5910 // deemed desirable by the target.
5911 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5912 ((!LegalOperations && !VT.isVector() &&
5913 !cast<LoadSDNode>(N0)->isVolatile()) ||
5914 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5915 bool DoXform = true;
5916 SmallVector<SDNode*, 4> SetCCs;
5917 if (!N0.hasOneUse())
5918 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5920 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5922 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5923 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5925 LN0->getBasePtr(), N0.getValueType(),
5926 LN0->getMemOperand());
5927 CombineTo(N, ExtLoad);
5928 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5929 N0.getValueType(), ExtLoad);
5930 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5931 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5937 // fold (sext (load x)) to multiple smaller sextloads.
5938 // Only on illegal but splittable vectors.
5939 if (SDValue ExtLoad = CombineExtLoad(N))
5942 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5943 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5944 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5945 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5947 EVT MemVT = LN0->getMemoryVT();
5948 if ((!LegalOperations && !LN0->isVolatile()) ||
5949 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5950 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5952 LN0->getBasePtr(), MemVT,
5953 LN0->getMemOperand());
5954 CombineTo(N, ExtLoad);
5955 CombineTo(N0.getNode(),
5956 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5957 N0.getValueType(), ExtLoad),
5958 ExtLoad.getValue(1));
5959 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5963 // fold (sext (and/or/xor (load x), cst)) ->
5964 // (and/or/xor (sextload x), (sext cst))
5965 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5966 N0.getOpcode() == ISD::XOR) &&
5967 isa<LoadSDNode>(N0.getOperand(0)) &&
5968 N0.getOperand(1).getOpcode() == ISD::Constant &&
5969 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5970 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5971 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5972 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5973 bool DoXform = true;
5974 SmallVector<SDNode*, 4> SetCCs;
5975 if (!N0.hasOneUse())
5976 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5979 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5980 LN0->getChain(), LN0->getBasePtr(),
5982 LN0->getMemOperand());
5983 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5984 Mask = Mask.sext(VT.getSizeInBits());
5986 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5987 ExtLoad, DAG.getConstant(Mask, DL, VT));
5988 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5989 SDLoc(N0.getOperand(0)),
5990 N0.getOperand(0).getValueType(), ExtLoad);
5992 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5993 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6000 if (N0.getOpcode() == ISD::SETCC) {
6001 EVT N0VT = N0.getOperand(0).getValueType();
6002 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6003 // Only do this before legalize for now.
6004 if (VT.isVector() && !LegalOperations &&
6005 TLI.getBooleanContents(N0VT) ==
6006 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6007 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6008 // of the same size as the compared operands. Only optimize sext(setcc())
6009 // if this is the case.
6010 EVT SVT = getSetCCResultType(N0VT);
6012 // We know that the # elements of the results is the same as the
6013 // # elements of the compare (and the # elements of the compare result
6014 // for that matter). Check to see that they are the same size. If so,
6015 // we know that the element size of the sext'd result matches the
6016 // element size of the compare operands.
6017 if (VT.getSizeInBits() == SVT.getSizeInBits())
6018 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6020 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6022 // If the desired elements are smaller or larger than the source
6023 // elements we can use a matching integer vector type and then
6024 // truncate/sign extend
6025 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6026 if (SVT == MatchingVectorType) {
6027 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6028 N0.getOperand(0), N0.getOperand(1),
6029 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6030 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6034 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6035 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6038 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6040 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6041 NegOne, DAG.getConstant(0, DL, VT),
6042 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6043 if (SCC.getNode()) return SCC;
6045 if (!VT.isVector()) {
6046 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6047 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6049 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6050 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6051 N0.getOperand(0), N0.getOperand(1), CC);
6052 return DAG.getSelect(DL, VT, SetCC,
6053 NegOne, DAG.getConstant(0, DL, VT));
6058 // fold (sext x) -> (zext x) if the sign bit is known zero.
6059 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6060 DAG.SignBitIsZero(N0))
6061 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6066 // isTruncateOf - If N is a truncate of some other value, return true, record
6067 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6068 // This function computes KnownZero to avoid a duplicated call to
6069 // computeKnownBits in the caller.
6070 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6073 if (N->getOpcode() == ISD::TRUNCATE) {
6074 Op = N->getOperand(0);
6075 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6079 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6080 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6083 SDValue Op0 = N->getOperand(0);
6084 SDValue Op1 = N->getOperand(1);
6085 assert(Op0.getValueType() == Op1.getValueType());
6087 if (isNullConstant(Op0))
6089 else if (isNullConstant(Op1))
6094 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6096 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6102 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6103 SDValue N0 = N->getOperand(0);
6104 EVT VT = N->getValueType(0);
6106 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6108 return SDValue(Res, 0);
6110 // fold (zext (zext x)) -> (zext x)
6111 // fold (zext (aext x)) -> (zext x)
6112 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6113 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6116 // fold (zext (truncate x)) -> (zext x) or
6117 // (zext (truncate x)) -> (truncate x)
6118 // This is valid when the truncated bits of x are already zero.
6119 // FIXME: We should extend this to work for vectors too.
6122 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6123 APInt TruncatedBits =
6124 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6125 APInt(Op.getValueSizeInBits(), 0) :
6126 APInt::getBitsSet(Op.getValueSizeInBits(),
6127 N0.getValueSizeInBits(),
6128 std::min(Op.getValueSizeInBits(),
6129 VT.getSizeInBits()));
6130 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6131 if (VT.bitsGT(Op.getValueType()))
6132 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6133 if (VT.bitsLT(Op.getValueType()))
6134 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6140 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6141 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6142 if (N0.getOpcode() == ISD::TRUNCATE) {
6143 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6144 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6145 if (NarrowLoad.getNode() != N0.getNode()) {
6146 CombineTo(N0.getNode(), NarrowLoad);
6147 // CombineTo deleted the truncate, if needed, but not what's under it.
6150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6154 // fold (zext (truncate x)) -> (and x, mask)
6155 if (N0.getOpcode() == ISD::TRUNCATE) {
6156 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6157 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6158 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6159 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6160 if (NarrowLoad.getNode() != N0.getNode()) {
6161 CombineTo(N0.getNode(), NarrowLoad);
6162 // CombineTo deleted the truncate, if needed, but not what's under it.
6165 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6168 EVT SrcVT = N0.getOperand(0).getValueType();
6169 EVT MinVT = N0.getValueType();
6171 // Try to mask before the extension to avoid having to generate a larger mask,
6172 // possibly over several sub-vectors.
6173 if (SrcVT.bitsLT(VT)) {
6174 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6175 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6176 SDValue Op = N0.getOperand(0);
6177 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6178 AddToWorklist(Op.getNode());
6179 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6183 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6184 SDValue Op = N0.getOperand(0);
6185 if (SrcVT.bitsLT(VT)) {
6186 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6187 AddToWorklist(Op.getNode());
6188 } else if (SrcVT.bitsGT(VT)) {
6189 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6190 AddToWorklist(Op.getNode());
6192 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6196 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6197 // if either of the casts is not free.
6198 if (N0.getOpcode() == ISD::AND &&
6199 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6200 N0.getOperand(1).getOpcode() == ISD::Constant &&
6201 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6202 N0.getValueType()) ||
6203 !TLI.isZExtFree(N0.getValueType(), VT))) {
6204 SDValue X = N0.getOperand(0).getOperand(0);
6205 if (X.getValueType().bitsLT(VT)) {
6206 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6207 } else if (X.getValueType().bitsGT(VT)) {
6208 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6210 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6211 Mask = Mask.zext(VT.getSizeInBits());
6213 return DAG.getNode(ISD::AND, DL, VT,
6214 X, DAG.getConstant(Mask, DL, VT));
6217 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6218 // Only generate vector extloads when 1) they're legal, and 2) they are
6219 // deemed desirable by the target.
6220 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6221 ((!LegalOperations && !VT.isVector() &&
6222 !cast<LoadSDNode>(N0)->isVolatile()) ||
6223 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6224 bool DoXform = true;
6225 SmallVector<SDNode*, 4> SetCCs;
6226 if (!N0.hasOneUse())
6227 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6229 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6231 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6232 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6234 LN0->getBasePtr(), N0.getValueType(),
6235 LN0->getMemOperand());
6236 CombineTo(N, ExtLoad);
6237 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6238 N0.getValueType(), ExtLoad);
6239 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6241 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6247 // fold (zext (load x)) to multiple smaller zextloads.
6248 // Only on illegal but splittable vectors.
6249 if (SDValue ExtLoad = CombineExtLoad(N))
6252 // fold (zext (and/or/xor (load x), cst)) ->
6253 // (and/or/xor (zextload x), (zext cst))
6254 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6255 N0.getOpcode() == ISD::XOR) &&
6256 isa<LoadSDNode>(N0.getOperand(0)) &&
6257 N0.getOperand(1).getOpcode() == ISD::Constant &&
6258 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6259 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6260 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6261 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6262 bool DoXform = true;
6263 SmallVector<SDNode*, 4> SetCCs;
6264 if (!N0.hasOneUse())
6265 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6268 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6269 LN0->getChain(), LN0->getBasePtr(),
6271 LN0->getMemOperand());
6272 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6273 Mask = Mask.zext(VT.getSizeInBits());
6275 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6276 ExtLoad, DAG.getConstant(Mask, DL, VT));
6277 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6278 SDLoc(N0.getOperand(0)),
6279 N0.getOperand(0).getValueType(), ExtLoad);
6281 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6282 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6284 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6289 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6290 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6291 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6292 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6293 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6294 EVT MemVT = LN0->getMemoryVT();
6295 if ((!LegalOperations && !LN0->isVolatile()) ||
6296 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6297 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6299 LN0->getBasePtr(), MemVT,
6300 LN0->getMemOperand());
6301 CombineTo(N, ExtLoad);
6302 CombineTo(N0.getNode(),
6303 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6305 ExtLoad.getValue(1));
6306 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6310 if (N0.getOpcode() == ISD::SETCC) {
6311 if (!LegalOperations && VT.isVector() &&
6312 N0.getValueType().getVectorElementType() == MVT::i1) {
6313 EVT N0VT = N0.getOperand(0).getValueType();
6314 if (getSetCCResultType(N0VT) == N0.getValueType())
6317 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6318 // Only do this before legalize for now.
6319 EVT EltVT = VT.getVectorElementType();
6321 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6322 DAG.getConstant(1, DL, EltVT));
6323 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6324 // We know that the # elements of the results is the same as the
6325 // # elements of the compare (and the # elements of the compare result
6326 // for that matter). Check to see that they are the same size. If so,
6327 // we know that the element size of the sext'd result matches the
6328 // element size of the compare operands.
6329 return DAG.getNode(ISD::AND, DL, VT,
6330 DAG.getSetCC(DL, VT, N0.getOperand(0),
6332 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6333 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6336 // If the desired elements are smaller or larger than the source
6337 // elements we can use a matching integer vector type and then
6338 // truncate/sign extend
6339 EVT MatchingElementType =
6340 EVT::getIntegerVT(*DAG.getContext(),
6341 N0VT.getScalarType().getSizeInBits());
6342 EVT MatchingVectorType =
6343 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6344 N0VT.getVectorNumElements());
6346 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6348 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6349 return DAG.getNode(ISD::AND, DL, VT,
6350 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6351 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6354 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6357 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6358 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6359 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6360 if (SCC.getNode()) return SCC;
6363 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6364 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6365 isa<ConstantSDNode>(N0.getOperand(1)) &&
6366 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6368 SDValue ShAmt = N0.getOperand(1);
6369 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6370 if (N0.getOpcode() == ISD::SHL) {
6371 SDValue InnerZExt = N0.getOperand(0);
6372 // If the original shl may be shifting out bits, do not perform this
6374 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6375 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6376 if (ShAmtVal > KnownZeroBits)
6382 // Ensure that the shift amount is wide enough for the shifted value.
6383 if (VT.getSizeInBits() >= 256)
6384 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6386 return DAG.getNode(N0.getOpcode(), DL, VT,
6387 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6394 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6395 SDValue N0 = N->getOperand(0);
6396 EVT VT = N->getValueType(0);
6398 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6400 return SDValue(Res, 0);
6402 // fold (aext (aext x)) -> (aext x)
6403 // fold (aext (zext x)) -> (zext x)
6404 // fold (aext (sext x)) -> (sext x)
6405 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6406 N0.getOpcode() == ISD::ZERO_EXTEND ||
6407 N0.getOpcode() == ISD::SIGN_EXTEND)
6408 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6410 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6411 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6412 if (N0.getOpcode() == ISD::TRUNCATE) {
6413 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6414 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6415 if (NarrowLoad.getNode() != N0.getNode()) {
6416 CombineTo(N0.getNode(), NarrowLoad);
6417 // CombineTo deleted the truncate, if needed, but not what's under it.
6420 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6424 // fold (aext (truncate x))
6425 if (N0.getOpcode() == ISD::TRUNCATE) {
6426 SDValue TruncOp = N0.getOperand(0);
6427 if (TruncOp.getValueType() == VT)
6428 return TruncOp; // x iff x size == zext size.
6429 if (TruncOp.getValueType().bitsGT(VT))
6430 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6431 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6434 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6435 // if the trunc is not free.
6436 if (N0.getOpcode() == ISD::AND &&
6437 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6438 N0.getOperand(1).getOpcode() == ISD::Constant &&
6439 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6440 N0.getValueType())) {
6441 SDValue X = N0.getOperand(0).getOperand(0);
6442 if (X.getValueType().bitsLT(VT)) {
6443 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6444 } else if (X.getValueType().bitsGT(VT)) {
6445 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6447 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6448 Mask = Mask.zext(VT.getSizeInBits());
6450 return DAG.getNode(ISD::AND, DL, VT,
6451 X, DAG.getConstant(Mask, DL, VT));
6454 // fold (aext (load x)) -> (aext (truncate (extload x)))
6455 // None of the supported targets knows how to perform load and any_ext
6456 // on vectors in one instruction. We only perform this transformation on
6458 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6459 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6460 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6461 bool DoXform = true;
6462 SmallVector<SDNode*, 4> SetCCs;
6463 if (!N0.hasOneUse())
6464 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6466 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6467 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6469 LN0->getBasePtr(), N0.getValueType(),
6470 LN0->getMemOperand());
6471 CombineTo(N, ExtLoad);
6472 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6473 N0.getValueType(), ExtLoad);
6474 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6475 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6477 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6481 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6482 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6483 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6484 if (N0.getOpcode() == ISD::LOAD &&
6485 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6487 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6488 ISD::LoadExtType ExtType = LN0->getExtensionType();
6489 EVT MemVT = LN0->getMemoryVT();
6490 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6491 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6492 VT, LN0->getChain(), LN0->getBasePtr(),
6493 MemVT, LN0->getMemOperand());
6494 CombineTo(N, ExtLoad);
6495 CombineTo(N0.getNode(),
6496 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6497 N0.getValueType(), ExtLoad),
6498 ExtLoad.getValue(1));
6499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6503 if (N0.getOpcode() == ISD::SETCC) {
6505 // aext(setcc) -> vsetcc
6506 // aext(setcc) -> truncate(vsetcc)
6507 // aext(setcc) -> aext(vsetcc)
6508 // Only do this before legalize for now.
6509 if (VT.isVector() && !LegalOperations) {
6510 EVT N0VT = N0.getOperand(0).getValueType();
6511 // We know that the # elements of the results is the same as the
6512 // # elements of the compare (and the # elements of the compare result
6513 // for that matter). Check to see that they are the same size. If so,
6514 // we know that the element size of the sext'd result matches the
6515 // element size of the compare operands.
6516 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6517 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6519 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6520 // If the desired elements are smaller or larger than the source
6521 // elements we can use a matching integer vector type and then
6522 // truncate/any extend
6524 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6526 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6528 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6529 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6533 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6536 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6537 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6538 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6546 /// See if the specified operand can be simplified with the knowledge that only
6547 /// the bits specified by Mask are used. If so, return the simpler operand,
6548 /// otherwise return a null SDValue.
6549 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6550 switch (V.getOpcode()) {
6552 case ISD::Constant: {
6553 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6554 assert(CV && "Const value should be ConstSDNode.");
6555 const APInt &CVal = CV->getAPIntValue();
6556 APInt NewVal = CVal & Mask;
6558 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6563 // If the LHS or RHS don't contribute bits to the or, drop them.
6564 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6565 return V.getOperand(1);
6566 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6567 return V.getOperand(0);
6570 // Only look at single-use SRLs.
6571 if (!V.getNode()->hasOneUse())
6573 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6574 // See if we can recursively simplify the LHS.
6575 unsigned Amt = RHSC->getZExtValue();
6577 // Watch out for shift count overflow though.
6578 if (Amt >= Mask.getBitWidth()) break;
6579 APInt NewMask = Mask << Amt;
6580 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6581 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6582 SimplifyLHS, V.getOperand(1));
6588 /// If the result of a wider load is shifted to right of N bits and then
6589 /// truncated to a narrower type and where N is a multiple of number of bits of
6590 /// the narrower type, transform it to a narrower load from address + N / num of
6591 /// bits of new type. If the result is to be extended, also fold the extension
6592 /// to form a extending load.
6593 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6594 unsigned Opc = N->getOpcode();
6596 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6597 SDValue N0 = N->getOperand(0);
6598 EVT VT = N->getValueType(0);
6601 // This transformation isn't valid for vector loads.
6605 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6607 if (Opc == ISD::SIGN_EXTEND_INREG) {
6608 ExtType = ISD::SEXTLOAD;
6609 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6610 } else if (Opc == ISD::SRL) {
6611 // Another special-case: SRL is basically zero-extending a narrower value.
6612 ExtType = ISD::ZEXTLOAD;
6614 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6615 if (!N01) return SDValue();
6616 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6617 VT.getSizeInBits() - N01->getZExtValue());
6619 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6622 unsigned EVTBits = ExtVT.getSizeInBits();
6624 // Do not generate loads of non-round integer types since these can
6625 // be expensive (and would be wrong if the type is not byte sized).
6626 if (!ExtVT.isRound())
6630 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6631 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6632 ShAmt = N01->getZExtValue();
6633 // Is the shift amount a multiple of size of VT?
6634 if ((ShAmt & (EVTBits-1)) == 0) {
6635 N0 = N0.getOperand(0);
6636 // Is the load width a multiple of size of VT?
6637 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6641 // At this point, we must have a load or else we can't do the transform.
6642 if (!isa<LoadSDNode>(N0)) return SDValue();
6644 // Because a SRL must be assumed to *need* to zero-extend the high bits
6645 // (as opposed to anyext the high bits), we can't combine the zextload
6646 // lowering of SRL and an sextload.
6647 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6650 // If the shift amount is larger than the input type then we're not
6651 // accessing any of the loaded bytes. If the load was a zextload/extload
6652 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6653 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6658 // If the load is shifted left (and the result isn't shifted back right),
6659 // we can fold the truncate through the shift.
6660 unsigned ShLeftAmt = 0;
6661 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6662 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6663 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6664 ShLeftAmt = N01->getZExtValue();
6665 N0 = N0.getOperand(0);
6669 // If we haven't found a load, we can't narrow it. Don't transform one with
6670 // multiple uses, this would require adding a new load.
6671 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6674 // Don't change the width of a volatile load.
6675 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6676 if (LN0->isVolatile())
6679 // Verify that we are actually reducing a load width here.
6680 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6683 // For the transform to be legal, the load must produce only two values
6684 // (the value loaded and the chain). Don't transform a pre-increment
6685 // load, for example, which produces an extra value. Otherwise the
6686 // transformation is not equivalent, and the downstream logic to replace
6687 // uses gets things wrong.
6688 if (LN0->getNumValues() > 2)
6691 // If the load that we're shrinking is an extload and we're not just
6692 // discarding the extension we can't simply shrink the load. Bail.
6693 // TODO: It would be possible to merge the extensions in some cases.
6694 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6695 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6698 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6701 EVT PtrType = N0.getOperand(1).getValueType();
6703 if (PtrType == MVT::Untyped || PtrType.isExtended())
6704 // It's not possible to generate a constant of extended or untyped type.
6707 // For big endian targets, we need to adjust the offset to the pointer to
6708 // load the correct bytes.
6709 if (DAG.getDataLayout().isBigEndian()) {
6710 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6711 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6712 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6715 uint64_t PtrOff = ShAmt / 8;
6716 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6718 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6719 PtrType, LN0->getBasePtr(),
6720 DAG.getConstant(PtrOff, DL, PtrType));
6721 AddToWorklist(NewPtr.getNode());
6724 if (ExtType == ISD::NON_EXTLOAD)
6725 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6726 LN0->getPointerInfo().getWithOffset(PtrOff),
6727 LN0->isVolatile(), LN0->isNonTemporal(),
6728 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6730 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6731 LN0->getPointerInfo().getWithOffset(PtrOff),
6732 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6733 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6735 // Replace the old load's chain with the new load's chain.
6736 WorklistRemover DeadNodes(*this);
6737 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6739 // Shift the result left, if we've swallowed a left shift.
6740 SDValue Result = Load;
6741 if (ShLeftAmt != 0) {
6742 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6743 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6745 // If the shift amount is as large as the result size (but, presumably,
6746 // no larger than the source) then the useful bits of the result are
6747 // zero; we can't simply return the shortened shift, because the result
6748 // of that operation is undefined.
6750 if (ShLeftAmt >= VT.getSizeInBits())
6751 Result = DAG.getConstant(0, DL, VT);
6753 Result = DAG.getNode(ISD::SHL, DL, VT,
6754 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6757 // Return the new loaded value.
6761 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6762 SDValue N0 = N->getOperand(0);
6763 SDValue N1 = N->getOperand(1);
6764 EVT VT = N->getValueType(0);
6765 EVT EVT = cast<VTSDNode>(N1)->getVT();
6766 unsigned VTBits = VT.getScalarType().getSizeInBits();
6767 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6769 // fold (sext_in_reg c1) -> c1
6770 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6771 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6773 // If the input is already sign extended, just drop the extension.
6774 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6777 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6778 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6779 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6780 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6781 N0.getOperand(0), N1);
6783 // fold (sext_in_reg (sext x)) -> (sext x)
6784 // fold (sext_in_reg (aext x)) -> (sext x)
6785 // if x is small enough.
6786 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6787 SDValue N00 = N0.getOperand(0);
6788 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6789 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6790 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6793 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6794 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6795 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6797 // fold operands of sext_in_reg based on knowledge that the top bits are not
6799 if (SimplifyDemandedBits(SDValue(N, 0)))
6800 return SDValue(N, 0);
6802 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6803 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6804 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6807 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6808 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6809 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6810 if (N0.getOpcode() == ISD::SRL) {
6811 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6812 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6813 // We can turn this into an SRA iff the input to the SRL is already sign
6815 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6816 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6817 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6818 N0.getOperand(0), N0.getOperand(1));
6822 // fold (sext_inreg (extload x)) -> (sextload x)
6823 if (ISD::isEXTLoad(N0.getNode()) &&
6824 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6825 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6826 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6827 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6829 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6831 LN0->getBasePtr(), EVT,
6832 LN0->getMemOperand());
6833 CombineTo(N, ExtLoad);
6834 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6835 AddToWorklist(ExtLoad.getNode());
6836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6838 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6839 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6841 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6842 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6843 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6844 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6845 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6847 LN0->getBasePtr(), EVT,
6848 LN0->getMemOperand());
6849 CombineTo(N, ExtLoad);
6850 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6854 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6855 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6856 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6857 N0.getOperand(1), false);
6858 if (BSwap.getNode())
6859 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6863 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6864 // into a build_vector.
6865 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6866 SmallVector<SDValue, 8> Elts;
6867 unsigned NumElts = N0->getNumOperands();
6868 unsigned ShAmt = VTBits - EVTBits;
6870 for (unsigned i = 0; i != NumElts; ++i) {
6871 SDValue Op = N0->getOperand(i);
6872 if (Op->getOpcode() == ISD::UNDEF) {
6877 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6878 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6879 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6880 SDLoc(Op), Op.getValueType()));
6883 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6889 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6890 SDValue N0 = N->getOperand(0);
6891 EVT VT = N->getValueType(0);
6893 if (N0.getOpcode() == ISD::UNDEF)
6894 return DAG.getUNDEF(VT);
6896 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6898 return SDValue(Res, 0);
6903 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6904 SDValue N0 = N->getOperand(0);
6905 EVT VT = N->getValueType(0);
6906 bool isLE = DAG.getDataLayout().isLittleEndian();
6909 if (N0.getValueType() == N->getValueType(0))
6911 // fold (truncate c1) -> c1
6912 if (isConstantIntBuildVectorOrConstantInt(N0))
6913 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6914 // fold (truncate (truncate x)) -> (truncate x)
6915 if (N0.getOpcode() == ISD::TRUNCATE)
6916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6917 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6918 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6919 N0.getOpcode() == ISD::SIGN_EXTEND ||
6920 N0.getOpcode() == ISD::ANY_EXTEND) {
6921 if (N0.getOperand(0).getValueType().bitsLT(VT))
6922 // if the source is smaller than the dest, we still need an extend
6923 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6925 if (N0.getOperand(0).getValueType().bitsGT(VT))
6926 // if the source is larger than the dest, than we just need the truncate
6927 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6928 // if the source and dest are the same type, we can drop both the extend
6929 // and the truncate.
6930 return N0.getOperand(0);
6933 // Fold extract-and-trunc into a narrow extract. For example:
6934 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6935 // i32 y = TRUNCATE(i64 x)
6937 // v16i8 b = BITCAST (v2i64 val)
6938 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6940 // Note: We only run this optimization after type legalization (which often
6941 // creates this pattern) and before operation legalization after which
6942 // we need to be more careful about the vector instructions that we generate.
6943 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6944 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6946 EVT VecTy = N0.getOperand(0).getValueType();
6947 EVT ExTy = N0.getValueType();
6948 EVT TrTy = N->getValueType(0);
6950 unsigned NumElem = VecTy.getVectorNumElements();
6951 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6953 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6954 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6956 SDValue EltNo = N0->getOperand(1);
6957 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6958 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6959 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6960 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6962 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6963 NVT, N0.getOperand(0));
6966 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6968 DAG.getConstant(Index, DL, IndexTy));
6972 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6973 if (N0.getOpcode() == ISD::SELECT) {
6974 EVT SrcVT = N0.getValueType();
6975 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6976 TLI.isTruncateFree(SrcVT, VT)) {
6978 SDValue Cond = N0.getOperand(0);
6979 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6980 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6981 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6985 // Fold a series of buildvector, bitcast, and truncate if possible.
6987 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6988 // (2xi32 (buildvector x, y)).
6989 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6990 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6991 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6992 N0.getOperand(0).hasOneUse()) {
6994 SDValue BuildVect = N0.getOperand(0);
6995 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6996 EVT TruncVecEltTy = VT.getVectorElementType();
6998 // Check that the element types match.
6999 if (BuildVectEltTy == TruncVecEltTy) {
7000 // Now we only need to compute the offset of the truncated elements.
7001 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7002 unsigned TruncVecNumElts = VT.getVectorNumElements();
7003 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7005 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7006 "Invalid number of elements");
7008 SmallVector<SDValue, 8> Opnds;
7009 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7010 Opnds.push_back(BuildVect.getOperand(i));
7012 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7016 // See if we can simplify the input to this truncate through knowledge that
7017 // only the low bits are being used.
7018 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7019 // Currently we only perform this optimization on scalars because vectors
7020 // may have different active low bits.
7021 if (!VT.isVector()) {
7023 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7024 VT.getSizeInBits()));
7025 if (Shorter.getNode())
7026 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7028 // fold (truncate (load x)) -> (smaller load x)
7029 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7030 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7031 if (SDValue Reduced = ReduceLoadWidth(N))
7034 // Handle the case where the load remains an extending load even
7035 // after truncation.
7036 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7037 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7038 if (!LN0->isVolatile() &&
7039 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7040 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7041 VT, LN0->getChain(), LN0->getBasePtr(),
7043 LN0->getMemOperand());
7044 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7049 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7050 // where ... are all 'undef'.
7051 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7052 SmallVector<EVT, 8> VTs;
7055 unsigned NumDefs = 0;
7057 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7058 SDValue X = N0.getOperand(i);
7059 if (X.getOpcode() != ISD::UNDEF) {
7064 // Stop if more than one members are non-undef.
7067 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7068 VT.getVectorElementType(),
7069 X.getValueType().getVectorNumElements()));
7073 return DAG.getUNDEF(VT);
7076 assert(V.getNode() && "The single defined operand is empty!");
7077 SmallVector<SDValue, 8> Opnds;
7078 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7080 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7083 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7084 AddToWorklist(NV.getNode());
7085 Opnds.push_back(NV);
7087 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7091 // Simplify the operands using demanded-bits information.
7092 if (!VT.isVector() &&
7093 SimplifyDemandedBits(SDValue(N, 0)))
7094 return SDValue(N, 0);
7099 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7100 SDValue Elt = N->getOperand(i);
7101 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7102 return Elt.getNode();
7103 return Elt.getOperand(Elt.getResNo()).getNode();
7106 /// build_pair (load, load) -> load
7107 /// if load locations are consecutive.
7108 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7109 assert(N->getOpcode() == ISD::BUILD_PAIR);
7111 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7112 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7113 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7114 LD1->getAddressSpace() != LD2->getAddressSpace())
7116 EVT LD1VT = LD1->getValueType(0);
7118 if (ISD::isNON_EXTLoad(LD2) &&
7120 // If both are volatile this would reduce the number of volatile loads.
7121 // If one is volatile it might be ok, but play conservative and bail out.
7122 !LD1->isVolatile() &&
7123 !LD2->isVolatile() &&
7124 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7125 unsigned Align = LD1->getAlignment();
7126 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7127 VT.getTypeForEVT(*DAG.getContext()));
7129 if (NewAlign <= Align &&
7130 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7131 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7132 LD1->getBasePtr(), LD1->getPointerInfo(),
7133 false, false, false, Align);
7139 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7140 SDValue N0 = N->getOperand(0);
7141 EVT VT = N->getValueType(0);
7143 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7144 // Only do this before legalize, since afterward the target may be depending
7145 // on the bitconvert.
7146 // First check to see if this is all constant.
7148 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7150 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7152 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7153 assert(!DestEltVT.isVector() &&
7154 "Element type of vector ValueType must not be vector!");
7156 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7159 // If the input is a constant, let getNode fold it.
7160 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7161 // If we can't allow illegal operations, we need to check that this is just
7162 // a fp -> int or int -> conversion and that the resulting operation will
7164 if (!LegalOperations ||
7165 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7166 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7167 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7168 TLI.isOperationLegal(ISD::Constant, VT)))
7169 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7172 // (conv (conv x, t1), t2) -> (conv x, t2)
7173 if (N0.getOpcode() == ISD::BITCAST)
7174 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7177 // fold (conv (load x)) -> (load (conv*)x)
7178 // If the resultant load doesn't need a higher alignment than the original!
7179 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7180 // Do not change the width of a volatile load.
7181 !cast<LoadSDNode>(N0)->isVolatile() &&
7182 // Do not remove the cast if the types differ in endian layout.
7183 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7184 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7185 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7186 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7187 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7188 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7189 VT.getTypeForEVT(*DAG.getContext()));
7190 unsigned OrigAlign = LN0->getAlignment();
7192 if (Align <= OrigAlign) {
7193 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7194 LN0->getBasePtr(), LN0->getPointerInfo(),
7195 LN0->isVolatile(), LN0->isNonTemporal(),
7196 LN0->isInvariant(), OrigAlign,
7198 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7203 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7204 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7205 // This often reduces constant pool loads.
7206 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7207 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7208 N0.getNode()->hasOneUse() && VT.isInteger() &&
7209 !VT.isVector() && !N0.getValueType().isVector()) {
7210 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7212 AddToWorklist(NewConv.getNode());
7215 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7216 if (N0.getOpcode() == ISD::FNEG)
7217 return DAG.getNode(ISD::XOR, DL, VT,
7218 NewConv, DAG.getConstant(SignBit, DL, VT));
7219 assert(N0.getOpcode() == ISD::FABS);
7220 return DAG.getNode(ISD::AND, DL, VT,
7221 NewConv, DAG.getConstant(~SignBit, DL, VT));
7224 // fold (bitconvert (fcopysign cst, x)) ->
7225 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7226 // Note that we don't handle (copysign x, cst) because this can always be
7227 // folded to an fneg or fabs.
7228 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7229 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7230 VT.isInteger() && !VT.isVector()) {
7231 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7232 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7233 if (isTypeLegal(IntXVT)) {
7234 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7235 IntXVT, N0.getOperand(1));
7236 AddToWorklist(X.getNode());
7238 // If X has a different width than the result/lhs, sext it or truncate it.
7239 unsigned VTWidth = VT.getSizeInBits();
7240 if (OrigXWidth < VTWidth) {
7241 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7242 AddToWorklist(X.getNode());
7243 } else if (OrigXWidth > VTWidth) {
7244 // To get the sign bit in the right place, we have to shift it right
7245 // before truncating.
7247 X = DAG.getNode(ISD::SRL, DL,
7248 X.getValueType(), X,
7249 DAG.getConstant(OrigXWidth-VTWidth, DL,
7251 AddToWorklist(X.getNode());
7252 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7253 AddToWorklist(X.getNode());
7256 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7257 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7258 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7259 AddToWorklist(X.getNode());
7261 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7262 VT, N0.getOperand(0));
7263 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7264 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7265 AddToWorklist(Cst.getNode());
7267 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7271 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7272 if (N0.getOpcode() == ISD::BUILD_PAIR)
7273 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7276 // Remove double bitcasts from shuffles - this is often a legacy of
7277 // XformToShuffleWithZero being used to combine bitmaskings (of
7278 // float vectors bitcast to integer vectors) into shuffles.
7279 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7280 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7281 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7282 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7283 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7284 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7286 // If operands are a bitcast, peek through if it casts the original VT.
7287 // If operands are a constant, just bitcast back to original VT.
7288 auto PeekThroughBitcast = [&](SDValue Op) {
7289 if (Op.getOpcode() == ISD::BITCAST &&
7290 Op.getOperand(0).getValueType() == VT)
7291 return SDValue(Op.getOperand(0));
7292 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7293 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7294 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7298 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7299 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7304 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7305 SmallVector<int, 8> NewMask;
7306 for (int M : SVN->getMask())
7307 for (int i = 0; i != MaskScale; ++i)
7308 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7310 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7312 std::swap(SV0, SV1);
7313 ShuffleVectorSDNode::commuteMask(NewMask);
7314 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7318 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7324 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7325 EVT VT = N->getValueType(0);
7326 return CombineConsecutiveLoads(N, VT);
7329 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7330 /// operands. DstEltVT indicates the destination element value type.
7331 SDValue DAGCombiner::
7332 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7333 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7335 // If this is already the right type, we're done.
7336 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7338 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7339 unsigned DstBitSize = DstEltVT.getSizeInBits();
7341 // If this is a conversion of N elements of one type to N elements of another
7342 // type, convert each element. This handles FP<->INT cases.
7343 if (SrcBitSize == DstBitSize) {
7344 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7345 BV->getValueType(0).getVectorNumElements());
7347 // Due to the FP element handling below calling this routine recursively,
7348 // we can end up with a scalar-to-vector node here.
7349 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7350 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7351 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7352 DstEltVT, BV->getOperand(0)));
7354 SmallVector<SDValue, 8> Ops;
7355 for (SDValue Op : BV->op_values()) {
7356 // If the vector element type is not legal, the BUILD_VECTOR operands
7357 // are promoted and implicitly truncated. Make that explicit here.
7358 if (Op.getValueType() != SrcEltVT)
7359 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7360 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7362 AddToWorklist(Ops.back().getNode());
7364 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7367 // Otherwise, we're growing or shrinking the elements. To avoid having to
7368 // handle annoying details of growing/shrinking FP values, we convert them to
7370 if (SrcEltVT.isFloatingPoint()) {
7371 // Convert the input float vector to a int vector where the elements are the
7373 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7374 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7378 // Now we know the input is an integer vector. If the output is a FP type,
7379 // convert to integer first, then to FP of the right size.
7380 if (DstEltVT.isFloatingPoint()) {
7381 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7382 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7384 // Next, convert to FP elements of the same size.
7385 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7390 // Okay, we know the src/dst types are both integers of differing types.
7391 // Handling growing first.
7392 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7393 if (SrcBitSize < DstBitSize) {
7394 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7396 SmallVector<SDValue, 8> Ops;
7397 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7398 i += NumInputsPerOutput) {
7399 bool isLE = DAG.getDataLayout().isLittleEndian();
7400 APInt NewBits = APInt(DstBitSize, 0);
7401 bool EltIsUndef = true;
7402 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7403 // Shift the previously computed bits over.
7404 NewBits <<= SrcBitSize;
7405 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7406 if (Op.getOpcode() == ISD::UNDEF) continue;
7409 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7410 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7414 Ops.push_back(DAG.getUNDEF(DstEltVT));
7416 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7419 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7420 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7423 // Finally, this must be the case where we are shrinking elements: each input
7424 // turns into multiple outputs.
7425 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7426 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7427 NumOutputsPerInput*BV->getNumOperands());
7428 SmallVector<SDValue, 8> Ops;
7430 for (const SDValue &Op : BV->op_values()) {
7431 if (Op.getOpcode() == ISD::UNDEF) {
7432 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7436 APInt OpVal = cast<ConstantSDNode>(Op)->
7437 getAPIntValue().zextOrTrunc(SrcBitSize);
7439 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7440 APInt ThisVal = OpVal.trunc(DstBitSize);
7441 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7442 OpVal = OpVal.lshr(DstBitSize);
7445 // For big endian targets, swap the order of the pieces of each element.
7446 if (DAG.getDataLayout().isBigEndian())
7447 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7450 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7453 /// Try to perform FMA combining on a given FADD node.
7454 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7455 SDValue N0 = N->getOperand(0);
7456 SDValue N1 = N->getOperand(1);
7457 EVT VT = N->getValueType(0);
7460 const TargetOptions &Options = DAG.getTarget().Options;
7461 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7462 Options.UnsafeFPMath);
7464 // Floating-point multiply-add with intermediate rounding.
7465 bool HasFMAD = (LegalOperations &&
7466 TLI.isOperationLegal(ISD::FMAD, VT));
7468 // Floating-point multiply-add without intermediate rounding.
7469 bool HasFMA = ((!LegalOperations ||
7470 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7471 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7474 // No valid opcode, do not combine.
7475 if (!HasFMAD && !HasFMA)
7478 // Always prefer FMAD to FMA for precision.
7479 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7480 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7481 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7483 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7484 // prefer to fold the multiply with fewer uses.
7485 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7486 N1.getOpcode() == ISD::FMUL) {
7487 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7491 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7492 if (N0.getOpcode() == ISD::FMUL &&
7493 (Aggressive || N0->hasOneUse())) {
7494 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7495 N0.getOperand(0), N0.getOperand(1), N1);
7498 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7499 // Note: Commutes FADD operands.
7500 if (N1.getOpcode() == ISD::FMUL &&
7501 (Aggressive || N1->hasOneUse())) {
7502 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7503 N1.getOperand(0), N1.getOperand(1), N0);
7506 // Look through FP_EXTEND nodes to do more combining.
7507 if (UnsafeFPMath && LookThroughFPExt) {
7508 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7509 if (N0.getOpcode() == ISD::FP_EXTEND) {
7510 SDValue N00 = N0.getOperand(0);
7511 if (N00.getOpcode() == ISD::FMUL)
7512 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7513 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7515 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7516 N00.getOperand(1)), N1);
7519 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7520 // Note: Commutes FADD operands.
7521 if (N1.getOpcode() == ISD::FP_EXTEND) {
7522 SDValue N10 = N1.getOperand(0);
7523 if (N10.getOpcode() == ISD::FMUL)
7524 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7525 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7527 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7528 N10.getOperand(1)), N0);
7532 // More folding opportunities when target permits.
7533 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7534 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7535 if (N0.getOpcode() == PreferredFusedOpcode &&
7536 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7537 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7538 N0.getOperand(0), N0.getOperand(1),
7539 DAG.getNode(PreferredFusedOpcode, SL, VT,
7540 N0.getOperand(2).getOperand(0),
7541 N0.getOperand(2).getOperand(1),
7545 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7546 if (N1->getOpcode() == PreferredFusedOpcode &&
7547 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7548 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7549 N1.getOperand(0), N1.getOperand(1),
7550 DAG.getNode(PreferredFusedOpcode, SL, VT,
7551 N1.getOperand(2).getOperand(0),
7552 N1.getOperand(2).getOperand(1),
7556 if (UnsafeFPMath && LookThroughFPExt) {
7557 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7558 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7559 auto FoldFAddFMAFPExtFMul = [&] (
7560 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7561 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7562 DAG.getNode(PreferredFusedOpcode, SL, VT,
7563 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7564 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7567 if (N0.getOpcode() == PreferredFusedOpcode) {
7568 SDValue N02 = N0.getOperand(2);
7569 if (N02.getOpcode() == ISD::FP_EXTEND) {
7570 SDValue N020 = N02.getOperand(0);
7571 if (N020.getOpcode() == ISD::FMUL)
7572 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7573 N020.getOperand(0), N020.getOperand(1),
7578 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7579 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7580 // FIXME: This turns two single-precision and one double-precision
7581 // operation into two double-precision operations, which might not be
7582 // interesting for all targets, especially GPUs.
7583 auto FoldFAddFPExtFMAFMul = [&] (
7584 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7585 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7586 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7587 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7588 DAG.getNode(PreferredFusedOpcode, SL, VT,
7589 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7590 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7593 if (N0.getOpcode() == ISD::FP_EXTEND) {
7594 SDValue N00 = N0.getOperand(0);
7595 if (N00.getOpcode() == PreferredFusedOpcode) {
7596 SDValue N002 = N00.getOperand(2);
7597 if (N002.getOpcode() == ISD::FMUL)
7598 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7599 N002.getOperand(0), N002.getOperand(1),
7604 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7605 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7606 if (N1.getOpcode() == PreferredFusedOpcode) {
7607 SDValue N12 = N1.getOperand(2);
7608 if (N12.getOpcode() == ISD::FP_EXTEND) {
7609 SDValue N120 = N12.getOperand(0);
7610 if (N120.getOpcode() == ISD::FMUL)
7611 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7612 N120.getOperand(0), N120.getOperand(1),
7617 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7618 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7619 // FIXME: This turns two single-precision and one double-precision
7620 // operation into two double-precision operations, which might not be
7621 // interesting for all targets, especially GPUs.
7622 if (N1.getOpcode() == ISD::FP_EXTEND) {
7623 SDValue N10 = N1.getOperand(0);
7624 if (N10.getOpcode() == PreferredFusedOpcode) {
7625 SDValue N102 = N10.getOperand(2);
7626 if (N102.getOpcode() == ISD::FMUL)
7627 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7628 N102.getOperand(0), N102.getOperand(1),
7638 /// Try to perform FMA combining on a given FSUB node.
7639 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7640 SDValue N0 = N->getOperand(0);
7641 SDValue N1 = N->getOperand(1);
7642 EVT VT = N->getValueType(0);
7645 const TargetOptions &Options = DAG.getTarget().Options;
7646 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7647 Options.UnsafeFPMath);
7649 // Floating-point multiply-add with intermediate rounding.
7650 bool HasFMAD = (LegalOperations &&
7651 TLI.isOperationLegal(ISD::FMAD, VT));
7653 // Floating-point multiply-add without intermediate rounding.
7654 bool HasFMA = ((!LegalOperations ||
7655 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7656 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7659 // No valid opcode, do not combine.
7660 if (!HasFMAD && !HasFMA)
7663 // Always prefer FMAD to FMA for precision.
7664 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7665 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7666 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7668 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7669 if (N0.getOpcode() == ISD::FMUL &&
7670 (Aggressive || N0->hasOneUse())) {
7671 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7672 N0.getOperand(0), N0.getOperand(1),
7673 DAG.getNode(ISD::FNEG, SL, VT, N1));
7676 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7677 // Note: Commutes FSUB operands.
7678 if (N1.getOpcode() == ISD::FMUL &&
7679 (Aggressive || N1->hasOneUse()))
7680 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7681 DAG.getNode(ISD::FNEG, SL, VT,
7683 N1.getOperand(1), N0);
7685 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7686 if (N0.getOpcode() == ISD::FNEG &&
7687 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7688 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7689 SDValue N00 = N0.getOperand(0).getOperand(0);
7690 SDValue N01 = N0.getOperand(0).getOperand(1);
7691 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7692 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7693 DAG.getNode(ISD::FNEG, SL, VT, N1));
7696 // Look through FP_EXTEND nodes to do more combining.
7697 if (UnsafeFPMath && LookThroughFPExt) {
7698 // fold (fsub (fpext (fmul x, y)), z)
7699 // -> (fma (fpext x), (fpext y), (fneg z))
7700 if (N0.getOpcode() == ISD::FP_EXTEND) {
7701 SDValue N00 = N0.getOperand(0);
7702 if (N00.getOpcode() == ISD::FMUL)
7703 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7704 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7708 DAG.getNode(ISD::FNEG, SL, VT, N1));
7711 // fold (fsub x, (fpext (fmul y, z)))
7712 // -> (fma (fneg (fpext y)), (fpext z), x)
7713 // Note: Commutes FSUB operands.
7714 if (N1.getOpcode() == ISD::FP_EXTEND) {
7715 SDValue N10 = N1.getOperand(0);
7716 if (N10.getOpcode() == ISD::FMUL)
7717 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7718 DAG.getNode(ISD::FNEG, SL, VT,
7719 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7720 N10.getOperand(0))),
7721 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7727 // -> (fneg (fma (fpext x), (fpext y), z))
7728 // Note: This could be removed with appropriate canonicalization of the
7729 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7730 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7731 // from implementing the canonicalization in visitFSUB.
7732 if (N0.getOpcode() == ISD::FP_EXTEND) {
7733 SDValue N00 = N0.getOperand(0);
7734 if (N00.getOpcode() == ISD::FNEG) {
7735 SDValue N000 = N00.getOperand(0);
7736 if (N000.getOpcode() == ISD::FMUL) {
7737 return DAG.getNode(ISD::FNEG, SL, VT,
7738 DAG.getNode(PreferredFusedOpcode, SL, VT,
7739 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7740 N000.getOperand(0)),
7741 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7742 N000.getOperand(1)),
7748 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7749 // -> (fneg (fma (fpext x)), (fpext y), z)
7750 // Note: This could be removed with appropriate canonicalization of the
7751 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7752 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7753 // from implementing the canonicalization in visitFSUB.
7754 if (N0.getOpcode() == ISD::FNEG) {
7755 SDValue N00 = N0.getOperand(0);
7756 if (N00.getOpcode() == ISD::FP_EXTEND) {
7757 SDValue N000 = N00.getOperand(0);
7758 if (N000.getOpcode() == ISD::FMUL) {
7759 return DAG.getNode(ISD::FNEG, SL, VT,
7760 DAG.getNode(PreferredFusedOpcode, SL, VT,
7761 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7762 N000.getOperand(0)),
7763 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7764 N000.getOperand(1)),
7772 // More folding opportunities when target permits.
7773 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7774 // fold (fsub (fma x, y, (fmul u, v)), z)
7775 // -> (fma x, y (fma u, v, (fneg z)))
7776 if (N0.getOpcode() == PreferredFusedOpcode &&
7777 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7778 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7779 N0.getOperand(0), N0.getOperand(1),
7780 DAG.getNode(PreferredFusedOpcode, SL, VT,
7781 N0.getOperand(2).getOperand(0),
7782 N0.getOperand(2).getOperand(1),
7783 DAG.getNode(ISD::FNEG, SL, VT,
7787 // fold (fsub x, (fma y, z, (fmul u, v)))
7788 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7789 if (N1.getOpcode() == PreferredFusedOpcode &&
7790 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7791 SDValue N20 = N1.getOperand(2).getOperand(0);
7792 SDValue N21 = N1.getOperand(2).getOperand(1);
7793 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7794 DAG.getNode(ISD::FNEG, SL, VT,
7797 DAG.getNode(PreferredFusedOpcode, SL, VT,
7798 DAG.getNode(ISD::FNEG, SL, VT, N20),
7803 if (UnsafeFPMath && LookThroughFPExt) {
7804 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7805 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7806 if (N0.getOpcode() == PreferredFusedOpcode) {
7807 SDValue N02 = N0.getOperand(2);
7808 if (N02.getOpcode() == ISD::FP_EXTEND) {
7809 SDValue N020 = N02.getOperand(0);
7810 if (N020.getOpcode() == ISD::FMUL)
7811 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7812 N0.getOperand(0), N0.getOperand(1),
7813 DAG.getNode(PreferredFusedOpcode, SL, VT,
7814 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7815 N020.getOperand(0)),
7816 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7817 N020.getOperand(1)),
7818 DAG.getNode(ISD::FNEG, SL, VT,
7823 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7824 // -> (fma (fpext x), (fpext y),
7825 // (fma (fpext u), (fpext v), (fneg z)))
7826 // FIXME: This turns two single-precision and one double-precision
7827 // operation into two double-precision operations, which might not be
7828 // interesting for all targets, especially GPUs.
7829 if (N0.getOpcode() == ISD::FP_EXTEND) {
7830 SDValue N00 = N0.getOperand(0);
7831 if (N00.getOpcode() == PreferredFusedOpcode) {
7832 SDValue N002 = N00.getOperand(2);
7833 if (N002.getOpcode() == ISD::FMUL)
7834 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7835 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7837 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7839 DAG.getNode(PreferredFusedOpcode, SL, VT,
7840 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7841 N002.getOperand(0)),
7842 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7843 N002.getOperand(1)),
7844 DAG.getNode(ISD::FNEG, SL, VT,
7849 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7850 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7851 if (N1.getOpcode() == PreferredFusedOpcode &&
7852 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7853 SDValue N120 = N1.getOperand(2).getOperand(0);
7854 if (N120.getOpcode() == ISD::FMUL) {
7855 SDValue N1200 = N120.getOperand(0);
7856 SDValue N1201 = N120.getOperand(1);
7857 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7858 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7860 DAG.getNode(PreferredFusedOpcode, SL, VT,
7861 DAG.getNode(ISD::FNEG, SL, VT,
7862 DAG.getNode(ISD::FP_EXTEND, SL,
7864 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7870 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7871 // -> (fma (fneg (fpext y)), (fpext z),
7872 // (fma (fneg (fpext u)), (fpext v), x))
7873 // FIXME: This turns two single-precision and one double-precision
7874 // operation into two double-precision operations, which might not be
7875 // interesting for all targets, especially GPUs.
7876 if (N1.getOpcode() == ISD::FP_EXTEND &&
7877 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7878 SDValue N100 = N1.getOperand(0).getOperand(0);
7879 SDValue N101 = N1.getOperand(0).getOperand(1);
7880 SDValue N102 = N1.getOperand(0).getOperand(2);
7881 if (N102.getOpcode() == ISD::FMUL) {
7882 SDValue N1020 = N102.getOperand(0);
7883 SDValue N1021 = N102.getOperand(1);
7884 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7885 DAG.getNode(ISD::FNEG, SL, VT,
7886 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7889 DAG.getNode(PreferredFusedOpcode, SL, VT,
7890 DAG.getNode(ISD::FNEG, SL, VT,
7891 DAG.getNode(ISD::FP_EXTEND, SL,
7893 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7904 SDValue DAGCombiner::visitFADD(SDNode *N) {
7905 SDValue N0 = N->getOperand(0);
7906 SDValue N1 = N->getOperand(1);
7907 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7908 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7909 EVT VT = N->getValueType(0);
7911 const TargetOptions &Options = DAG.getTarget().Options;
7915 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7918 // fold (fadd c1, c2) -> c1 + c2
7920 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7922 // canonicalize constant to RHS
7923 if (N0CFP && !N1CFP)
7924 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7926 // fold (fadd A, (fneg B)) -> (fsub A, B)
7927 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7928 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7929 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7930 GetNegatedExpression(N1, DAG, LegalOperations));
7932 // fold (fadd (fneg A), B) -> (fsub B, A)
7933 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7934 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7935 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7936 GetNegatedExpression(N0, DAG, LegalOperations));
7938 // If 'unsafe math' is enabled, fold lots of things.
7939 if (Options.UnsafeFPMath) {
7940 // No FP constant should be created after legalization as Instruction
7941 // Selection pass has a hard time dealing with FP constants.
7942 bool AllowNewConst = (Level < AfterLegalizeDAG);
7944 // fold (fadd A, 0) -> A
7945 if (N1CFP && N1CFP->isZero())
7948 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7949 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7950 isa<ConstantFPSDNode>(N0.getOperand(1)))
7951 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7952 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7954 // If allowed, fold (fadd (fneg x), x) -> 0.0
7955 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7956 return DAG.getConstantFP(0.0, DL, VT);
7958 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7959 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7960 return DAG.getConstantFP(0.0, DL, VT);
7962 // We can fold chains of FADD's of the same value into multiplications.
7963 // This transform is not safe in general because we are reducing the number
7964 // of rounding steps.
7965 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7966 if (N0.getOpcode() == ISD::FMUL) {
7967 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7968 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7970 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7971 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7972 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7973 DAG.getConstantFP(1.0, DL, VT));
7974 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7977 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7978 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7979 N1.getOperand(0) == N1.getOperand(1) &&
7980 N0.getOperand(0) == N1.getOperand(0)) {
7981 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7982 DAG.getConstantFP(2.0, DL, VT));
7983 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7987 if (N1.getOpcode() == ISD::FMUL) {
7988 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7989 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7991 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7992 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7993 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7994 DAG.getConstantFP(1.0, DL, VT));
7995 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7998 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7999 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8000 N0.getOperand(0) == N0.getOperand(1) &&
8001 N1.getOperand(0) == N0.getOperand(0)) {
8002 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8003 DAG.getConstantFP(2.0, DL, VT));
8004 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8008 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8009 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8010 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8011 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8012 (N0.getOperand(0) == N1)) {
8013 return DAG.getNode(ISD::FMUL, DL, VT,
8014 N1, DAG.getConstantFP(3.0, DL, VT));
8018 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8019 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8020 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8021 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8022 N1.getOperand(0) == N0) {
8023 return DAG.getNode(ISD::FMUL, DL, VT,
8024 N0, DAG.getConstantFP(3.0, DL, VT));
8028 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8029 if (AllowNewConst &&
8030 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8031 N0.getOperand(0) == N0.getOperand(1) &&
8032 N1.getOperand(0) == N1.getOperand(1) &&
8033 N0.getOperand(0) == N1.getOperand(0)) {
8034 return DAG.getNode(ISD::FMUL, DL, VT,
8035 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8038 } // enable-unsafe-fp-math
8040 // FADD -> FMA combines:
8041 if (SDValue Fused = visitFADDForFMACombine(N)) {
8042 AddToWorklist(Fused.getNode());
8049 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8050 SDValue N0 = N->getOperand(0);
8051 SDValue N1 = N->getOperand(1);
8052 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8053 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8054 EVT VT = N->getValueType(0);
8056 const TargetOptions &Options = DAG.getTarget().Options;
8060 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8063 // fold (fsub c1, c2) -> c1-c2
8065 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8067 // fold (fsub A, (fneg B)) -> (fadd A, B)
8068 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8069 return DAG.getNode(ISD::FADD, dl, VT, N0,
8070 GetNegatedExpression(N1, DAG, LegalOperations));
8072 // If 'unsafe math' is enabled, fold lots of things.
8073 if (Options.UnsafeFPMath) {
8075 if (N1CFP && N1CFP->isZero())
8078 // (fsub 0, B) -> -B
8079 if (N0CFP && N0CFP->isZero()) {
8080 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8081 return GetNegatedExpression(N1, DAG, LegalOperations);
8082 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8083 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8086 // (fsub x, x) -> 0.0
8088 return DAG.getConstantFP(0.0f, dl, VT);
8090 // (fsub x, (fadd x, y)) -> (fneg y)
8091 // (fsub x, (fadd y, x)) -> (fneg y)
8092 if (N1.getOpcode() == ISD::FADD) {
8093 SDValue N10 = N1->getOperand(0);
8094 SDValue N11 = N1->getOperand(1);
8096 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8097 return GetNegatedExpression(N11, DAG, LegalOperations);
8099 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8100 return GetNegatedExpression(N10, DAG, LegalOperations);
8104 // FSUB -> FMA combines:
8105 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8106 AddToWorklist(Fused.getNode());
8113 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8114 SDValue N0 = N->getOperand(0);
8115 SDValue N1 = N->getOperand(1);
8116 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8117 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8118 EVT VT = N->getValueType(0);
8120 const TargetOptions &Options = DAG.getTarget().Options;
8123 if (VT.isVector()) {
8124 // This just handles C1 * C2 for vectors. Other vector folds are below.
8125 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8129 // fold (fmul c1, c2) -> c1*c2
8131 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8133 // canonicalize constant to RHS
8134 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8135 !isConstantFPBuildVectorOrConstantFP(N1))
8136 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8138 // fold (fmul A, 1.0) -> A
8139 if (N1CFP && N1CFP->isExactlyValue(1.0))
8142 if (Options.UnsafeFPMath) {
8143 // fold (fmul A, 0) -> 0
8144 if (N1CFP && N1CFP->isZero())
8147 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8148 if (N0.getOpcode() == ISD::FMUL) {
8149 // Fold scalars or any vector constants (not just splats).
8150 // This fold is done in general by InstCombine, but extra fmul insts
8151 // may have been generated during lowering.
8152 SDValue N00 = N0.getOperand(0);
8153 SDValue N01 = N0.getOperand(1);
8154 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8155 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8156 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8158 // Check 1: Make sure that the first operand of the inner multiply is NOT
8159 // a constant. Otherwise, we may induce infinite looping.
8160 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8161 // Check 2: Make sure that the second operand of the inner multiply and
8162 // the second operand of the outer multiply are constants.
8163 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8164 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8165 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8166 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8171 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8172 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8173 // during an early run of DAGCombiner can prevent folding with fmuls
8174 // inserted during lowering.
8175 if (N0.getOpcode() == ISD::FADD &&
8176 (N0.getOperand(0) == N0.getOperand(1)) &&
8178 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8179 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8180 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8184 // fold (fmul X, 2.0) -> (fadd X, X)
8185 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8186 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8188 // fold (fmul X, -1.0) -> (fneg X)
8189 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8190 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8191 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8193 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8194 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8195 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8196 // Both can be negated for free, check to see if at least one is cheaper
8198 if (LHSNeg == 2 || RHSNeg == 2)
8199 return DAG.getNode(ISD::FMUL, DL, VT,
8200 GetNegatedExpression(N0, DAG, LegalOperations),
8201 GetNegatedExpression(N1, DAG, LegalOperations));
8208 SDValue DAGCombiner::visitFMA(SDNode *N) {
8209 SDValue N0 = N->getOperand(0);
8210 SDValue N1 = N->getOperand(1);
8211 SDValue N2 = N->getOperand(2);
8212 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8213 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8214 EVT VT = N->getValueType(0);
8216 const TargetOptions &Options = DAG.getTarget().Options;
8218 // Constant fold FMA.
8219 if (isa<ConstantFPSDNode>(N0) &&
8220 isa<ConstantFPSDNode>(N1) &&
8221 isa<ConstantFPSDNode>(N2)) {
8222 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8225 if (Options.UnsafeFPMath) {
8226 if (N0CFP && N0CFP->isZero())
8228 if (N1CFP && N1CFP->isZero())
8231 if (N0CFP && N0CFP->isExactlyValue(1.0))
8232 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8233 if (N1CFP && N1CFP->isExactlyValue(1.0))
8234 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8236 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8237 if (N0CFP && !N1CFP)
8238 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8240 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8241 if (Options.UnsafeFPMath && N1CFP &&
8242 N2.getOpcode() == ISD::FMUL &&
8243 N0 == N2.getOperand(0) &&
8244 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8245 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8246 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8250 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8251 if (Options.UnsafeFPMath &&
8252 N0.getOpcode() == ISD::FMUL && N1CFP &&
8253 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8254 return DAG.getNode(ISD::FMA, dl, VT,
8256 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8260 // (fma x, 1, y) -> (fadd x, y)
8261 // (fma x, -1, y) -> (fadd (fneg x), y)
8263 if (N1CFP->isExactlyValue(1.0))
8264 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8266 if (N1CFP->isExactlyValue(-1.0) &&
8267 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8268 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8269 AddToWorklist(RHSNeg.getNode());
8270 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8274 // (fma x, c, x) -> (fmul x, (c+1))
8275 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8276 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8277 DAG.getNode(ISD::FADD, dl, VT,
8278 N1, DAG.getConstantFP(1.0, dl, VT)));
8280 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8281 if (Options.UnsafeFPMath && N1CFP &&
8282 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8283 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8284 DAG.getNode(ISD::FADD, dl, VT,
8285 N1, DAG.getConstantFP(-1.0, dl, VT)));
8291 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8293 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8294 // Notice that this is not always beneficial. One reason is different target
8295 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8296 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8297 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8298 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8299 if (!DAG.getTarget().Options.UnsafeFPMath)
8302 // Skip if current node is a reciprocal.
8303 SDValue N0 = N->getOperand(0);
8304 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8305 if (N0CFP && N0CFP->isExactlyValue(1.0))
8308 // Exit early if the target does not want this transform or if there can't
8309 // possibly be enough uses of the divisor to make the transform worthwhile.
8310 SDValue N1 = N->getOperand(1);
8311 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8312 if (!MinUses || N1->use_size() < MinUses)
8315 // Find all FDIV users of the same divisor.
8316 // Use a set because duplicates may be present in the user list.
8317 SetVector<SDNode *> Users;
8318 for (auto *U : N1->uses())
8319 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8322 // Now that we have the actual number of divisor uses, make sure it meets
8323 // the minimum threshold specified by the target.
8324 if (Users.size() < MinUses)
8327 EVT VT = N->getValueType(0);
8329 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8330 // FIXME: This optimization requires some level of fast-math, so the
8331 // created reciprocal node should at least have the 'allowReciprocal'
8332 // fast-math-flag set.
8333 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8335 // Dividend / Divisor -> Dividend * Reciprocal
8336 for (auto *U : Users) {
8337 SDValue Dividend = U->getOperand(0);
8338 if (Dividend != FPOne) {
8339 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8341 CombineTo(U, NewNode);
8342 } else if (U != Reciprocal.getNode()) {
8343 // In the absence of fast-math-flags, this user node is always the
8344 // same node as Reciprocal, but with FMF they may be different nodes.
8345 CombineTo(U, Reciprocal);
8348 return SDValue(N, 0); // N was replaced.
8351 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8352 SDValue N0 = N->getOperand(0);
8353 SDValue N1 = N->getOperand(1);
8354 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8355 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8356 EVT VT = N->getValueType(0);
8358 const TargetOptions &Options = DAG.getTarget().Options;
8362 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8365 // fold (fdiv c1, c2) -> c1/c2
8367 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8369 if (Options.UnsafeFPMath) {
8370 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8372 // Compute the reciprocal 1.0 / c2.
8373 APFloat N1APF = N1CFP->getValueAPF();
8374 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8375 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8376 // Only do the transform if the reciprocal is a legal fp immediate that
8377 // isn't too nasty (eg NaN, denormal, ...).
8378 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8379 (!LegalOperations ||
8380 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8381 // backend)... we should handle this gracefully after Legalize.
8382 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8383 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8384 TLI.isFPImmLegal(Recip, VT)))
8385 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8386 DAG.getConstantFP(Recip, DL, VT));
8389 // If this FDIV is part of a reciprocal square root, it may be folded
8390 // into a target-specific square root estimate instruction.
8391 if (N1.getOpcode() == ISD::FSQRT) {
8392 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8393 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8395 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8396 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8397 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8398 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8399 AddToWorklist(RV.getNode());
8400 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8402 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8403 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8404 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8405 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8406 AddToWorklist(RV.getNode());
8407 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8409 } else if (N1.getOpcode() == ISD::FMUL) {
8410 // Look through an FMUL. Even though this won't remove the FDIV directly,
8411 // it's still worthwhile to get rid of the FSQRT if possible.
8414 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8415 SqrtOp = N1.getOperand(0);
8416 OtherOp = N1.getOperand(1);
8417 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8418 SqrtOp = N1.getOperand(1);
8419 OtherOp = N1.getOperand(0);
8421 if (SqrtOp.getNode()) {
8422 // We found a FSQRT, so try to make this fold:
8423 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8424 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8425 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8426 AddToWorklist(RV.getNode());
8427 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8432 // Fold into a reciprocal estimate and multiply instead of a real divide.
8433 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8434 AddToWorklist(RV.getNode());
8435 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8439 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8440 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8441 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8442 // Both can be negated for free, check to see if at least one is cheaper
8444 if (LHSNeg == 2 || RHSNeg == 2)
8445 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8446 GetNegatedExpression(N0, DAG, LegalOperations),
8447 GetNegatedExpression(N1, DAG, LegalOperations));
8451 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8452 return CombineRepeatedDivisors;
8457 SDValue DAGCombiner::visitFREM(SDNode *N) {
8458 SDValue N0 = N->getOperand(0);
8459 SDValue N1 = N->getOperand(1);
8460 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8462 EVT VT = N->getValueType(0);
8464 // fold (frem c1, c2) -> fmod(c1,c2)
8466 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8471 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8472 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8475 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8476 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8480 EVT VT = RV.getValueType();
8482 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8483 AddToWorklist(RV.getNode());
8485 // Unfortunately, RV is now NaN if the input was exactly 0.
8486 // Select out this case and force the answer to 0.
8487 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8488 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8489 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8490 AddToWorklist(ZeroCmp.getNode());
8491 AddToWorklist(RV.getNode());
8493 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8497 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8498 SDValue N0 = N->getOperand(0);
8499 SDValue N1 = N->getOperand(1);
8500 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8501 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8502 EVT VT = N->getValueType(0);
8504 if (N0CFP && N1CFP) // Constant fold
8505 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8508 const APFloat& V = N1CFP->getValueAPF();
8509 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8510 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8511 if (!V.isNegative()) {
8512 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8513 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8515 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8516 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8517 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8521 // copysign(fabs(x), y) -> copysign(x, y)
8522 // copysign(fneg(x), y) -> copysign(x, y)
8523 // copysign(copysign(x,z), y) -> copysign(x, y)
8524 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8525 N0.getOpcode() == ISD::FCOPYSIGN)
8526 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8527 N0.getOperand(0), N1);
8529 // copysign(x, abs(y)) -> abs(x)
8530 if (N1.getOpcode() == ISD::FABS)
8531 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8533 // copysign(x, copysign(y,z)) -> copysign(x, z)
8534 if (N1.getOpcode() == ISD::FCOPYSIGN)
8535 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8536 N0, N1.getOperand(1));
8538 // copysign(x, fp_extend(y)) -> copysign(x, y)
8539 // copysign(x, fp_round(y)) -> copysign(x, y)
8540 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8541 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8542 N0, N1.getOperand(0));
8547 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8548 SDValue N0 = N->getOperand(0);
8549 EVT VT = N->getValueType(0);
8550 EVT OpVT = N0.getValueType();
8552 // fold (sint_to_fp c1) -> c1fp
8553 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8554 // ...but only if the target supports immediate floating-point values
8555 (!LegalOperations ||
8556 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8557 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8559 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8560 // but UINT_TO_FP is legal on this target, try to convert.
8561 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8562 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8563 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8564 if (DAG.SignBitIsZero(N0))
8565 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8568 // The next optimizations are desirable only if SELECT_CC can be lowered.
8569 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8570 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8571 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8573 (!LegalOperations ||
8574 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8577 { N0.getOperand(0), N0.getOperand(1),
8578 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8580 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8583 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8584 // (select_cc x, y, 1.0, 0.0,, cc)
8585 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8586 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8587 (!LegalOperations ||
8588 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8591 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8592 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8593 N0.getOperand(0).getOperand(2) };
8594 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8601 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8602 SDValue N0 = N->getOperand(0);
8603 EVT VT = N->getValueType(0);
8604 EVT OpVT = N0.getValueType();
8606 // fold (uint_to_fp c1) -> c1fp
8607 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8608 // ...but only if the target supports immediate floating-point values
8609 (!LegalOperations ||
8610 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8611 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8613 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8614 // but SINT_TO_FP is legal on this target, try to convert.
8615 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8616 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8617 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8618 if (DAG.SignBitIsZero(N0))
8619 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8622 // The next optimizations are desirable only if SELECT_CC can be lowered.
8623 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8624 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8626 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8627 (!LegalOperations ||
8628 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8631 { N0.getOperand(0), N0.getOperand(1),
8632 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8634 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8641 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8642 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8643 SDValue N0 = N->getOperand(0);
8644 EVT VT = N->getValueType(0);
8646 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8649 SDValue Src = N0.getOperand(0);
8650 EVT SrcVT = Src.getValueType();
8651 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8652 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8654 // We can safely assume the conversion won't overflow the output range,
8655 // because (for example) (uint8_t)18293.f is undefined behavior.
8657 // Since we can assume the conversion won't overflow, our decision as to
8658 // whether the input will fit in the float should depend on the minimum
8659 // of the input range and output range.
8661 // This means this is also safe for a signed input and unsigned output, since
8662 // a negative input would lead to undefined behavior.
8663 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8664 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8665 unsigned ActualSize = std::min(InputSize, OutputSize);
8666 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8668 // We can only fold away the float conversion if the input range can be
8669 // represented exactly in the float range.
8670 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8671 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8672 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8674 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8676 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8677 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8680 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8685 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8686 SDValue N0 = N->getOperand(0);
8687 EVT VT = N->getValueType(0);
8689 // fold (fp_to_sint c1fp) -> c1
8690 if (isConstantFPBuildVectorOrConstantFP(N0))
8691 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8693 return FoldIntToFPToInt(N, DAG);
8696 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8697 SDValue N0 = N->getOperand(0);
8698 EVT VT = N->getValueType(0);
8700 // fold (fp_to_uint c1fp) -> c1
8701 if (isConstantFPBuildVectorOrConstantFP(N0))
8702 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8704 return FoldIntToFPToInt(N, DAG);
8707 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8708 SDValue N0 = N->getOperand(0);
8709 SDValue N1 = N->getOperand(1);
8710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8711 EVT VT = N->getValueType(0);
8713 // fold (fp_round c1fp) -> c1fp
8715 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8717 // fold (fp_round (fp_extend x)) -> x
8718 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8719 return N0.getOperand(0);
8721 // fold (fp_round (fp_round x)) -> (fp_round x)
8722 if (N0.getOpcode() == ISD::FP_ROUND) {
8723 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8724 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8725 // If the first fp_round isn't a value preserving truncation, it might
8726 // introduce a tie in the second fp_round, that wouldn't occur in the
8727 // single-step fp_round we want to fold to.
8728 // In other words, double rounding isn't the same as rounding.
8729 // Also, this is a value preserving truncation iff both fp_round's are.
8730 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8732 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8733 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8737 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8738 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8739 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8740 N0.getOperand(0), N1);
8741 AddToWorklist(Tmp.getNode());
8742 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8743 Tmp, N0.getOperand(1));
8749 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8750 SDValue N0 = N->getOperand(0);
8751 EVT VT = N->getValueType(0);
8752 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8753 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8755 // fold (fp_round_inreg c1fp) -> c1fp
8756 if (N0CFP && isTypeLegal(EVT)) {
8758 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8759 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8765 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8766 SDValue N0 = N->getOperand(0);
8767 EVT VT = N->getValueType(0);
8769 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8770 if (N->hasOneUse() &&
8771 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8774 // fold (fp_extend c1fp) -> c1fp
8775 if (isConstantFPBuildVectorOrConstantFP(N0))
8776 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8778 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8779 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8780 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8781 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8783 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8785 if (N0.getOpcode() == ISD::FP_ROUND
8786 && N0.getNode()->getConstantOperandVal(1) == 1) {
8787 SDValue In = N0.getOperand(0);
8788 if (In.getValueType() == VT) return In;
8789 if (VT.bitsLT(In.getValueType()))
8790 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8791 In, N0.getOperand(1));
8792 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8795 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8796 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8797 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8798 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8799 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8801 LN0->getBasePtr(), N0.getValueType(),
8802 LN0->getMemOperand());
8803 CombineTo(N, ExtLoad);
8804 CombineTo(N0.getNode(),
8805 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8806 N0.getValueType(), ExtLoad,
8807 DAG.getIntPtrConstant(1, SDLoc(N0))),
8808 ExtLoad.getValue(1));
8809 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8815 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8816 SDValue N0 = N->getOperand(0);
8817 EVT VT = N->getValueType(0);
8819 // fold (fceil c1) -> fceil(c1)
8820 if (isConstantFPBuildVectorOrConstantFP(N0))
8821 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8826 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8827 SDValue N0 = N->getOperand(0);
8828 EVT VT = N->getValueType(0);
8830 // fold (ftrunc c1) -> ftrunc(c1)
8831 if (isConstantFPBuildVectorOrConstantFP(N0))
8832 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8837 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8838 SDValue N0 = N->getOperand(0);
8839 EVT VT = N->getValueType(0);
8841 // fold (ffloor c1) -> ffloor(c1)
8842 if (isConstantFPBuildVectorOrConstantFP(N0))
8843 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8848 // FIXME: FNEG and FABS have a lot in common; refactor.
8849 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8850 SDValue N0 = N->getOperand(0);
8851 EVT VT = N->getValueType(0);
8853 // Constant fold FNEG.
8854 if (isConstantFPBuildVectorOrConstantFP(N0))
8855 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8857 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8858 &DAG.getTarget().Options))
8859 return GetNegatedExpression(N0, DAG, LegalOperations);
8861 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8862 // constant pool values.
8863 if (!TLI.isFNegFree(VT) &&
8864 N0.getOpcode() == ISD::BITCAST &&
8865 N0.getNode()->hasOneUse()) {
8866 SDValue Int = N0.getOperand(0);
8867 EVT IntVT = Int.getValueType();
8868 if (IntVT.isInteger() && !IntVT.isVector()) {
8870 if (N0.getValueType().isVector()) {
8871 // For a vector, get a mask such as 0x80... per scalar element
8873 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8874 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8876 // For a scalar, just generate 0x80...
8877 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8880 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8881 DAG.getConstant(SignMask, DL0, IntVT));
8882 AddToWorklist(Int.getNode());
8883 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8887 // (fneg (fmul c, x)) -> (fmul -c, x)
8888 if (N0.getOpcode() == ISD::FMUL &&
8889 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8890 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8892 APFloat CVal = CFP1->getValueAPF();
8894 if (Level >= AfterLegalizeDAG &&
8895 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8896 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8898 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8899 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8906 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8907 SDValue N0 = N->getOperand(0);
8908 SDValue N1 = N->getOperand(1);
8909 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8910 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8912 if (N0CFP && N1CFP) {
8913 const APFloat &C0 = N0CFP->getValueAPF();
8914 const APFloat &C1 = N1CFP->getValueAPF();
8915 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8919 EVT VT = N->getValueType(0);
8920 // Canonicalize to constant on RHS.
8921 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8927 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8928 SDValue N0 = N->getOperand(0);
8929 SDValue N1 = N->getOperand(1);
8930 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8931 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8933 if (N0CFP && N1CFP) {
8934 const APFloat &C0 = N0CFP->getValueAPF();
8935 const APFloat &C1 = N1CFP->getValueAPF();
8936 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8940 EVT VT = N->getValueType(0);
8941 // Canonicalize to constant on RHS.
8942 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8948 SDValue DAGCombiner::visitFABS(SDNode *N) {
8949 SDValue N0 = N->getOperand(0);
8950 EVT VT = N->getValueType(0);
8952 // fold (fabs c1) -> fabs(c1)
8953 if (isConstantFPBuildVectorOrConstantFP(N0))
8954 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8956 // fold (fabs (fabs x)) -> (fabs x)
8957 if (N0.getOpcode() == ISD::FABS)
8958 return N->getOperand(0);
8960 // fold (fabs (fneg x)) -> (fabs x)
8961 // fold (fabs (fcopysign x, y)) -> (fabs x)
8962 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8963 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8965 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8966 // constant pool values.
8967 if (!TLI.isFAbsFree(VT) &&
8968 N0.getOpcode() == ISD::BITCAST &&
8969 N0.getNode()->hasOneUse()) {
8970 SDValue Int = N0.getOperand(0);
8971 EVT IntVT = Int.getValueType();
8972 if (IntVT.isInteger() && !IntVT.isVector()) {
8974 if (N0.getValueType().isVector()) {
8975 // For a vector, get a mask such as 0x7f... per scalar element
8977 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8978 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8980 // For a scalar, just generate 0x7f...
8981 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8984 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8985 DAG.getConstant(SignMask, DL, IntVT));
8986 AddToWorklist(Int.getNode());
8987 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8994 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8995 SDValue Chain = N->getOperand(0);
8996 SDValue N1 = N->getOperand(1);
8997 SDValue N2 = N->getOperand(2);
8999 // If N is a constant we could fold this into a fallthrough or unconditional
9000 // branch. However that doesn't happen very often in normal code, because
9001 // Instcombine/SimplifyCFG should have handled the available opportunities.
9002 // If we did this folding here, it would be necessary to update the
9003 // MachineBasicBlock CFG, which is awkward.
9005 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9007 if (N1.getOpcode() == ISD::SETCC &&
9008 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9009 N1.getOperand(0).getValueType())) {
9010 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9011 Chain, N1.getOperand(2),
9012 N1.getOperand(0), N1.getOperand(1), N2);
9015 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9016 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9017 (N1.getOperand(0).hasOneUse() &&
9018 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9019 SDNode *Trunc = nullptr;
9020 if (N1.getOpcode() == ISD::TRUNCATE) {
9021 // Look pass the truncate.
9022 Trunc = N1.getNode();
9023 N1 = N1.getOperand(0);
9026 // Match this pattern so that we can generate simpler code:
9029 // %b = and i32 %a, 2
9030 // %c = srl i32 %b, 1
9031 // brcond i32 %c ...
9036 // %b = and i32 %a, 2
9037 // %c = setcc eq %b, 0
9040 // This applies only when the AND constant value has one bit set and the
9041 // SRL constant is equal to the log2 of the AND constant. The back-end is
9042 // smart enough to convert the result into a TEST/JMP sequence.
9043 SDValue Op0 = N1.getOperand(0);
9044 SDValue Op1 = N1.getOperand(1);
9046 if (Op0.getOpcode() == ISD::AND &&
9047 Op1.getOpcode() == ISD::Constant) {
9048 SDValue AndOp1 = Op0.getOperand(1);
9050 if (AndOp1.getOpcode() == ISD::Constant) {
9051 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9053 if (AndConst.isPowerOf2() &&
9054 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9058 getSetCCResultType(Op0.getValueType()),
9059 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9062 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9063 MVT::Other, Chain, SetCC, N2);
9064 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9065 // will convert it back to (X & C1) >> C2.
9066 CombineTo(N, NewBRCond, false);
9067 // Truncate is dead.
9069 deleteAndRecombine(Trunc);
9070 // Replace the uses of SRL with SETCC
9071 WorklistRemover DeadNodes(*this);
9072 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9073 deleteAndRecombine(N1.getNode());
9074 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9080 // Restore N1 if the above transformation doesn't match.
9081 N1 = N->getOperand(1);
9084 // Transform br(xor(x, y)) -> br(x != y)
9085 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9086 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9087 SDNode *TheXor = N1.getNode();
9088 SDValue Op0 = TheXor->getOperand(0);
9089 SDValue Op1 = TheXor->getOperand(1);
9090 if (Op0.getOpcode() == Op1.getOpcode()) {
9091 // Avoid missing important xor optimizations.
9092 if (SDValue Tmp = visitXOR(TheXor)) {
9093 if (Tmp.getNode() != TheXor) {
9094 DEBUG(dbgs() << "\nReplacing.8 ";
9096 dbgs() << "\nWith: ";
9097 Tmp.getNode()->dump(&DAG);
9099 WorklistRemover DeadNodes(*this);
9100 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9101 deleteAndRecombine(TheXor);
9102 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9103 MVT::Other, Chain, Tmp, N2);
9106 // visitXOR has changed XOR's operands or replaced the XOR completely,
9108 return SDValue(N, 0);
9112 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9114 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9115 Op0.getOpcode() == ISD::XOR) {
9116 TheXor = Op0.getNode();
9120 EVT SetCCVT = N1.getValueType();
9122 SetCCVT = getSetCCResultType(SetCCVT);
9123 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9126 Equal ? ISD::SETEQ : ISD::SETNE);
9127 // Replace the uses of XOR with SETCC
9128 WorklistRemover DeadNodes(*this);
9129 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9130 deleteAndRecombine(N1.getNode());
9131 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9132 MVT::Other, Chain, SetCC, N2);
9139 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9141 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9142 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9143 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9145 // If N is a constant we could fold this into a fallthrough or unconditional
9146 // branch. However that doesn't happen very often in normal code, because
9147 // Instcombine/SimplifyCFG should have handled the available opportunities.
9148 // If we did this folding here, it would be necessary to update the
9149 // MachineBasicBlock CFG, which is awkward.
9151 // Use SimplifySetCC to simplify SETCC's.
9152 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9153 CondLHS, CondRHS, CC->get(), SDLoc(N),
9155 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9157 // fold to a simpler setcc
9158 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9159 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9160 N->getOperand(0), Simp.getOperand(2),
9161 Simp.getOperand(0), Simp.getOperand(1),
9167 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9168 /// and that N may be folded in the load / store addressing mode.
9169 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9171 const TargetLowering &TLI) {
9175 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9176 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9178 VT = LD->getMemoryVT();
9179 AS = LD->getAddressSpace();
9180 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9181 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9183 VT = ST->getMemoryVT();
9184 AS = ST->getAddressSpace();
9188 TargetLowering::AddrMode AM;
9189 if (N->getOpcode() == ISD::ADD) {
9190 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9193 AM.BaseOffs = Offset->getSExtValue();
9197 } else if (N->getOpcode() == ISD::SUB) {
9198 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9201 AM.BaseOffs = -Offset->getSExtValue();
9208 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9209 VT.getTypeForEVT(*DAG.getContext()), AS);
9212 /// Try turning a load/store into a pre-indexed load/store when the base
9213 /// pointer is an add or subtract and it has other uses besides the load/store.
9214 /// After the transformation, the new indexed load/store has effectively folded
9215 /// the add/subtract in and all of its other uses are redirected to the
9217 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9218 if (Level < AfterLegalizeDAG)
9224 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9225 if (LD->isIndexed())
9227 VT = LD->getMemoryVT();
9228 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9229 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9231 Ptr = LD->getBasePtr();
9232 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9233 if (ST->isIndexed())
9235 VT = ST->getMemoryVT();
9236 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9237 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9239 Ptr = ST->getBasePtr();
9245 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9246 // out. There is no reason to make this a preinc/predec.
9247 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9248 Ptr.getNode()->hasOneUse())
9251 // Ask the target to do addressing mode selection.
9254 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9255 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9258 // Backends without true r+i pre-indexed forms may need to pass a
9259 // constant base with a variable offset so that constant coercion
9260 // will work with the patterns in canonical form.
9261 bool Swapped = false;
9262 if (isa<ConstantSDNode>(BasePtr)) {
9263 std::swap(BasePtr, Offset);
9267 // Don't create a indexed load / store with zero offset.
9268 if (isNullConstant(Offset))
9271 // Try turning it into a pre-indexed load / store except when:
9272 // 1) The new base ptr is a frame index.
9273 // 2) If N is a store and the new base ptr is either the same as or is a
9274 // predecessor of the value being stored.
9275 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9276 // that would create a cycle.
9277 // 4) All uses are load / store ops that use it as old base ptr.
9279 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9280 // (plus the implicit offset) to a register to preinc anyway.
9281 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9286 SDValue Val = cast<StoreSDNode>(N)->getValue();
9287 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9291 // If the offset is a constant, there may be other adds of constants that
9292 // can be folded with this one. We should do this to avoid having to keep
9293 // a copy of the original base pointer.
9294 SmallVector<SDNode *, 16> OtherUses;
9295 if (isa<ConstantSDNode>(Offset))
9296 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9297 UE = BasePtr.getNode()->use_end();
9299 SDUse &Use = UI.getUse();
9300 // Skip the use that is Ptr and uses of other results from BasePtr's
9301 // node (important for nodes that return multiple results).
9302 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9305 if (Use.getUser()->isPredecessorOf(N))
9308 if (Use.getUser()->getOpcode() != ISD::ADD &&
9309 Use.getUser()->getOpcode() != ISD::SUB) {
9314 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9315 if (!isa<ConstantSDNode>(Op1)) {
9320 // FIXME: In some cases, we can be smarter about this.
9321 if (Op1.getValueType() != Offset.getValueType()) {
9326 OtherUses.push_back(Use.getUser());
9330 std::swap(BasePtr, Offset);
9332 // Now check for #3 and #4.
9333 bool RealUse = false;
9335 // Caches for hasPredecessorHelper
9336 SmallPtrSet<const SDNode *, 32> Visited;
9337 SmallVector<const SDNode *, 16> Worklist;
9339 for (SDNode *Use : Ptr.getNode()->uses()) {
9342 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9345 // If Ptr may be folded in addressing mode of other use, then it's
9346 // not profitable to do this transformation.
9347 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9356 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9357 BasePtr, Offset, AM);
9359 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9360 BasePtr, Offset, AM);
9363 DEBUG(dbgs() << "\nReplacing.4 ";
9365 dbgs() << "\nWith: ";
9366 Result.getNode()->dump(&DAG);
9368 WorklistRemover DeadNodes(*this);
9370 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9371 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9373 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9376 // Finally, since the node is now dead, remove it from the graph.
9377 deleteAndRecombine(N);
9380 std::swap(BasePtr, Offset);
9382 // Replace other uses of BasePtr that can be updated to use Ptr
9383 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9384 unsigned OffsetIdx = 1;
9385 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9387 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9388 BasePtr.getNode() && "Expected BasePtr operand");
9390 // We need to replace ptr0 in the following expression:
9391 // x0 * offset0 + y0 * ptr0 = t0
9393 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9395 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9396 // indexed load/store and the expresion that needs to be re-written.
9398 // Therefore, we have:
9399 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9401 ConstantSDNode *CN =
9402 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9404 APInt Offset0 = CN->getAPIntValue();
9405 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9407 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9408 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9409 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9410 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9412 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9414 APInt CNV = Offset0;
9415 if (X0 < 0) CNV = -CNV;
9416 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9417 else CNV = CNV - Offset1;
9419 SDLoc DL(OtherUses[i]);
9421 // We can now generate the new expression.
9422 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9423 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9425 SDValue NewUse = DAG.getNode(Opcode,
9427 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9428 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9429 deleteAndRecombine(OtherUses[i]);
9432 // Replace the uses of Ptr with uses of the updated base value.
9433 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9434 deleteAndRecombine(Ptr.getNode());
9439 /// Try to combine a load/store with a add/sub of the base pointer node into a
9440 /// post-indexed load/store. The transformation folded the add/subtract into the
9441 /// new indexed load/store effectively and all of its uses are redirected to the
9443 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9444 if (Level < AfterLegalizeDAG)
9450 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9451 if (LD->isIndexed())
9453 VT = LD->getMemoryVT();
9454 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9455 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9457 Ptr = LD->getBasePtr();
9458 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9459 if (ST->isIndexed())
9461 VT = ST->getMemoryVT();
9462 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9463 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9465 Ptr = ST->getBasePtr();
9471 if (Ptr.getNode()->hasOneUse())
9474 for (SDNode *Op : Ptr.getNode()->uses()) {
9476 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9481 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9482 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9483 // Don't create a indexed load / store with zero offset.
9484 if (isNullConstant(Offset))
9487 // Try turning it into a post-indexed load / store except when
9488 // 1) All uses are load / store ops that use it as base ptr (and
9489 // it may be folded as addressing mmode).
9490 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9491 // nor a successor of N. Otherwise, if Op is folded that would
9494 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9498 bool TryNext = false;
9499 for (SDNode *Use : BasePtr.getNode()->uses()) {
9500 if (Use == Ptr.getNode())
9503 // If all the uses are load / store addresses, then don't do the
9505 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9506 bool RealUse = false;
9507 for (SDNode *UseUse : Use->uses()) {
9508 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9523 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9524 SDValue Result = isLoad
9525 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9526 BasePtr, Offset, AM)
9527 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9528 BasePtr, Offset, AM);
9531 DEBUG(dbgs() << "\nReplacing.5 ";
9533 dbgs() << "\nWith: ";
9534 Result.getNode()->dump(&DAG);
9536 WorklistRemover DeadNodes(*this);
9538 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9541 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9544 // Finally, since the node is now dead, remove it from the graph.
9545 deleteAndRecombine(N);
9547 // Replace the uses of Use with uses of the updated base value.
9548 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9549 Result.getValue(isLoad ? 1 : 0));
9550 deleteAndRecombine(Op);
9559 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9560 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9561 ISD::MemIndexedMode AM = LD->getAddressingMode();
9562 assert(AM != ISD::UNINDEXED);
9563 SDValue BP = LD->getOperand(1);
9564 SDValue Inc = LD->getOperand(2);
9566 // Some backends use TargetConstants for load offsets, but don't expect
9567 // TargetConstants in general ADD nodes. We can convert these constants into
9568 // regular Constants (if the constant is not opaque).
9569 assert((Inc.getOpcode() != ISD::TargetConstant ||
9570 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9571 "Cannot split out indexing using opaque target constants");
9572 if (Inc.getOpcode() == ISD::TargetConstant) {
9573 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9574 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9575 ConstInc->getValueType(0));
9579 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9580 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9583 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9584 LoadSDNode *LD = cast<LoadSDNode>(N);
9585 SDValue Chain = LD->getChain();
9586 SDValue Ptr = LD->getBasePtr();
9588 // If load is not volatile and there are no uses of the loaded value (and
9589 // the updated indexed value in case of indexed loads), change uses of the
9590 // chain value into uses of the chain input (i.e. delete the dead load).
9591 if (!LD->isVolatile()) {
9592 if (N->getValueType(1) == MVT::Other) {
9594 if (!N->hasAnyUseOfValue(0)) {
9595 // It's not safe to use the two value CombineTo variant here. e.g.
9596 // v1, chain2 = load chain1, loc
9597 // v2, chain3 = load chain2, loc
9599 // Now we replace use of chain2 with chain1. This makes the second load
9600 // isomorphic to the one we are deleting, and thus makes this load live.
9601 DEBUG(dbgs() << "\nReplacing.6 ";
9603 dbgs() << "\nWith chain: ";
9604 Chain.getNode()->dump(&DAG);
9606 WorklistRemover DeadNodes(*this);
9607 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9610 deleteAndRecombine(N);
9612 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9616 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9618 // If this load has an opaque TargetConstant offset, then we cannot split
9619 // the indexing into an add/sub directly (that TargetConstant may not be
9620 // valid for a different type of node, and we cannot convert an opaque
9621 // target constant into a regular constant).
9622 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9623 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9625 if (!N->hasAnyUseOfValue(0) &&
9626 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9627 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9629 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9630 Index = SplitIndexingFromLoad(LD);
9631 // Try to fold the base pointer arithmetic into subsequent loads and
9633 AddUsersToWorklist(N);
9635 Index = DAG.getUNDEF(N->getValueType(1));
9636 DEBUG(dbgs() << "\nReplacing.7 ";
9638 dbgs() << "\nWith: ";
9639 Undef.getNode()->dump(&DAG);
9640 dbgs() << " and 2 other values\n");
9641 WorklistRemover DeadNodes(*this);
9642 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9643 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9644 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9645 deleteAndRecombine(N);
9646 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9651 // If this load is directly stored, replace the load value with the stored
9653 // TODO: Handle store large -> read small portion.
9654 // TODO: Handle TRUNCSTORE/LOADEXT
9655 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9656 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9657 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9658 if (PrevST->getBasePtr() == Ptr &&
9659 PrevST->getValue().getValueType() == N->getValueType(0))
9660 return CombineTo(N, Chain.getOperand(1), Chain);
9664 // Try to infer better alignment information than the load already has.
9665 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9666 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9667 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9669 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9670 LD->getValueType(0),
9671 Chain, Ptr, LD->getPointerInfo(),
9673 LD->isVolatile(), LD->isNonTemporal(),
9674 LD->isInvariant(), Align, LD->getAAInfo());
9675 if (NewLoad.getNode() != N)
9676 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9681 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9682 : DAG.getSubtarget().useAA();
9684 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9685 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9688 if (UseAA && LD->isUnindexed()) {
9689 // Walk up chain skipping non-aliasing memory nodes.
9690 SDValue BetterChain = FindBetterChain(N, Chain);
9692 // If there is a better chain.
9693 if (Chain != BetterChain) {
9696 // Replace the chain to void dependency.
9697 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9698 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9699 BetterChain, Ptr, LD->getMemOperand());
9701 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9702 LD->getValueType(0),
9703 BetterChain, Ptr, LD->getMemoryVT(),
9704 LD->getMemOperand());
9707 // Create token factor to keep old chain connected.
9708 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9709 MVT::Other, Chain, ReplLoad.getValue(1));
9711 // Make sure the new and old chains are cleaned up.
9712 AddToWorklist(Token.getNode());
9714 // Replace uses with load result and token factor. Don't add users
9716 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9720 // Try transforming N to an indexed load.
9721 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9722 return SDValue(N, 0);
9724 // Try to slice up N to more direct loads if the slices are mapped to
9725 // different register banks or pairing can take place.
9727 return SDValue(N, 0);
9733 /// \brief Helper structure used to slice a load in smaller loads.
9734 /// Basically a slice is obtained from the following sequence:
9735 /// Origin = load Ty1, Base
9736 /// Shift = srl Ty1 Origin, CstTy Amount
9737 /// Inst = trunc Shift to Ty2
9739 /// Then, it will be rewriten into:
9740 /// Slice = load SliceTy, Base + SliceOffset
9741 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9743 /// SliceTy is deduced from the number of bits that are actually used to
9745 struct LoadedSlice {
9746 /// \brief Helper structure used to compute the cost of a slice.
9748 /// Are we optimizing for code size.
9753 unsigned CrossRegisterBanksCopies;
9757 Cost(bool ForCodeSize = false)
9758 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9759 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9761 /// \brief Get the cost of one isolated slice.
9762 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9763 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9764 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9765 EVT TruncType = LS.Inst->getValueType(0);
9766 EVT LoadedType = LS.getLoadedType();
9767 if (TruncType != LoadedType &&
9768 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9772 /// \brief Account for slicing gain in the current cost.
9773 /// Slicing provide a few gains like removing a shift or a
9774 /// truncate. This method allows to grow the cost of the original
9775 /// load with the gain from this slice.
9776 void addSliceGain(const LoadedSlice &LS) {
9777 // Each slice saves a truncate.
9778 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9779 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9780 LS.Inst->getValueType(0)))
9782 // If there is a shift amount, this slice gets rid of it.
9785 // If this slice can merge a cross register bank copy, account for it.
9786 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9787 ++CrossRegisterBanksCopies;
9790 Cost &operator+=(const Cost &RHS) {
9792 Truncates += RHS.Truncates;
9793 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9799 bool operator==(const Cost &RHS) const {
9800 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9801 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9802 ZExts == RHS.ZExts && Shift == RHS.Shift;
9805 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9807 bool operator<(const Cost &RHS) const {
9808 // Assume cross register banks copies are as expensive as loads.
9809 // FIXME: Do we want some more target hooks?
9810 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9811 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9812 // Unless we are optimizing for code size, consider the
9813 // expensive operation first.
9814 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9815 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9816 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9817 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9820 bool operator>(const Cost &RHS) const { return RHS < *this; }
9822 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9824 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9826 // The last instruction that represent the slice. This should be a
9827 // truncate instruction.
9829 // The original load instruction.
9831 // The right shift amount in bits from the original load.
9833 // The DAG from which Origin came from.
9834 // This is used to get some contextual information about legal types, etc.
9837 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9838 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9839 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9841 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9842 /// \return Result is \p BitWidth and has used bits set to 1 and
9843 /// not used bits set to 0.
9844 APInt getUsedBits() const {
9845 // Reproduce the trunc(lshr) sequence:
9846 // - Start from the truncated value.
9847 // - Zero extend to the desired bit width.
9849 assert(Origin && "No original load to compare against.");
9850 unsigned BitWidth = Origin->getValueSizeInBits(0);
9851 assert(Inst && "This slice is not bound to an instruction");
9852 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9853 "Extracted slice is bigger than the whole type!");
9854 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9855 UsedBits.setAllBits();
9856 UsedBits = UsedBits.zext(BitWidth);
9861 /// \brief Get the size of the slice to be loaded in bytes.
9862 unsigned getLoadedSize() const {
9863 unsigned SliceSize = getUsedBits().countPopulation();
9864 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9865 return SliceSize / 8;
9868 /// \brief Get the type that will be loaded for this slice.
9869 /// Note: This may not be the final type for the slice.
9870 EVT getLoadedType() const {
9871 assert(DAG && "Missing context");
9872 LLVMContext &Ctxt = *DAG->getContext();
9873 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9876 /// \brief Get the alignment of the load used for this slice.
9877 unsigned getAlignment() const {
9878 unsigned Alignment = Origin->getAlignment();
9879 unsigned Offset = getOffsetFromBase();
9881 Alignment = MinAlign(Alignment, Alignment + Offset);
9885 /// \brief Check if this slice can be rewritten with legal operations.
9886 bool isLegal() const {
9887 // An invalid slice is not legal.
9888 if (!Origin || !Inst || !DAG)
9891 // Offsets are for indexed load only, we do not handle that.
9892 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9895 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9897 // Check that the type is legal.
9898 EVT SliceType = getLoadedType();
9899 if (!TLI.isTypeLegal(SliceType))
9902 // Check that the load is legal for this type.
9903 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9906 // Check that the offset can be computed.
9907 // 1. Check its type.
9908 EVT PtrType = Origin->getBasePtr().getValueType();
9909 if (PtrType == MVT::Untyped || PtrType.isExtended())
9912 // 2. Check that it fits in the immediate.
9913 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9916 // 3. Check that the computation is legal.
9917 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9920 // Check that the zext is legal if it needs one.
9921 EVT TruncateType = Inst->getValueType(0);
9922 if (TruncateType != SliceType &&
9923 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9929 /// \brief Get the offset in bytes of this slice in the original chunk of
9931 /// \pre DAG != nullptr.
9932 uint64_t getOffsetFromBase() const {
9933 assert(DAG && "Missing context.");
9934 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9935 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9936 uint64_t Offset = Shift / 8;
9937 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9938 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9939 "The size of the original loaded type is not a multiple of a"
9941 // If Offset is bigger than TySizeInBytes, it means we are loading all
9942 // zeros. This should have been optimized before in the process.
9943 assert(TySizeInBytes > Offset &&
9944 "Invalid shift amount for given loaded size");
9946 Offset = TySizeInBytes - Offset - getLoadedSize();
9950 /// \brief Generate the sequence of instructions to load the slice
9951 /// represented by this object and redirect the uses of this slice to
9952 /// this new sequence of instructions.
9953 /// \pre this->Inst && this->Origin are valid Instructions and this
9954 /// object passed the legal check: LoadedSlice::isLegal returned true.
9955 /// \return The last instruction of the sequence used to load the slice.
9956 SDValue loadSlice() const {
9957 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9958 const SDValue &OldBaseAddr = Origin->getBasePtr();
9959 SDValue BaseAddr = OldBaseAddr;
9960 // Get the offset in that chunk of bytes w.r.t. the endianess.
9961 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9962 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9964 // BaseAddr = BaseAddr + Offset.
9965 EVT ArithType = BaseAddr.getValueType();
9967 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9968 DAG->getConstant(Offset, DL, ArithType));
9971 // Create the type of the loaded slice according to its size.
9972 EVT SliceType = getLoadedType();
9974 // Create the load for the slice.
9975 SDValue LastInst = DAG->getLoad(
9976 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9977 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9978 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9979 // If the final type is not the same as the loaded type, this means that
9980 // we have to pad with zero. Create a zero extend for that.
9981 EVT FinalType = Inst->getValueType(0);
9982 if (SliceType != FinalType)
9984 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9988 /// \brief Check if this slice can be merged with an expensive cross register
9989 /// bank copy. E.g.,
9991 /// f = bitcast i32 i to float
9992 bool canMergeExpensiveCrossRegisterBankCopy() const {
9993 if (!Inst || !Inst->hasOneUse())
9995 SDNode *Use = *Inst->use_begin();
9996 if (Use->getOpcode() != ISD::BITCAST)
9998 assert(DAG && "Missing context");
9999 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10000 EVT ResVT = Use->getValueType(0);
10001 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10002 const TargetRegisterClass *ArgRC =
10003 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10004 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10007 // At this point, we know that we perform a cross-register-bank copy.
10008 // Check if it is expensive.
10009 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10010 // Assume bitcasts are cheap, unless both register classes do not
10011 // explicitly share a common sub class.
10012 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10015 // Check if it will be merged with the load.
10016 // 1. Check the alignment constraint.
10017 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10018 ResVT.getTypeForEVT(*DAG->getContext()));
10020 if (RequiredAlignment > getAlignment())
10023 // 2. Check that the load is a legal operation for that type.
10024 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10027 // 3. Check that we do not have a zext in the way.
10028 if (Inst->getValueType(0) != getLoadedType())
10036 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10037 /// \p UsedBits looks like 0..0 1..1 0..0.
10038 static bool areUsedBitsDense(const APInt &UsedBits) {
10039 // If all the bits are one, this is dense!
10040 if (UsedBits.isAllOnesValue())
10043 // Get rid of the unused bits on the right.
10044 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10045 // Get rid of the unused bits on the left.
10046 if (NarrowedUsedBits.countLeadingZeros())
10047 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10048 // Check that the chunk of bits is completely used.
10049 return NarrowedUsedBits.isAllOnesValue();
10052 /// \brief Check whether or not \p First and \p Second are next to each other
10053 /// in memory. This means that there is no hole between the bits loaded
10054 /// by \p First and the bits loaded by \p Second.
10055 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10056 const LoadedSlice &Second) {
10057 assert(First.Origin == Second.Origin && First.Origin &&
10058 "Unable to match different memory origins.");
10059 APInt UsedBits = First.getUsedBits();
10060 assert((UsedBits & Second.getUsedBits()) == 0 &&
10061 "Slices are not supposed to overlap.");
10062 UsedBits |= Second.getUsedBits();
10063 return areUsedBitsDense(UsedBits);
10066 /// \brief Adjust the \p GlobalLSCost according to the target
10067 /// paring capabilities and the layout of the slices.
10068 /// \pre \p GlobalLSCost should account for at least as many loads as
10069 /// there is in the slices in \p LoadedSlices.
10070 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10071 LoadedSlice::Cost &GlobalLSCost) {
10072 unsigned NumberOfSlices = LoadedSlices.size();
10073 // If there is less than 2 elements, no pairing is possible.
10074 if (NumberOfSlices < 2)
10077 // Sort the slices so that elements that are likely to be next to each
10078 // other in memory are next to each other in the list.
10079 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10080 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10081 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10082 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10084 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10085 // First (resp. Second) is the first (resp. Second) potentially candidate
10086 // to be placed in a paired load.
10087 const LoadedSlice *First = nullptr;
10088 const LoadedSlice *Second = nullptr;
10089 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10090 // Set the beginning of the pair.
10093 Second = &LoadedSlices[CurrSlice];
10095 // If First is NULL, it means we start a new pair.
10096 // Get to the next slice.
10100 EVT LoadedType = First->getLoadedType();
10102 // If the types of the slices are different, we cannot pair them.
10103 if (LoadedType != Second->getLoadedType())
10106 // Check if the target supplies paired loads for this type.
10107 unsigned RequiredAlignment = 0;
10108 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10109 // move to the next pair, this type is hopeless.
10113 // Check if we meet the alignment requirement.
10114 if (RequiredAlignment > First->getAlignment())
10117 // Check that both loads are next to each other in memory.
10118 if (!areSlicesNextToEachOther(*First, *Second))
10121 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10122 --GlobalLSCost.Loads;
10123 // Move to the next pair.
10128 /// \brief Check the profitability of all involved LoadedSlice.
10129 /// Currently, it is considered profitable if there is exactly two
10130 /// involved slices (1) which are (2) next to each other in memory, and
10131 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10133 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10134 /// the elements themselves.
10136 /// FIXME: When the cost model will be mature enough, we can relax
10137 /// constraints (1) and (2).
10138 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10139 const APInt &UsedBits, bool ForCodeSize) {
10140 unsigned NumberOfSlices = LoadedSlices.size();
10141 if (StressLoadSlicing)
10142 return NumberOfSlices > 1;
10145 if (NumberOfSlices != 2)
10149 if (!areUsedBitsDense(UsedBits))
10153 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10154 // The original code has one big load.
10155 OrigCost.Loads = 1;
10156 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10157 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10158 // Accumulate the cost of all the slices.
10159 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10160 GlobalSlicingCost += SliceCost;
10162 // Account as cost in the original configuration the gain obtained
10163 // with the current slices.
10164 OrigCost.addSliceGain(LS);
10167 // If the target supports paired load, adjust the cost accordingly.
10168 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10169 return OrigCost > GlobalSlicingCost;
10172 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10173 /// operations, split it in the various pieces being extracted.
10175 /// This sort of thing is introduced by SROA.
10176 /// This slicing takes care not to insert overlapping loads.
10177 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10178 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10179 if (Level < AfterLegalizeDAG)
10182 LoadSDNode *LD = cast<LoadSDNode>(N);
10183 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10184 !LD->getValueType(0).isInteger())
10187 // Keep track of already used bits to detect overlapping values.
10188 // In that case, we will just abort the transformation.
10189 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10191 SmallVector<LoadedSlice, 4> LoadedSlices;
10193 // Check if this load is used as several smaller chunks of bits.
10194 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10195 // of computation for each trunc.
10196 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10197 UI != UIEnd; ++UI) {
10198 // Skip the uses of the chain.
10199 if (UI.getUse().getResNo() != 0)
10202 SDNode *User = *UI;
10203 unsigned Shift = 0;
10205 // Check if this is a trunc(lshr).
10206 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10207 isa<ConstantSDNode>(User->getOperand(1))) {
10208 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10209 User = *User->use_begin();
10212 // At this point, User is a Truncate, iff we encountered, trunc or
10214 if (User->getOpcode() != ISD::TRUNCATE)
10217 // The width of the type must be a power of 2 and greater than 8-bits.
10218 // Otherwise the load cannot be represented in LLVM IR.
10219 // Moreover, if we shifted with a non-8-bits multiple, the slice
10220 // will be across several bytes. We do not support that.
10221 unsigned Width = User->getValueSizeInBits(0);
10222 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10225 // Build the slice for this chain of computations.
10226 LoadedSlice LS(User, LD, Shift, &DAG);
10227 APInt CurrentUsedBits = LS.getUsedBits();
10229 // Check if this slice overlaps with another.
10230 if ((CurrentUsedBits & UsedBits) != 0)
10232 // Update the bits used globally.
10233 UsedBits |= CurrentUsedBits;
10235 // Check if the new slice would be legal.
10239 // Record the slice.
10240 LoadedSlices.push_back(LS);
10243 // Abort slicing if it does not seem to be profitable.
10244 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10249 // Rewrite each chain to use an independent load.
10250 // By construction, each chain can be represented by a unique load.
10252 // Prepare the argument for the new token factor for all the slices.
10253 SmallVector<SDValue, 8> ArgChains;
10254 for (SmallVectorImpl<LoadedSlice>::const_iterator
10255 LSIt = LoadedSlices.begin(),
10256 LSItEnd = LoadedSlices.end();
10257 LSIt != LSItEnd; ++LSIt) {
10258 SDValue SliceInst = LSIt->loadSlice();
10259 CombineTo(LSIt->Inst, SliceInst, true);
10260 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10261 SliceInst = SliceInst.getOperand(0);
10262 assert(SliceInst->getOpcode() == ISD::LOAD &&
10263 "It takes more than a zext to get to the loaded slice!!");
10264 ArgChains.push_back(SliceInst.getValue(1));
10267 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10269 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10273 /// Check to see if V is (and load (ptr), imm), where the load is having
10274 /// specific bytes cleared out. If so, return the byte size being masked out
10275 /// and the shift amount.
10276 static std::pair<unsigned, unsigned>
10277 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10278 std::pair<unsigned, unsigned> Result(0, 0);
10280 // Check for the structure we're looking for.
10281 if (V->getOpcode() != ISD::AND ||
10282 !isa<ConstantSDNode>(V->getOperand(1)) ||
10283 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10286 // Check the chain and pointer.
10287 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10288 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10290 // The store should be chained directly to the load or be an operand of a
10292 if (LD == Chain.getNode())
10294 else if (Chain->getOpcode() != ISD::TokenFactor)
10295 return Result; // Fail.
10298 for (const SDValue &ChainOp : Chain->op_values())
10299 if (ChainOp.getNode() == LD) {
10303 if (!isOk) return Result;
10306 // This only handles simple types.
10307 if (V.getValueType() != MVT::i16 &&
10308 V.getValueType() != MVT::i32 &&
10309 V.getValueType() != MVT::i64)
10312 // Check the constant mask. Invert it so that the bits being masked out are
10313 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10314 // follow the sign bit for uniformity.
10315 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10316 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10317 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10318 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10319 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10320 if (NotMaskLZ == 64) return Result; // All zero mask.
10322 // See if we have a continuous run of bits. If so, we have 0*1+0*
10323 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10326 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10327 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10328 NotMaskLZ -= 64-V.getValueSizeInBits();
10330 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10331 switch (MaskedBytes) {
10335 default: return Result; // All one mask, or 5-byte mask.
10338 // Verify that the first bit starts at a multiple of mask so that the access
10339 // is aligned the same as the access width.
10340 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10342 Result.first = MaskedBytes;
10343 Result.second = NotMaskTZ/8;
10348 /// Check to see if IVal is something that provides a value as specified by
10349 /// MaskInfo. If so, replace the specified store with a narrower store of
10350 /// truncated IVal.
10352 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10353 SDValue IVal, StoreSDNode *St,
10355 unsigned NumBytes = MaskInfo.first;
10356 unsigned ByteShift = MaskInfo.second;
10357 SelectionDAG &DAG = DC->getDAG();
10359 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10360 // that uses this. If not, this is not a replacement.
10361 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10362 ByteShift*8, (ByteShift+NumBytes)*8);
10363 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10365 // Check that it is legal on the target to do this. It is legal if the new
10366 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10368 MVT VT = MVT::getIntegerVT(NumBytes*8);
10369 if (!DC->isTypeLegal(VT))
10372 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10373 // shifted by ByteShift and truncated down to NumBytes.
10376 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10377 DAG.getConstant(ByteShift*8, DL,
10378 DC->getShiftAmountTy(IVal.getValueType())));
10381 // Figure out the offset for the store and the alignment of the access.
10383 unsigned NewAlign = St->getAlignment();
10385 if (DAG.getDataLayout().isLittleEndian())
10386 StOffset = ByteShift;
10388 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10390 SDValue Ptr = St->getBasePtr();
10393 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10394 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10395 NewAlign = MinAlign(NewAlign, StOffset);
10398 // Truncate down to the new size.
10399 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10402 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10403 St->getPointerInfo().getWithOffset(StOffset),
10404 false, false, NewAlign).getNode();
10408 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10409 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10410 /// narrowing the load and store if it would end up being a win for performance
10412 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10413 StoreSDNode *ST = cast<StoreSDNode>(N);
10414 if (ST->isVolatile())
10417 SDValue Chain = ST->getChain();
10418 SDValue Value = ST->getValue();
10419 SDValue Ptr = ST->getBasePtr();
10420 EVT VT = Value.getValueType();
10422 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10425 unsigned Opc = Value.getOpcode();
10427 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10428 // is a byte mask indicating a consecutive number of bytes, check to see if
10429 // Y is known to provide just those bytes. If so, we try to replace the
10430 // load + replace + store sequence with a single (narrower) store, which makes
10432 if (Opc == ISD::OR) {
10433 std::pair<unsigned, unsigned> MaskedLoad;
10434 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10435 if (MaskedLoad.first)
10436 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10437 Value.getOperand(1), ST,this))
10438 return SDValue(NewST, 0);
10440 // Or is commutative, so try swapping X and Y.
10441 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10442 if (MaskedLoad.first)
10443 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10444 Value.getOperand(0), ST,this))
10445 return SDValue(NewST, 0);
10448 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10449 Value.getOperand(1).getOpcode() != ISD::Constant)
10452 SDValue N0 = Value.getOperand(0);
10453 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10454 Chain == SDValue(N0.getNode(), 1)) {
10455 LoadSDNode *LD = cast<LoadSDNode>(N0);
10456 if (LD->getBasePtr() != Ptr ||
10457 LD->getPointerInfo().getAddrSpace() !=
10458 ST->getPointerInfo().getAddrSpace())
10461 // Find the type to narrow it the load / op / store to.
10462 SDValue N1 = Value.getOperand(1);
10463 unsigned BitWidth = N1.getValueSizeInBits();
10464 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10465 if (Opc == ISD::AND)
10466 Imm ^= APInt::getAllOnesValue(BitWidth);
10467 if (Imm == 0 || Imm.isAllOnesValue())
10469 unsigned ShAmt = Imm.countTrailingZeros();
10470 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10471 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10472 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10473 // The narrowing should be profitable, the load/store operation should be
10474 // legal (or custom) and the store size should be equal to the NewVT width.
10475 while (NewBW < BitWidth &&
10476 (NewVT.getStoreSizeInBits() != NewBW ||
10477 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10478 !TLI.isNarrowingProfitable(VT, NewVT))) {
10479 NewBW = NextPowerOf2(NewBW);
10480 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10482 if (NewBW >= BitWidth)
10485 // If the lsb changed does not start at the type bitwidth boundary,
10486 // start at the previous one.
10488 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10489 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10490 std::min(BitWidth, ShAmt + NewBW));
10491 if ((Imm & Mask) == Imm) {
10492 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10493 if (Opc == ISD::AND)
10494 NewImm ^= APInt::getAllOnesValue(NewBW);
10495 uint64_t PtrOff = ShAmt / 8;
10496 // For big endian targets, we need to adjust the offset to the pointer to
10497 // load the correct bytes.
10498 if (DAG.getDataLayout().isBigEndian())
10499 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10501 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10502 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10503 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10506 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10507 Ptr.getValueType(), Ptr,
10508 DAG.getConstant(PtrOff, SDLoc(LD),
10509 Ptr.getValueType()));
10510 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10511 LD->getChain(), NewPtr,
10512 LD->getPointerInfo().getWithOffset(PtrOff),
10513 LD->isVolatile(), LD->isNonTemporal(),
10514 LD->isInvariant(), NewAlign,
10516 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10517 DAG.getConstant(NewImm, SDLoc(Value),
10519 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10521 ST->getPointerInfo().getWithOffset(PtrOff),
10522 false, false, NewAlign);
10524 AddToWorklist(NewPtr.getNode());
10525 AddToWorklist(NewLD.getNode());
10526 AddToWorklist(NewVal.getNode());
10527 WorklistRemover DeadNodes(*this);
10528 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10537 /// For a given floating point load / store pair, if the load value isn't used
10538 /// by any other operations, then consider transforming the pair to integer
10539 /// load / store operations if the target deems the transformation profitable.
10540 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10541 StoreSDNode *ST = cast<StoreSDNode>(N);
10542 SDValue Chain = ST->getChain();
10543 SDValue Value = ST->getValue();
10544 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10545 Value.hasOneUse() &&
10546 Chain == SDValue(Value.getNode(), 1)) {
10547 LoadSDNode *LD = cast<LoadSDNode>(Value);
10548 EVT VT = LD->getMemoryVT();
10549 if (!VT.isFloatingPoint() ||
10550 VT != ST->getMemoryVT() ||
10551 LD->isNonTemporal() ||
10552 ST->isNonTemporal() ||
10553 LD->getPointerInfo().getAddrSpace() != 0 ||
10554 ST->getPointerInfo().getAddrSpace() != 0)
10557 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10558 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10559 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10560 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10561 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10564 unsigned LDAlign = LD->getAlignment();
10565 unsigned STAlign = ST->getAlignment();
10566 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10567 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10568 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10571 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10572 LD->getChain(), LD->getBasePtr(),
10573 LD->getPointerInfo(),
10574 false, false, false, LDAlign);
10576 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10577 NewLD, ST->getBasePtr(),
10578 ST->getPointerInfo(),
10579 false, false, STAlign);
10581 AddToWorklist(NewLD.getNode());
10582 AddToWorklist(NewST.getNode());
10583 WorklistRemover DeadNodes(*this);
10584 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10593 /// Helper struct to parse and store a memory address as base + index + offset.
10594 /// We ignore sign extensions when it is safe to do so.
10595 /// The following two expressions are not equivalent. To differentiate we need
10596 /// to store whether there was a sign extension involved in the index
10598 /// (load (i64 add (i64 copyfromreg %c)
10599 /// (i64 signextend (add (i8 load %index)
10603 /// (load (i64 add (i64 copyfromreg %c)
10604 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10606 struct BaseIndexOffset {
10610 bool IsIndexSignExt;
10612 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10614 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10615 bool IsIndexSignExt) :
10616 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10618 bool equalBaseIndex(const BaseIndexOffset &Other) {
10619 return Other.Base == Base && Other.Index == Index &&
10620 Other.IsIndexSignExt == IsIndexSignExt;
10623 /// Parses tree in Ptr for base, index, offset addresses.
10624 static BaseIndexOffset match(SDValue Ptr) {
10625 bool IsIndexSignExt = false;
10627 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10628 // instruction, then it could be just the BASE or everything else we don't
10629 // know how to handle. Just use Ptr as BASE and give up.
10630 if (Ptr->getOpcode() != ISD::ADD)
10631 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10633 // We know that we have at least an ADD instruction. Try to pattern match
10634 // the simple case of BASE + OFFSET.
10635 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10636 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10637 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10641 // Inside a loop the current BASE pointer is calculated using an ADD and a
10642 // MUL instruction. In this case Ptr is the actual BASE pointer.
10643 // (i64 add (i64 %array_ptr)
10644 // (i64 mul (i64 %induction_var)
10645 // (i64 %element_size)))
10646 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10647 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10649 // Look at Base + Index + Offset cases.
10650 SDValue Base = Ptr->getOperand(0);
10651 SDValue IndexOffset = Ptr->getOperand(1);
10653 // Skip signextends.
10654 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10655 IndexOffset = IndexOffset->getOperand(0);
10656 IsIndexSignExt = true;
10659 // Either the case of Base + Index (no offset) or something else.
10660 if (IndexOffset->getOpcode() != ISD::ADD)
10661 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10663 // Now we have the case of Base + Index + offset.
10664 SDValue Index = IndexOffset->getOperand(0);
10665 SDValue Offset = IndexOffset->getOperand(1);
10667 if (!isa<ConstantSDNode>(Offset))
10668 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10670 // Ignore signextends.
10671 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10672 Index = Index->getOperand(0);
10673 IsIndexSignExt = true;
10674 } else IsIndexSignExt = false;
10676 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10677 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10682 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10684 ArrayRef<MemOpLink> Stores,
10686 SmallVector<SDValue, 8> BuildVector;
10688 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10689 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10691 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10694 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10695 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10696 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10697 // Make sure we have something to merge.
10701 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10702 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10703 unsigned LatestNodeUsed = 0;
10705 for (unsigned i=0; i < NumElem; ++i) {
10706 // Find a chain for the new wide-store operand. Notice that some
10707 // of the store nodes that we found may not be selected for inclusion
10708 // in the wide store. The chain we use needs to be the chain of the
10709 // latest store node which is *used* and replaced by the wide store.
10710 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10711 LatestNodeUsed = i;
10714 // The latest Node in the DAG.
10715 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10716 SDLoc DL(StoreNodes[0].MemNode);
10720 // Find a legal type for the vector store.
10721 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10722 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10723 if (IsConstantSrc) {
10724 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10726 SmallVector<SDValue, 8> Ops;
10727 for (unsigned i = 0; i < NumElem ; ++i) {
10728 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10729 SDValue Val = St->getValue();
10730 // All of the operands of a BUILD_VECTOR must have the same type.
10731 if (Val.getValueType() != MemVT)
10733 Ops.push_back(Val);
10736 // Build the extracted vector elements back into a vector.
10737 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10740 // We should always use a vector store when merging extracted vector
10741 // elements, so this path implies a store of constants.
10742 assert(IsConstantSrc && "Merged vector elements should use vector store");
10744 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10745 APInt StoreInt(SizeInBits, 0);
10747 // Construct a single integer constant which is made of the smaller
10748 // constant inputs.
10749 bool IsLE = DAG.getDataLayout().isLittleEndian();
10750 for (unsigned i = 0; i < NumElem ; ++i) {
10751 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10752 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10753 SDValue Val = St->getValue();
10754 StoreInt <<= ElementSizeBytes * 8;
10755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10756 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10757 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10758 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10760 llvm_unreachable("Invalid constant element type");
10764 // Create the new Load and Store operations.
10765 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10766 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10769 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10770 FirstInChain->getBasePtr(),
10771 FirstInChain->getPointerInfo(),
10773 FirstInChain->getAlignment());
10775 // Replace the last store with the new store
10776 CombineTo(LatestOp, NewStore);
10777 // Erase all other stores.
10778 for (unsigned i = 0; i < NumElem ; ++i) {
10779 if (StoreNodes[i].MemNode == LatestOp)
10781 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10782 // ReplaceAllUsesWith will replace all uses that existed when it was
10783 // called, but graph optimizations may cause new ones to appear. For
10784 // example, the case in pr14333 looks like
10786 // St's chain -> St -> another store -> X
10788 // And the only difference from St to the other store is the chain.
10789 // When we change it's chain to be St's chain they become identical,
10790 // get CSEed and the net result is that X is now a use of St.
10791 // Since we know that St is redundant, just iterate.
10792 while (!St->use_empty())
10793 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10794 deleteAndRecombine(St);
10800 void DAGCombiner::getStoreMergeAndAliasCandidates(
10801 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10802 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10803 // This holds the base pointer, index, and the offset in bytes from the base
10805 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10807 // We must have a base and an offset.
10808 if (!BasePtr.Base.getNode())
10811 // Do not handle stores to undef base pointers.
10812 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10815 // Walk up the chain and look for nodes with offsets from the same
10816 // base pointer. Stop when reaching an instruction with a different kind
10817 // or instruction which has a different base pointer.
10818 EVT MemVT = St->getMemoryVT();
10820 StoreSDNode *Index = St;
10822 // If the chain has more than one use, then we can't reorder the mem ops.
10823 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10826 // Find the base pointer and offset for this memory node.
10827 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10829 // Check that the base pointer is the same as the original one.
10830 if (!Ptr.equalBaseIndex(BasePtr))
10833 // The memory operands must not be volatile.
10834 if (Index->isVolatile() || Index->isIndexed())
10838 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10839 if (St->isTruncatingStore())
10842 // The stored memory type must be the same.
10843 if (Index->getMemoryVT() != MemVT)
10846 // We found a potential memory operand to merge.
10847 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10849 // Find the next memory operand in the chain. If the next operand in the
10850 // chain is a store then move up and continue the scan with the next
10851 // memory operand. If the next operand is a load save it and use alias
10852 // information to check if it interferes with anything.
10853 SDNode *NextInChain = Index->getChain().getNode();
10855 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10856 // We found a store node. Use it for the next iteration.
10859 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10860 if (Ldn->isVolatile()) {
10865 // Save the load node for later. Continue the scan.
10866 AliasLoadNodes.push_back(Ldn);
10867 NextInChain = Ldn->getChain().getNode();
10877 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10878 if (OptLevel == CodeGenOpt::None)
10881 EVT MemVT = St->getMemoryVT();
10882 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10883 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10884 Attribute::NoImplicitFloat);
10886 // This function cannot currently deal with non-byte-sized memory sizes.
10887 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10890 // Don't merge vectors into wider inputs.
10891 if (MemVT.isVector() || !MemVT.isSimple())
10894 // Perform an early exit check. Do not bother looking at stored values that
10895 // are not constants, loads, or extracted vector elements.
10896 SDValue StoredVal = St->getValue();
10897 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10898 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10899 isa<ConstantFPSDNode>(StoredVal);
10900 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10902 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10905 // Only look at ends of store sequences.
10906 SDValue Chain = SDValue(St, 0);
10907 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10910 // Save the LoadSDNodes that we find in the chain.
10911 // We need to make sure that these nodes do not interfere with
10912 // any of the store nodes.
10913 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10915 // Save the StoreSDNodes that we find in the chain.
10916 SmallVector<MemOpLink, 8> StoreNodes;
10918 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10920 // Check if there is anything to merge.
10921 if (StoreNodes.size() < 2)
10924 // Sort the memory operands according to their distance from the base pointer.
10925 std::sort(StoreNodes.begin(), StoreNodes.end(),
10926 [](MemOpLink LHS, MemOpLink RHS) {
10927 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10928 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10929 LHS.SequenceNum > RHS.SequenceNum);
10932 // Scan the memory operations on the chain and find the first non-consecutive
10933 // store memory address.
10934 unsigned LastConsecutiveStore = 0;
10935 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10936 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10938 // Check that the addresses are consecutive starting from the second
10939 // element in the list of stores.
10941 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10942 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10946 bool Alias = false;
10947 // Check if this store interferes with any of the loads that we found.
10948 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10949 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10953 // We found a load that alias with this store. Stop the sequence.
10957 // Mark this node as useful.
10958 LastConsecutiveStore = i;
10961 // The node with the lowest store address.
10962 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10963 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10964 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10965 LLVMContext &Context = *DAG.getContext();
10966 const DataLayout &DL = DAG.getDataLayout();
10968 // Store the constants into memory as one consecutive store.
10969 if (IsConstantSrc) {
10970 unsigned LastLegalType = 0;
10971 unsigned LastLegalVectorType = 0;
10972 bool NonZero = false;
10973 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10974 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10975 SDValue StoredVal = St->getValue();
10977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10978 NonZero |= !C->isNullValue();
10979 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10980 NonZero |= !C->getConstantFPValue()->isNullValue();
10986 // Find a legal type for the constant store.
10987 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10988 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10989 if (TLI.isTypeLegal(StoreTy) &&
10990 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
10991 FirstStoreAlign)) {
10992 LastLegalType = i+1;
10993 // Or check whether a truncstore is legal.
10994 } else if (TLI.getTypeAction(Context, StoreTy) ==
10995 TargetLowering::TypePromoteInteger) {
10996 EVT LegalizedStoredValueTy =
10997 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
10998 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10999 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11000 FirstStoreAS, FirstStoreAlign)) {
11001 LastLegalType = i + 1;
11005 // Find a legal type for the vector store.
11006 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11007 if (TLI.isTypeLegal(Ty) &&
11008 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11009 FirstStoreAlign)) {
11010 LastLegalVectorType = i + 1;
11015 // We only use vectors if the constant is known to be zero or the target
11016 // allows it and the function is not marked with the noimplicitfloat
11019 LastLegalVectorType = 0;
11020 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
11021 LastLegalVectorType,
11023 LastLegalVectorType = 0;
11026 // Check if we found a legal integer type to store.
11027 if (LastLegalType == 0 && LastLegalVectorType == 0)
11030 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11031 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11033 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11037 // When extracting multiple vector elements, try to store them
11038 // in one vector store rather than a sequence of scalar stores.
11039 if (IsExtractVecEltSrc) {
11040 unsigned NumElem = 0;
11041 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11042 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11043 SDValue StoredVal = St->getValue();
11044 // This restriction could be loosened.
11045 // Bail out if any stored values are not elements extracted from a vector.
11046 // It should be possible to handle mixed sources, but load sources need
11047 // more careful handling (see the block of code below that handles
11048 // consecutive loads).
11049 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11052 // Find a legal type for the vector store.
11053 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11054 if (TLI.isTypeLegal(Ty) &&
11055 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11060 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11064 // Below we handle the case of multiple consecutive stores that
11065 // come from multiple consecutive loads. We merge them into a single
11066 // wide load and a single wide store.
11068 // Look for load nodes which are used by the stored values.
11069 SmallVector<MemOpLink, 8> LoadNodes;
11071 // Find acceptable loads. Loads need to have the same chain (token factor),
11072 // must not be zext, volatile, indexed, and they must be consecutive.
11073 BaseIndexOffset LdBasePtr;
11074 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11075 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11076 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11079 // Loads must only have one use.
11080 if (!Ld->hasNUsesOfValue(1, 0))
11083 // The memory operands must not be volatile.
11084 if (Ld->isVolatile() || Ld->isIndexed())
11087 // We do not accept ext loads.
11088 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11091 // The stored memory type must be the same.
11092 if (Ld->getMemoryVT() != MemVT)
11095 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11096 // If this is not the first ptr that we check.
11097 if (LdBasePtr.Base.getNode()) {
11098 // The base ptr must be the same.
11099 if (!LdPtr.equalBaseIndex(LdBasePtr))
11102 // Check that all other base pointers are the same as this one.
11106 // We found a potential memory operand to merge.
11107 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11110 if (LoadNodes.size() < 2)
11113 // If we have load/store pair instructions and we only have two values,
11115 unsigned RequiredAlignment;
11116 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11117 St->getAlignment() >= RequiredAlignment)
11120 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11121 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11122 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11124 // Scan the memory operations on the chain and find the first non-consecutive
11125 // load memory address. These variables hold the index in the store node
11127 unsigned LastConsecutiveLoad = 0;
11128 // This variable refers to the size and not index in the array.
11129 unsigned LastLegalVectorType = 0;
11130 unsigned LastLegalIntegerType = 0;
11131 StartAddress = LoadNodes[0].OffsetFromBase;
11132 SDValue FirstChain = FirstLoad->getChain();
11133 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11134 // All loads much share the same chain.
11135 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11138 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11139 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11141 LastConsecutiveLoad = i;
11143 // Find a legal type for the vector store.
11144 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11145 if (TLI.isTypeLegal(StoreTy) &&
11146 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11147 FirstStoreAlign) &&
11148 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11150 LastLegalVectorType = i + 1;
11153 // Find a legal type for the integer store.
11154 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11155 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11156 if (TLI.isTypeLegal(StoreTy) &&
11157 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11158 FirstStoreAlign) &&
11159 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11161 LastLegalIntegerType = i + 1;
11162 // Or check whether a truncstore and extload is legal.
11163 else if (TLI.getTypeAction(Context, StoreTy) ==
11164 TargetLowering::TypePromoteInteger) {
11165 EVT LegalizedStoredValueTy =
11166 TLI.getTypeToTransformTo(Context, StoreTy);
11167 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11168 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11169 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11170 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11171 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11172 FirstStoreAS, FirstStoreAlign) &&
11173 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11174 FirstLoadAS, FirstLoadAlign))
11175 LastLegalIntegerType = i+1;
11179 // Only use vector types if the vector type is larger than the integer type.
11180 // If they are the same, use integers.
11181 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11182 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11184 // We add +1 here because the LastXXX variables refer to location while
11185 // the NumElem refers to array/index size.
11186 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11187 NumElem = std::min(LastLegalType, NumElem);
11192 // The latest Node in the DAG.
11193 unsigned LatestNodeUsed = 0;
11194 for (unsigned i=1; i<NumElem; ++i) {
11195 // Find a chain for the new wide-store operand. Notice that some
11196 // of the store nodes that we found may not be selected for inclusion
11197 // in the wide store. The chain we use needs to be the chain of the
11198 // latest store node which is *used* and replaced by the wide store.
11199 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11200 LatestNodeUsed = i;
11203 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11205 // Find if it is better to use vectors or integers to load and store
11209 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11211 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11212 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11215 SDLoc LoadDL(LoadNodes[0].MemNode);
11216 SDLoc StoreDL(StoreNodes[0].MemNode);
11218 SDValue NewLoad = DAG.getLoad(
11219 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11220 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11222 SDValue NewStore = DAG.getStore(
11223 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11224 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11226 // Replace one of the loads with the new load.
11227 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11228 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11229 SDValue(NewLoad.getNode(), 1));
11231 // Remove the rest of the load chains.
11232 for (unsigned i = 1; i < NumElem ; ++i) {
11233 // Replace all chain users of the old load nodes with the chain of the new
11235 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11236 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11239 // Replace the last store with the new store.
11240 CombineTo(LatestOp, NewStore);
11241 // Erase all other stores.
11242 for (unsigned i = 0; i < NumElem ; ++i) {
11243 // Remove all Store nodes.
11244 if (StoreNodes[i].MemNode == LatestOp)
11246 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11247 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11248 deleteAndRecombine(St);
11254 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11255 StoreSDNode *ST = cast<StoreSDNode>(N);
11256 SDValue Chain = ST->getChain();
11257 SDValue Value = ST->getValue();
11258 SDValue Ptr = ST->getBasePtr();
11260 // If this is a store of a bit convert, store the input value if the
11261 // resultant store does not need a higher alignment than the original.
11262 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11263 ST->isUnindexed()) {
11264 unsigned OrigAlign = ST->getAlignment();
11265 EVT SVT = Value.getOperand(0).getValueType();
11266 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11267 SVT.getTypeForEVT(*DAG.getContext()));
11268 if (Align <= OrigAlign &&
11269 ((!LegalOperations && !ST->isVolatile()) ||
11270 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11271 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11272 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11273 ST->isNonTemporal(), OrigAlign,
11277 // Turn 'store undef, Ptr' -> nothing.
11278 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11281 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11282 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11283 // NOTE: If the original store is volatile, this transform must not increase
11284 // the number of stores. For example, on x86-32 an f64 can be stored in one
11285 // processor operation but an i64 (which is not legal) requires two. So the
11286 // transform should not be done in this case.
11287 if (Value.getOpcode() != ISD::TargetConstantFP) {
11289 switch (CFP->getSimpleValueType(0).SimpleTy) {
11290 default: llvm_unreachable("Unknown FP type");
11291 case MVT::f16: // We don't do this for these yet.
11297 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11298 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11300 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11301 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11303 return DAG.getStore(Chain, SDLoc(N), Tmp,
11304 Ptr, ST->getMemOperand());
11308 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11309 !ST->isVolatile()) ||
11310 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11312 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11313 getZExtValue(), SDLoc(CFP), MVT::i64);
11314 return DAG.getStore(Chain, SDLoc(N), Tmp,
11315 Ptr, ST->getMemOperand());
11318 if (!ST->isVolatile() &&
11319 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11320 // Many FP stores are not made apparent until after legalize, e.g. for
11321 // argument passing. Since this is so common, custom legalize the
11322 // 64-bit integer store into two 32-bit stores.
11323 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11324 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11325 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11326 if (DAG.getDataLayout().isBigEndian())
11329 unsigned Alignment = ST->getAlignment();
11330 bool isVolatile = ST->isVolatile();
11331 bool isNonTemporal = ST->isNonTemporal();
11332 AAMDNodes AAInfo = ST->getAAInfo();
11336 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11337 Ptr, ST->getPointerInfo(),
11338 isVolatile, isNonTemporal,
11339 ST->getAlignment(), AAInfo);
11340 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11341 DAG.getConstant(4, DL, Ptr.getValueType()));
11342 Alignment = MinAlign(Alignment, 4U);
11343 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11344 Ptr, ST->getPointerInfo().getWithOffset(4),
11345 isVolatile, isNonTemporal,
11346 Alignment, AAInfo);
11347 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11356 // Try to infer better alignment information than the store already has.
11357 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11358 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11359 if (Align > ST->getAlignment()) {
11361 DAG.getTruncStore(Chain, SDLoc(N), Value,
11362 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11363 ST->isVolatile(), ST->isNonTemporal(), Align,
11365 if (NewStore.getNode() != N)
11366 return CombineTo(ST, NewStore, true);
11371 // Try transforming a pair floating point load / store ops to integer
11372 // load / store ops.
11373 if (SDValue NewST = TransformFPLoadStorePair(N))
11376 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11377 : DAG.getSubtarget().useAA();
11379 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11380 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11383 if (UseAA && ST->isUnindexed()) {
11384 // Walk up chain skipping non-aliasing memory nodes.
11385 SDValue BetterChain = FindBetterChain(N, Chain);
11387 // If there is a better chain.
11388 if (Chain != BetterChain) {
11391 // Replace the chain to avoid dependency.
11392 if (ST->isTruncatingStore()) {
11393 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11394 ST->getMemoryVT(), ST->getMemOperand());
11396 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11397 ST->getMemOperand());
11400 // Create token to keep both nodes around.
11401 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11402 MVT::Other, Chain, ReplStore);
11404 // Make sure the new and old chains are cleaned up.
11405 AddToWorklist(Token.getNode());
11407 // Don't add users to work list.
11408 return CombineTo(N, Token, false);
11412 // Try transforming N to an indexed store.
11413 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11414 return SDValue(N, 0);
11416 // FIXME: is there such a thing as a truncating indexed store?
11417 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11418 Value.getValueType().isInteger()) {
11419 // See if we can simplify the input to this truncstore with knowledge that
11420 // only the low bits are being used. For example:
11421 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11423 GetDemandedBits(Value,
11424 APInt::getLowBitsSet(
11425 Value.getValueType().getScalarType().getSizeInBits(),
11426 ST->getMemoryVT().getScalarType().getSizeInBits()));
11427 AddToWorklist(Value.getNode());
11428 if (Shorter.getNode())
11429 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11430 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11432 // Otherwise, see if we can simplify the operation with
11433 // SimplifyDemandedBits, which only works if the value has a single use.
11434 if (SimplifyDemandedBits(Value,
11435 APInt::getLowBitsSet(
11436 Value.getValueType().getScalarType().getSizeInBits(),
11437 ST->getMemoryVT().getScalarType().getSizeInBits())))
11438 return SDValue(N, 0);
11441 // If this is a load followed by a store to the same location, then the store
11443 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11444 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11445 ST->isUnindexed() && !ST->isVolatile() &&
11446 // There can't be any side effects between the load and store, such as
11447 // a call or store.
11448 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11449 // The store is dead, remove it.
11454 // If this is a store followed by a store with the same value to the same
11455 // location, then the store is dead/noop.
11456 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11457 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11458 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11459 ST1->isUnindexed() && !ST1->isVolatile()) {
11460 // The store is dead, remove it.
11465 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11466 // truncating store. We can do this even if this is already a truncstore.
11467 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11468 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11469 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11470 ST->getMemoryVT())) {
11471 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11472 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11475 // Only perform this optimization before the types are legal, because we
11476 // don't want to perform this optimization on every DAGCombine invocation.
11478 bool EverChanged = false;
11481 // There can be multiple store sequences on the same chain.
11482 // Keep trying to merge store sequences until we are unable to do so
11483 // or until we merge the last store on the chain.
11484 bool Changed = MergeConsecutiveStores(ST);
11485 EverChanged |= Changed;
11486 if (!Changed) break;
11487 } while (ST->getOpcode() != ISD::DELETED_NODE);
11490 return SDValue(N, 0);
11493 return ReduceLoadOpStoreWidth(N);
11496 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11497 SDValue InVec = N->getOperand(0);
11498 SDValue InVal = N->getOperand(1);
11499 SDValue EltNo = N->getOperand(2);
11502 // If the inserted element is an UNDEF, just use the input vector.
11503 if (InVal.getOpcode() == ISD::UNDEF)
11506 EVT VT = InVec.getValueType();
11508 // If we can't generate a legal BUILD_VECTOR, exit
11509 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11512 // Check that we know which element is being inserted
11513 if (!isa<ConstantSDNode>(EltNo))
11515 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11517 // Canonicalize insert_vector_elt dag nodes.
11519 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11520 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11522 // Do this only if the child insert_vector node has one use; also
11523 // do this only if indices are both constants and Idx1 < Idx0.
11524 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11525 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11526 unsigned OtherElt =
11527 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11528 if (Elt < OtherElt) {
11530 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11531 InVec.getOperand(0), InVal, EltNo);
11532 AddToWorklist(NewOp.getNode());
11533 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11534 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11538 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11539 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11540 // vector elements.
11541 SmallVector<SDValue, 8> Ops;
11542 // Do not combine these two vectors if the output vector will not replace
11543 // the input vector.
11544 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11545 Ops.append(InVec.getNode()->op_begin(),
11546 InVec.getNode()->op_end());
11547 } else if (InVec.getOpcode() == ISD::UNDEF) {
11548 unsigned NElts = VT.getVectorNumElements();
11549 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11554 // Insert the element
11555 if (Elt < Ops.size()) {
11556 // All the operands of BUILD_VECTOR must have the same type;
11557 // we enforce that here.
11558 EVT OpVT = Ops[0].getValueType();
11559 if (InVal.getValueType() != OpVT)
11560 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11561 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11562 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11566 // Return the new vector
11567 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11570 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11571 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11572 EVT ResultVT = EVE->getValueType(0);
11573 EVT VecEltVT = InVecVT.getVectorElementType();
11574 unsigned Align = OriginalLoad->getAlignment();
11575 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11576 VecEltVT.getTypeForEVT(*DAG.getContext()));
11578 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11583 SDValue NewPtr = OriginalLoad->getBasePtr();
11585 EVT PtrType = NewPtr.getValueType();
11586 MachinePointerInfo MPI;
11588 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11589 int Elt = ConstEltNo->getZExtValue();
11590 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11591 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11592 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11594 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11595 Offset = DAG.getNode(
11596 ISD::MUL, DL, PtrType, Offset,
11597 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11598 MPI = OriginalLoad->getPointerInfo();
11600 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11602 // The replacement we need to do here is a little tricky: we need to
11603 // replace an extractelement of a load with a load.
11604 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11605 // Note that this replacement assumes that the extractvalue is the only
11606 // use of the load; that's okay because we don't want to perform this
11607 // transformation in other cases anyway.
11610 if (ResultVT.bitsGT(VecEltVT)) {
11611 // If the result type of vextract is wider than the load, then issue an
11612 // extending load instead.
11613 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11617 Load = DAG.getExtLoad(
11618 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11619 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11620 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11621 Chain = Load.getValue(1);
11623 Load = DAG.getLoad(
11624 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11625 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11626 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11627 Chain = Load.getValue(1);
11628 if (ResultVT.bitsLT(VecEltVT))
11629 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11631 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11633 WorklistRemover DeadNodes(*this);
11634 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11635 SDValue To[] = { Load, Chain };
11636 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11637 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11638 // worklist explicitly as well.
11639 AddToWorklist(Load.getNode());
11640 AddUsersToWorklist(Load.getNode()); // Add users too
11641 // Make sure to revisit this node to clean it up; it will usually be dead.
11642 AddToWorklist(EVE);
11644 return SDValue(EVE, 0);
11647 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11648 // (vextract (scalar_to_vector val, 0) -> val
11649 SDValue InVec = N->getOperand(0);
11650 EVT VT = InVec.getValueType();
11651 EVT NVT = N->getValueType(0);
11653 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11654 // Check if the result type doesn't match the inserted element type. A
11655 // SCALAR_TO_VECTOR may truncate the inserted element and the
11656 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11657 SDValue InOp = InVec.getOperand(0);
11658 if (InOp.getValueType() != NVT) {
11659 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11660 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11665 SDValue EltNo = N->getOperand(1);
11666 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11668 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11669 // We only perform this optimization before the op legalization phase because
11670 // we may introduce new vector instructions which are not backed by TD
11671 // patterns. For example on AVX, extracting elements from a wide vector
11672 // without using extract_subvector. However, if we can find an underlying
11673 // scalar value, then we can always use that.
11674 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11676 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11677 int NumElem = VT.getVectorNumElements();
11678 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11679 // Find the new index to extract from.
11680 int OrigElt = SVOp->getMaskElt(Elt);
11682 // Extracting an undef index is undef.
11684 return DAG.getUNDEF(NVT);
11686 // Select the right vector half to extract from.
11688 if (OrigElt < NumElem) {
11689 SVInVec = InVec->getOperand(0);
11691 SVInVec = InVec->getOperand(1);
11692 OrigElt -= NumElem;
11695 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11696 SDValue InOp = SVInVec.getOperand(OrigElt);
11697 if (InOp.getValueType() != NVT) {
11698 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11699 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11705 // FIXME: We should handle recursing on other vector shuffles and
11706 // scalar_to_vector here as well.
11708 if (!LegalOperations) {
11709 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11710 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11711 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11715 bool BCNumEltsChanged = false;
11716 EVT ExtVT = VT.getVectorElementType();
11719 // If the result of load has to be truncated, then it's not necessarily
11721 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11724 if (InVec.getOpcode() == ISD::BITCAST) {
11725 // Don't duplicate a load with other uses.
11726 if (!InVec.hasOneUse())
11729 EVT BCVT = InVec.getOperand(0).getValueType();
11730 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11732 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11733 BCNumEltsChanged = true;
11734 InVec = InVec.getOperand(0);
11735 ExtVT = BCVT.getVectorElementType();
11738 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11739 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11740 ISD::isNormalLoad(InVec.getNode()) &&
11741 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11742 SDValue Index = N->getOperand(1);
11743 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11744 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11748 // Perform only after legalization to ensure build_vector / vector_shuffle
11749 // optimizations have already been done.
11750 if (!LegalOperations) return SDValue();
11752 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11753 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11754 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11757 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11759 LoadSDNode *LN0 = nullptr;
11760 const ShuffleVectorSDNode *SVN = nullptr;
11761 if (ISD::isNormalLoad(InVec.getNode())) {
11762 LN0 = cast<LoadSDNode>(InVec);
11763 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11764 InVec.getOperand(0).getValueType() == ExtVT &&
11765 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11766 // Don't duplicate a load with other uses.
11767 if (!InVec.hasOneUse())
11770 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11771 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11772 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11774 // (load $addr+1*size)
11776 // Don't duplicate a load with other uses.
11777 if (!InVec.hasOneUse())
11780 // If the bit convert changed the number of elements, it is unsafe
11781 // to examine the mask.
11782 if (BCNumEltsChanged)
11785 // Select the input vector, guarding against out of range extract vector.
11786 unsigned NumElems = VT.getVectorNumElements();
11787 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11788 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11790 if (InVec.getOpcode() == ISD::BITCAST) {
11791 // Don't duplicate a load with other uses.
11792 if (!InVec.hasOneUse())
11795 InVec = InVec.getOperand(0);
11797 if (ISD::isNormalLoad(InVec.getNode())) {
11798 LN0 = cast<LoadSDNode>(InVec);
11799 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11800 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11804 // Make sure we found a non-volatile load and the extractelement is
11806 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11809 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11811 return DAG.getUNDEF(LVT);
11813 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11819 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11820 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11821 // We perform this optimization post type-legalization because
11822 // the type-legalizer often scalarizes integer-promoted vectors.
11823 // Performing this optimization before may create bit-casts which
11824 // will be type-legalized to complex code sequences.
11825 // We perform this optimization only before the operation legalizer because we
11826 // may introduce illegal operations.
11827 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11830 unsigned NumInScalars = N->getNumOperands();
11832 EVT VT = N->getValueType(0);
11834 // Check to see if this is a BUILD_VECTOR of a bunch of values
11835 // which come from any_extend or zero_extend nodes. If so, we can create
11836 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11837 // optimizations. We do not handle sign-extend because we can't fill the sign
11839 EVT SourceType = MVT::Other;
11840 bool AllAnyExt = true;
11842 for (unsigned i = 0; i != NumInScalars; ++i) {
11843 SDValue In = N->getOperand(i);
11844 // Ignore undef inputs.
11845 if (In.getOpcode() == ISD::UNDEF) continue;
11847 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11848 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11850 // Abort if the element is not an extension.
11851 if (!ZeroExt && !AnyExt) {
11852 SourceType = MVT::Other;
11856 // The input is a ZeroExt or AnyExt. Check the original type.
11857 EVT InTy = In.getOperand(0).getValueType();
11859 // Check that all of the widened source types are the same.
11860 if (SourceType == MVT::Other)
11863 else if (InTy != SourceType) {
11864 // Multiple income types. Abort.
11865 SourceType = MVT::Other;
11869 // Check if all of the extends are ANY_EXTENDs.
11870 AllAnyExt &= AnyExt;
11873 // In order to have valid types, all of the inputs must be extended from the
11874 // same source type and all of the inputs must be any or zero extend.
11875 // Scalar sizes must be a power of two.
11876 EVT OutScalarTy = VT.getScalarType();
11877 bool ValidTypes = SourceType != MVT::Other &&
11878 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11879 isPowerOf2_32(SourceType.getSizeInBits());
11881 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11882 // turn into a single shuffle instruction.
11886 bool isLE = DAG.getDataLayout().isLittleEndian();
11887 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11888 assert(ElemRatio > 1 && "Invalid element size ratio");
11889 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11890 DAG.getConstant(0, SDLoc(N), SourceType);
11892 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11893 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11895 // Populate the new build_vector
11896 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11897 SDValue Cast = N->getOperand(i);
11898 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11899 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11900 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11902 if (Cast.getOpcode() == ISD::UNDEF)
11903 In = DAG.getUNDEF(SourceType);
11905 In = Cast->getOperand(0);
11906 unsigned Index = isLE ? (i * ElemRatio) :
11907 (i * ElemRatio + (ElemRatio - 1));
11909 assert(Index < Ops.size() && "Invalid index");
11913 // The type of the new BUILD_VECTOR node.
11914 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11915 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11916 "Invalid vector size");
11917 // Check if the new vector type is legal.
11918 if (!isTypeLegal(VecVT)) return SDValue();
11920 // Make the new BUILD_VECTOR.
11921 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11923 // The new BUILD_VECTOR node has the potential to be further optimized.
11924 AddToWorklist(BV.getNode());
11925 // Bitcast to the desired type.
11926 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11929 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11930 EVT VT = N->getValueType(0);
11932 unsigned NumInScalars = N->getNumOperands();
11935 EVT SrcVT = MVT::Other;
11936 unsigned Opcode = ISD::DELETED_NODE;
11937 unsigned NumDefs = 0;
11939 for (unsigned i = 0; i != NumInScalars; ++i) {
11940 SDValue In = N->getOperand(i);
11941 unsigned Opc = In.getOpcode();
11943 if (Opc == ISD::UNDEF)
11946 // If all scalar values are floats and converted from integers.
11947 if (Opcode == ISD::DELETED_NODE &&
11948 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11955 EVT InVT = In.getOperand(0).getValueType();
11957 // If all scalar values are typed differently, bail out. It's chosen to
11958 // simplify BUILD_VECTOR of integer types.
11959 if (SrcVT == MVT::Other)
11966 // If the vector has just one element defined, it's not worth to fold it into
11967 // a vectorized one.
11971 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11972 && "Should only handle conversion from integer to float.");
11973 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11975 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11977 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11980 // Just because the floating-point vector type is legal does not necessarily
11981 // mean that the corresponding integer vector type is.
11982 if (!isTypeLegal(NVT))
11985 SmallVector<SDValue, 8> Opnds;
11986 for (unsigned i = 0; i != NumInScalars; ++i) {
11987 SDValue In = N->getOperand(i);
11989 if (In.getOpcode() == ISD::UNDEF)
11990 Opnds.push_back(DAG.getUNDEF(SrcVT));
11992 Opnds.push_back(In.getOperand(0));
11994 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11995 AddToWorklist(BV.getNode());
11997 return DAG.getNode(Opcode, dl, VT, BV);
12000 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12001 unsigned NumInScalars = N->getNumOperands();
12003 EVT VT = N->getValueType(0);
12005 // A vector built entirely of undefs is undef.
12006 if (ISD::allOperandsUndef(N))
12007 return DAG.getUNDEF(VT);
12009 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12012 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12015 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12016 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12017 // at most two distinct vectors, turn this into a shuffle node.
12019 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12020 if (!isTypeLegal(VT))
12023 // May only combine to shuffle after legalize if shuffle is legal.
12024 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12027 SDValue VecIn1, VecIn2;
12028 bool UsesZeroVector = false;
12029 for (unsigned i = 0; i != NumInScalars; ++i) {
12030 SDValue Op = N->getOperand(i);
12031 // Ignore undef inputs.
12032 if (Op.getOpcode() == ISD::UNDEF) continue;
12034 // See if we can combine this build_vector into a blend with a zero vector.
12035 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12036 UsesZeroVector = true;
12040 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12041 // constant index, bail out.
12042 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12043 !isa<ConstantSDNode>(Op.getOperand(1))) {
12044 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12048 // We allow up to two distinct input vectors.
12049 SDValue ExtractedFromVec = Op.getOperand(0);
12050 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12053 if (!VecIn1.getNode()) {
12054 VecIn1 = ExtractedFromVec;
12055 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12056 VecIn2 = ExtractedFromVec;
12058 // Too many inputs.
12059 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12064 // If everything is good, we can make a shuffle operation.
12065 if (VecIn1.getNode()) {
12066 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12067 SmallVector<int, 8> Mask;
12068 for (unsigned i = 0; i != NumInScalars; ++i) {
12069 unsigned Opcode = N->getOperand(i).getOpcode();
12070 if (Opcode == ISD::UNDEF) {
12071 Mask.push_back(-1);
12075 // Operands can also be zero.
12076 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12077 assert(UsesZeroVector &&
12078 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12079 "Unexpected node found!");
12080 Mask.push_back(NumInScalars+i);
12084 // If extracting from the first vector, just use the index directly.
12085 SDValue Extract = N->getOperand(i);
12086 SDValue ExtVal = Extract.getOperand(1);
12087 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12088 if (Extract.getOperand(0) == VecIn1) {
12089 Mask.push_back(ExtIndex);
12093 // Otherwise, use InIdx + InputVecSize
12094 Mask.push_back(InNumElements + ExtIndex);
12097 // Avoid introducing illegal shuffles with zero.
12098 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12101 // We can't generate a shuffle node with mismatched input and output types.
12102 // Attempt to transform a single input vector to the correct type.
12103 if ((VT != VecIn1.getValueType())) {
12104 // If the input vector type has a different base type to the output
12105 // vector type, bail out.
12106 EVT VTElemType = VT.getVectorElementType();
12107 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12108 (VecIn2.getNode() &&
12109 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12112 // If the input vector is too small, widen it.
12113 // We only support widening of vectors which are half the size of the
12114 // output registers. For example XMM->YMM widening on X86 with AVX.
12115 EVT VecInT = VecIn1.getValueType();
12116 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12117 // If we only have one small input, widen it by adding undef values.
12118 if (!VecIn2.getNode())
12119 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12120 DAG.getUNDEF(VecIn1.getValueType()));
12121 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12122 // If we have two small inputs of the same type, try to concat them.
12123 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12124 VecIn2 = SDValue(nullptr, 0);
12127 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12128 // If the input vector is too large, try to split it.
12129 // We don't support having two input vectors that are too large.
12130 // If the zero vector was used, we can not split the vector,
12131 // since we'd need 3 inputs.
12132 if (UsesZeroVector || VecIn2.getNode())
12135 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12138 // Try to replace VecIn1 with two extract_subvectors
12139 // No need to update the masks, they should still be correct.
12140 VecIn2 = DAG.getNode(
12141 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12142 DAG.getConstant(VT.getVectorNumElements(), dl,
12143 TLI.getVectorIdxTy(DAG.getDataLayout())));
12144 VecIn1 = DAG.getNode(
12145 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12146 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12151 if (UsesZeroVector)
12152 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12153 DAG.getConstantFP(0.0, dl, VT);
12155 // If VecIn2 is unused then change it to undef.
12156 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12158 // Check that we were able to transform all incoming values to the same
12160 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12161 VecIn1.getValueType() != VT)
12164 // Return the new VECTOR_SHUFFLE node.
12168 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12174 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12175 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12176 EVT OpVT = N->getOperand(0).getValueType();
12178 // If the operands are legal vectors, leave them alone.
12179 if (TLI.isTypeLegal(OpVT))
12183 EVT VT = N->getValueType(0);
12184 SmallVector<SDValue, 8> Ops;
12186 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12187 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12189 // Keep track of what we encounter.
12190 bool AnyInteger = false;
12191 bool AnyFP = false;
12192 for (const SDValue &Op : N->ops()) {
12193 if (ISD::BITCAST == Op.getOpcode() &&
12194 !Op.getOperand(0).getValueType().isVector())
12195 Ops.push_back(Op.getOperand(0));
12196 else if (ISD::UNDEF == Op.getOpcode())
12197 Ops.push_back(ScalarUndef);
12201 // Note whether we encounter an integer or floating point scalar.
12202 // If it's neither, bail out, it could be something weird like x86mmx.
12203 EVT LastOpVT = Ops.back().getValueType();
12204 if (LastOpVT.isFloatingPoint())
12206 else if (LastOpVT.isInteger())
12212 // If any of the operands is a floating point scalar bitcast to a vector,
12213 // use floating point types throughout, and bitcast everything.
12214 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12216 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12217 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12219 for (SDValue &Op : Ops) {
12220 if (Op.getValueType() == SVT)
12222 if (Op.getOpcode() == ISD::UNDEF)
12225 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12230 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12231 VT.getSizeInBits() / SVT.getSizeInBits());
12232 return DAG.getNode(ISD::BITCAST, DL, VT,
12233 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12236 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12237 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12238 // most two distinct vectors the same size as the result, attempt to turn this
12239 // into a legal shuffle.
12240 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12241 EVT VT = N->getValueType(0);
12242 EVT OpVT = N->getOperand(0).getValueType();
12243 int NumElts = VT.getVectorNumElements();
12244 int NumOpElts = OpVT.getVectorNumElements();
12246 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12247 SmallVector<int, 8> Mask;
12249 for (SDValue Op : N->ops()) {
12250 // Peek through any bitcast.
12251 while (Op.getOpcode() == ISD::BITCAST)
12252 Op = Op.getOperand(0);
12254 // UNDEF nodes convert to UNDEF shuffle mask values.
12255 if (Op.getOpcode() == ISD::UNDEF) {
12256 Mask.append((unsigned)NumOpElts, -1);
12260 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12263 // What vector are we extracting the subvector from and at what index?
12264 SDValue ExtVec = Op.getOperand(0);
12265 if (ExtVec.getOpcode() == ISD::UNDEF) {
12266 Mask.append((unsigned)NumOpElts, -1);
12270 EVT ExtVT = ExtVec.getValueType();
12271 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12273 int ExtIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12275 // Ensure that we are extracting a subvector from a vector the same
12276 // size as the result.
12277 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12280 // Scale the subvector index to account for any bitcast.
12281 int NumExtElts = ExtVT.getVectorNumElements();
12282 if (0 == (NumExtElts % NumElts))
12283 ExtIdx /= (NumExtElts / NumElts);
12284 else if (0 == (NumElts % NumExtElts))
12285 ExtIdx *= (NumElts / NumExtElts);
12289 // At most we can reference 2 inputs in the final shuffle.
12290 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12292 for (int i = 0; i != NumOpElts; ++i)
12293 Mask.push_back(i + ExtIdx);
12294 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12296 for (int i = 0; i != NumOpElts; ++i)
12297 Mask.push_back(i + ExtIdx + NumElts);
12303 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12306 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12307 DAG.getBitcast(VT, SV1), Mask);
12310 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12311 // If we only have one input vector, we don't need to do any concatenation.
12312 if (N->getNumOperands() == 1)
12313 return N->getOperand(0);
12315 // Check if all of the operands are undefs.
12316 EVT VT = N->getValueType(0);
12317 if (ISD::allOperandsUndef(N))
12318 return DAG.getUNDEF(VT);
12320 // Optimize concat_vectors where all but the first of the vectors are undef.
12321 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12322 return Op.getOpcode() == ISD::UNDEF;
12324 SDValue In = N->getOperand(0);
12325 assert(In.getValueType().isVector() && "Must concat vectors");
12327 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12328 if (In->getOpcode() == ISD::BITCAST &&
12329 !In->getOperand(0)->getValueType(0).isVector()) {
12330 SDValue Scalar = In->getOperand(0);
12332 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12333 // look through the trunc so we can still do the transform:
12334 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12335 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12336 !TLI.isTypeLegal(Scalar.getValueType()) &&
12337 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12338 Scalar = Scalar->getOperand(0);
12340 EVT SclTy = Scalar->getValueType(0);
12342 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12345 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12346 VT.getSizeInBits() / SclTy.getSizeInBits());
12347 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12350 SDLoc dl = SDLoc(N);
12351 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12352 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12356 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12357 // We have already tested above for an UNDEF only concatenation.
12358 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12359 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12360 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12361 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12363 bool AllBuildVectorsOrUndefs =
12364 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12365 if (AllBuildVectorsOrUndefs) {
12366 SmallVector<SDValue, 8> Opnds;
12367 EVT SVT = VT.getScalarType();
12370 if (!SVT.isFloatingPoint()) {
12371 // If BUILD_VECTOR are from built from integer, they may have different
12372 // operand types. Get the smallest type and truncate all operands to it.
12373 bool FoundMinVT = false;
12374 for (const SDValue &Op : N->ops())
12375 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12376 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12377 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12380 assert(FoundMinVT && "Concat vector type mismatch");
12383 for (const SDValue &Op : N->ops()) {
12384 EVT OpVT = Op.getValueType();
12385 unsigned NumElts = OpVT.getVectorNumElements();
12387 if (ISD::UNDEF == Op.getOpcode())
12388 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12390 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12391 if (SVT.isFloatingPoint()) {
12392 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12393 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12395 for (unsigned i = 0; i != NumElts; ++i)
12397 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12402 assert(VT.getVectorNumElements() == Opnds.size() &&
12403 "Concat vector type mismatch");
12404 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12407 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12408 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12411 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12412 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12413 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12416 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12417 // nodes often generate nop CONCAT_VECTOR nodes.
12418 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12419 // place the incoming vectors at the exact same location.
12420 SDValue SingleSource = SDValue();
12421 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12423 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12424 SDValue Op = N->getOperand(i);
12426 if (Op.getOpcode() == ISD::UNDEF)
12429 // Check if this is the identity extract:
12430 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12433 // Find the single incoming vector for the extract_subvector.
12434 if (SingleSource.getNode()) {
12435 if (Op.getOperand(0) != SingleSource)
12438 SingleSource = Op.getOperand(0);
12440 // Check the source type is the same as the type of the result.
12441 // If not, this concat may extend the vector, so we can not
12442 // optimize it away.
12443 if (SingleSource.getValueType() != N->getValueType(0))
12447 unsigned IdentityIndex = i * PartNumElem;
12448 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12449 // The extract index must be constant.
12453 // Check that we are reading from the identity index.
12454 if (CS->getZExtValue() != IdentityIndex)
12458 if (SingleSource.getNode())
12459 return SingleSource;
12464 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12465 EVT NVT = N->getValueType(0);
12466 SDValue V = N->getOperand(0);
12468 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12470 // (extract_subvec (concat V1, V2, ...), i)
12473 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12475 if (V->getOperand(0).getValueType() != NVT)
12477 unsigned Idx = N->getConstantOperandVal(1);
12478 unsigned NumElems = NVT.getVectorNumElements();
12479 assert((Idx % NumElems) == 0 &&
12480 "IDX in concat is not a multiple of the result vector length.");
12481 return V->getOperand(Idx / NumElems);
12485 if (V->getOpcode() == ISD::BITCAST)
12486 V = V.getOperand(0);
12488 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12490 // Handle only simple case where vector being inserted and vector
12491 // being extracted are of same type, and are half size of larger vectors.
12492 EVT BigVT = V->getOperand(0).getValueType();
12493 EVT SmallVT = V->getOperand(1).getValueType();
12494 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12497 // Only handle cases where both indexes are constants with the same type.
12498 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12499 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12501 if (InsIdx && ExtIdx &&
12502 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12503 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12505 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12507 // indices are equal or bit offsets are equal => V1
12508 // otherwise => (extract_subvec V1, ExtIdx)
12509 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12510 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12511 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12512 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12513 DAG.getNode(ISD::BITCAST, dl,
12514 N->getOperand(0).getValueType(),
12515 V->getOperand(0)), N->getOperand(1));
12522 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12523 SDValue V, SelectionDAG &DAG) {
12525 EVT VT = V.getValueType();
12527 switch (V.getOpcode()) {
12531 case ISD::CONCAT_VECTORS: {
12532 EVT OpVT = V->getOperand(0).getValueType();
12533 int OpSize = OpVT.getVectorNumElements();
12534 SmallBitVector OpUsedElements(OpSize, false);
12535 bool FoundSimplification = false;
12536 SmallVector<SDValue, 4> NewOps;
12537 NewOps.reserve(V->getNumOperands());
12538 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12539 SDValue Op = V->getOperand(i);
12540 bool OpUsed = false;
12541 for (int j = 0; j < OpSize; ++j)
12542 if (UsedElements[i * OpSize + j]) {
12543 OpUsedElements[j] = true;
12547 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12548 : DAG.getUNDEF(OpVT));
12549 FoundSimplification |= Op == NewOps.back();
12550 OpUsedElements.reset();
12552 if (FoundSimplification)
12553 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12557 case ISD::INSERT_SUBVECTOR: {
12558 SDValue BaseV = V->getOperand(0);
12559 SDValue SubV = V->getOperand(1);
12560 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12564 int SubSize = SubV.getValueType().getVectorNumElements();
12565 int Idx = IdxN->getZExtValue();
12566 bool SubVectorUsed = false;
12567 SmallBitVector SubUsedElements(SubSize, false);
12568 for (int i = 0; i < SubSize; ++i)
12569 if (UsedElements[i + Idx]) {
12570 SubVectorUsed = true;
12571 SubUsedElements[i] = true;
12572 UsedElements[i + Idx] = false;
12575 // Now recurse on both the base and sub vectors.
12576 SDValue SimplifiedSubV =
12578 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12579 : DAG.getUNDEF(SubV.getValueType());
12580 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12581 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12582 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12583 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12589 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12590 SDValue N1, SelectionDAG &DAG) {
12591 EVT VT = SVN->getValueType(0);
12592 int NumElts = VT.getVectorNumElements();
12593 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12594 for (int M : SVN->getMask())
12595 if (M >= 0 && M < NumElts)
12596 N0UsedElements[M] = true;
12597 else if (M >= NumElts)
12598 N1UsedElements[M - NumElts] = true;
12600 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12601 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12602 if (S0 == N0 && S1 == N1)
12605 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12608 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12609 // or turn a shuffle of a single concat into simpler shuffle then concat.
12610 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12611 EVT VT = N->getValueType(0);
12612 unsigned NumElts = VT.getVectorNumElements();
12614 SDValue N0 = N->getOperand(0);
12615 SDValue N1 = N->getOperand(1);
12616 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12618 SmallVector<SDValue, 4> Ops;
12619 EVT ConcatVT = N0.getOperand(0).getValueType();
12620 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12621 unsigned NumConcats = NumElts / NumElemsPerConcat;
12623 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12624 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12625 // half vector elements.
12626 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12627 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12628 SVN->getMask().end(), [](int i) { return i == -1; })) {
12629 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12630 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12631 N1 = DAG.getUNDEF(ConcatVT);
12632 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12635 // Look at every vector that's inserted. We're looking for exact
12636 // subvector-sized copies from a concatenated vector
12637 for (unsigned I = 0; I != NumConcats; ++I) {
12638 // Make sure we're dealing with a copy.
12639 unsigned Begin = I * NumElemsPerConcat;
12640 bool AllUndef = true, NoUndef = true;
12641 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12642 if (SVN->getMaskElt(J) >= 0)
12649 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12652 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12653 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12656 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12657 if (FirstElt < N0.getNumOperands())
12658 Ops.push_back(N0.getOperand(FirstElt));
12660 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12662 } else if (AllUndef) {
12663 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12664 } else { // Mixed with general masks and undefs, can't do optimization.
12669 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12672 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12673 EVT VT = N->getValueType(0);
12674 unsigned NumElts = VT.getVectorNumElements();
12676 SDValue N0 = N->getOperand(0);
12677 SDValue N1 = N->getOperand(1);
12679 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12681 // Canonicalize shuffle undef, undef -> undef
12682 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12683 return DAG.getUNDEF(VT);
12685 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12687 // Canonicalize shuffle v, v -> v, undef
12689 SmallVector<int, 8> NewMask;
12690 for (unsigned i = 0; i != NumElts; ++i) {
12691 int Idx = SVN->getMaskElt(i);
12692 if (Idx >= (int)NumElts) Idx -= NumElts;
12693 NewMask.push_back(Idx);
12695 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12699 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12700 if (N0.getOpcode() == ISD::UNDEF) {
12701 SmallVector<int, 8> NewMask;
12702 for (unsigned i = 0; i != NumElts; ++i) {
12703 int Idx = SVN->getMaskElt(i);
12705 if (Idx >= (int)NumElts)
12708 Idx = -1; // remove reference to lhs
12710 NewMask.push_back(Idx);
12712 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12716 // Remove references to rhs if it is undef
12717 if (N1.getOpcode() == ISD::UNDEF) {
12718 bool Changed = false;
12719 SmallVector<int, 8> NewMask;
12720 for (unsigned i = 0; i != NumElts; ++i) {
12721 int Idx = SVN->getMaskElt(i);
12722 if (Idx >= (int)NumElts) {
12726 NewMask.push_back(Idx);
12729 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12732 // If it is a splat, check if the argument vector is another splat or a
12734 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12735 SDNode *V = N0.getNode();
12737 // If this is a bit convert that changes the element type of the vector but
12738 // not the number of vector elements, look through it. Be careful not to
12739 // look though conversions that change things like v4f32 to v2f64.
12740 if (V->getOpcode() == ISD::BITCAST) {
12741 SDValue ConvInput = V->getOperand(0);
12742 if (ConvInput.getValueType().isVector() &&
12743 ConvInput.getValueType().getVectorNumElements() == NumElts)
12744 V = ConvInput.getNode();
12747 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12748 assert(V->getNumOperands() == NumElts &&
12749 "BUILD_VECTOR has wrong number of operands");
12751 bool AllSame = true;
12752 for (unsigned i = 0; i != NumElts; ++i) {
12753 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12754 Base = V->getOperand(i);
12758 // Splat of <u, u, u, u>, return <u, u, u, u>
12759 if (!Base.getNode())
12761 for (unsigned i = 0; i != NumElts; ++i) {
12762 if (V->getOperand(i) != Base) {
12767 // Splat of <x, x, x, x>, return <x, x, x, x>
12771 // Canonicalize any other splat as a build_vector.
12772 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12773 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12774 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12775 V->getValueType(0), Ops);
12777 // We may have jumped through bitcasts, so the type of the
12778 // BUILD_VECTOR may not match the type of the shuffle.
12779 if (V->getValueType(0) != VT)
12780 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12785 // There are various patterns used to build up a vector from smaller vectors,
12786 // subvectors, or elements. Scan chains of these and replace unused insertions
12787 // or components with undef.
12788 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12791 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12792 Level < AfterLegalizeVectorOps &&
12793 (N1.getOpcode() == ISD::UNDEF ||
12794 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12795 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12796 SDValue V = partitionShuffleOfConcats(N, DAG);
12802 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12803 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12804 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12805 SmallVector<SDValue, 8> Ops;
12806 for (int M : SVN->getMask()) {
12807 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12809 int Idx = M % NumElts;
12810 SDValue &S = (M < (int)NumElts ? N0 : N1);
12811 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12812 Op = S.getOperand(Idx);
12813 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12815 Op = S.getOperand(0);
12817 // Operand can't be combined - bail out.
12823 if (Ops.size() == VT.getVectorNumElements()) {
12824 // BUILD_VECTOR requires all inputs to be of the same type, find the
12825 // maximum type and extend them all.
12826 EVT SVT = VT.getScalarType();
12827 if (SVT.isInteger())
12828 for (SDValue &Op : Ops)
12829 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12830 if (SVT != VT.getScalarType())
12831 for (SDValue &Op : Ops)
12832 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12833 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12834 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12835 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12839 // If this shuffle only has a single input that is a bitcasted shuffle,
12840 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12841 // back to their original types.
12842 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12843 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12844 TLI.isTypeLegal(VT)) {
12846 // Peek through the bitcast only if there is one user.
12848 while (BC0.getOpcode() == ISD::BITCAST) {
12849 if (!BC0.hasOneUse())
12851 BC0 = BC0.getOperand(0);
12854 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12856 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12858 SmallVector<int, 8> NewMask;
12860 for (int s = 0; s != Scale; ++s)
12861 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12865 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12866 EVT SVT = VT.getScalarType();
12867 EVT InnerVT = BC0->getValueType(0);
12868 EVT InnerSVT = InnerVT.getScalarType();
12870 // Determine which shuffle works with the smaller scalar type.
12871 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12872 EVT ScaleSVT = ScaleVT.getScalarType();
12874 if (TLI.isTypeLegal(ScaleVT) &&
12875 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12876 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12878 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12879 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12881 // Scale the shuffle masks to the smaller scalar type.
12882 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12883 SmallVector<int, 8> InnerMask =
12884 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12885 SmallVector<int, 8> OuterMask =
12886 ScaleShuffleMask(SVN->getMask(), OuterScale);
12888 // Merge the shuffle masks.
12889 SmallVector<int, 8> NewMask;
12890 for (int M : OuterMask)
12891 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12893 // Test for shuffle mask legality over both commutations.
12894 SDValue SV0 = BC0->getOperand(0);
12895 SDValue SV1 = BC0->getOperand(1);
12896 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12898 std::swap(SV0, SV1);
12899 ShuffleVectorSDNode::commuteMask(NewMask);
12900 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12904 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12905 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12906 return DAG.getNode(
12907 ISD::BITCAST, SDLoc(N), VT,
12908 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12914 // Canonicalize shuffles according to rules:
12915 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12916 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12917 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12918 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12919 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12920 TLI.isTypeLegal(VT)) {
12921 // The incoming shuffle must be of the same type as the result of the
12922 // current shuffle.
12923 assert(N1->getOperand(0).getValueType() == VT &&
12924 "Shuffle types don't match");
12926 SDValue SV0 = N1->getOperand(0);
12927 SDValue SV1 = N1->getOperand(1);
12928 bool HasSameOp0 = N0 == SV0;
12929 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12930 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12931 // Commute the operands of this shuffle so that next rule
12933 return DAG.getCommutedVectorShuffle(*SVN);
12936 // Try to fold according to rules:
12937 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12938 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12939 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12940 // Don't try to fold shuffles with illegal type.
12941 // Only fold if this shuffle is the only user of the other shuffle.
12942 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12943 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12944 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12946 // The incoming shuffle must be of the same type as the result of the
12947 // current shuffle.
12948 assert(OtherSV->getOperand(0).getValueType() == VT &&
12949 "Shuffle types don't match");
12952 SmallVector<int, 4> Mask;
12953 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12954 // operand, and SV1 as the second operand.
12955 for (unsigned i = 0; i != NumElts; ++i) {
12956 int Idx = SVN->getMaskElt(i);
12958 // Propagate Undef.
12959 Mask.push_back(Idx);
12963 SDValue CurrentVec;
12964 if (Idx < (int)NumElts) {
12965 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12966 // shuffle mask to identify which vector is actually referenced.
12967 Idx = OtherSV->getMaskElt(Idx);
12969 // Propagate Undef.
12970 Mask.push_back(Idx);
12974 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12975 : OtherSV->getOperand(1);
12977 // This shuffle index references an element within N1.
12981 // Simple case where 'CurrentVec' is UNDEF.
12982 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12983 Mask.push_back(-1);
12987 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12988 // will be the first or second operand of the combined shuffle.
12989 Idx = Idx % NumElts;
12990 if (!SV0.getNode() || SV0 == CurrentVec) {
12991 // Ok. CurrentVec is the left hand side.
12992 // Update the mask accordingly.
12994 Mask.push_back(Idx);
12998 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12999 if (SV1.getNode() && SV1 != CurrentVec)
13002 // Ok. CurrentVec is the right hand side.
13003 // Update the mask accordingly.
13005 Mask.push_back(Idx + NumElts);
13008 // Check if all indices in Mask are Undef. In case, propagate Undef.
13009 bool isUndefMask = true;
13010 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13011 isUndefMask &= Mask[i] < 0;
13014 return DAG.getUNDEF(VT);
13016 if (!SV0.getNode())
13017 SV0 = DAG.getUNDEF(VT);
13018 if (!SV1.getNode())
13019 SV1 = DAG.getUNDEF(VT);
13021 // Avoid introducing shuffles with illegal mask.
13022 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13023 ShuffleVectorSDNode::commuteMask(Mask);
13025 if (!TLI.isShuffleMaskLegal(Mask, VT))
13028 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13029 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13030 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13031 std::swap(SV0, SV1);
13034 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13035 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13036 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13037 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13043 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13044 SDValue InVal = N->getOperand(0);
13045 EVT VT = N->getValueType(0);
13047 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13048 // with a VECTOR_SHUFFLE.
13049 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13050 SDValue InVec = InVal->getOperand(0);
13051 SDValue EltNo = InVal->getOperand(1);
13053 // FIXME: We could support implicit truncation if the shuffle can be
13054 // scaled to a smaller vector scalar type.
13055 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13056 if (C0 && VT == InVec.getValueType() &&
13057 VT.getScalarType() == InVal.getValueType()) {
13058 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13059 int Elt = C0->getZExtValue();
13062 if (TLI.isShuffleMaskLegal(NewMask, VT))
13063 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13071 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13072 SDValue N0 = N->getOperand(0);
13073 SDValue N2 = N->getOperand(2);
13075 // If the input vector is a concatenation, and the insert replaces
13076 // one of the halves, we can optimize into a single concat_vectors.
13077 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13078 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13079 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13080 EVT VT = N->getValueType(0);
13082 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13083 // (concat_vectors Z, Y)
13085 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13086 N->getOperand(1), N0.getOperand(1));
13088 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13089 // (concat_vectors X, Z)
13090 if (InsIdx == VT.getVectorNumElements()/2)
13091 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13092 N0.getOperand(0), N->getOperand(1));
13098 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13099 SDValue N0 = N->getOperand(0);
13101 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13102 if (N0->getOpcode() == ISD::FP16_TO_FP)
13103 return N0->getOperand(0);
13108 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13109 /// with the destination vector and a zero vector.
13110 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13111 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13112 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13113 EVT VT = N->getValueType(0);
13114 SDValue LHS = N->getOperand(0);
13115 SDValue RHS = N->getOperand(1);
13118 // Make sure we're not running after operation legalization where it
13119 // may have custom lowered the vector shuffles.
13120 if (LegalOperations)
13123 if (N->getOpcode() != ISD::AND)
13126 if (RHS.getOpcode() == ISD::BITCAST)
13127 RHS = RHS.getOperand(0);
13129 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13132 EVT RVT = RHS.getValueType();
13133 unsigned NumElts = RHS.getNumOperands();
13135 // Attempt to create a valid clear mask, splitting the mask into
13136 // sub elements and checking to see if each is
13137 // all zeros or all ones - suitable for shuffle masking.
13138 auto BuildClearMask = [&](int Split) {
13139 int NumSubElts = NumElts * Split;
13140 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13142 SmallVector<int, 8> Indices;
13143 for (int i = 0; i != NumSubElts; ++i) {
13144 int EltIdx = i / Split;
13145 int SubIdx = i % Split;
13146 SDValue Elt = RHS.getOperand(EltIdx);
13147 if (Elt.getOpcode() == ISD::UNDEF) {
13148 Indices.push_back(-1);
13153 if (isa<ConstantSDNode>(Elt))
13154 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13155 else if (isa<ConstantFPSDNode>(Elt))
13156 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13160 // Extract the sub element from the constant bit mask.
13161 if (DAG.getDataLayout().isBigEndian()) {
13162 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13164 Bits = Bits.lshr(SubIdx * NumSubBits);
13168 Bits = Bits.trunc(NumSubBits);
13170 if (Bits.isAllOnesValue())
13171 Indices.push_back(i);
13172 else if (Bits == 0)
13173 Indices.push_back(i + NumSubElts);
13178 // Let's see if the target supports this vector_shuffle.
13179 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13180 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13181 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13184 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13185 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13186 DAG.getBitcast(ClearVT, LHS),
13187 Zero, &Indices[0]));
13190 // Determine maximum split level (byte level masking).
13192 if (RVT.getScalarSizeInBits() % 8 == 0)
13193 MaxSplit = RVT.getScalarSizeInBits() / 8;
13195 for (int Split = 1; Split <= MaxSplit; ++Split)
13196 if (RVT.getScalarSizeInBits() % Split == 0)
13197 if (SDValue S = BuildClearMask(Split))
13203 /// Visit a binary vector operation, like ADD.
13204 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13205 assert(N->getValueType(0).isVector() &&
13206 "SimplifyVBinOp only works on vectors!");
13208 SDValue LHS = N->getOperand(0);
13209 SDValue RHS = N->getOperand(1);
13211 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13213 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13214 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13215 // Check if both vectors are constants. If not bail out.
13216 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13217 cast<BuildVectorSDNode>(RHS)->isConstant()))
13220 SmallVector<SDValue, 8> Ops;
13221 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13222 SDValue LHSOp = LHS.getOperand(i);
13223 SDValue RHSOp = RHS.getOperand(i);
13225 // Can't fold divide by zero.
13226 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13227 N->getOpcode() == ISD::FDIV) {
13228 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13229 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13233 EVT VT = LHSOp.getValueType();
13234 EVT RVT = RHSOp.getValueType();
13236 // Integer BUILD_VECTOR operands may have types larger than the element
13237 // size (e.g., when the element type is not legal). Prior to type
13238 // legalization, the types may not match between the two BUILD_VECTORS.
13239 // Truncate one of the operands to make them match.
13240 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13241 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13243 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13247 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13249 if (FoldOp.getOpcode() != ISD::UNDEF &&
13250 FoldOp.getOpcode() != ISD::Constant &&
13251 FoldOp.getOpcode() != ISD::ConstantFP)
13253 Ops.push_back(FoldOp);
13254 AddToWorklist(FoldOp.getNode());
13257 if (Ops.size() == LHS.getNumOperands())
13258 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13261 // Try to convert a constant mask AND into a shuffle clear mask.
13262 if (SDValue Shuffle = XformToShuffleWithZero(N))
13265 // Type legalization might introduce new shuffles in the DAG.
13266 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13267 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13268 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13269 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13270 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13271 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13272 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13273 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13275 if (SVN0->getMask().equals(SVN1->getMask())) {
13276 EVT VT = N->getValueType(0);
13277 SDValue UndefVector = LHS.getOperand(1);
13278 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13279 LHS.getOperand(0), RHS.getOperand(0));
13280 AddUsersToWorklist(N);
13281 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13282 &SVN0->getMask()[0]);
13289 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13290 SDValue N1, SDValue N2){
13291 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13293 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13294 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13296 // If we got a simplified select_cc node back from SimplifySelectCC, then
13297 // break it down into a new SETCC node, and a new SELECT node, and then return
13298 // the SELECT node, since we were called with a SELECT node.
13299 if (SCC.getNode()) {
13300 // Check to see if we got a select_cc back (to turn into setcc/select).
13301 // Otherwise, just return whatever node we got back, like fabs.
13302 if (SCC.getOpcode() == ISD::SELECT_CC) {
13303 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13305 SCC.getOperand(0), SCC.getOperand(1),
13306 SCC.getOperand(4));
13307 AddToWorklist(SETCC.getNode());
13308 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13309 SCC.getOperand(2), SCC.getOperand(3));
13317 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13318 /// being selected between, see if we can simplify the select. Callers of this
13319 /// should assume that TheSelect is deleted if this returns true. As such, they
13320 /// should return the appropriate thing (e.g. the node) back to the top-level of
13321 /// the DAG combiner loop to avoid it being looked at.
13322 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13325 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13326 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13327 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13328 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13329 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13330 SDValue Sqrt = RHS;
13333 const ConstantFPSDNode *NegZero = nullptr;
13335 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13336 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13337 CmpLHS = TheSelect->getOperand(0);
13338 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13340 // SELECT or VSELECT
13341 SDValue Cmp = TheSelect->getOperand(0);
13342 if (Cmp.getOpcode() == ISD::SETCC) {
13343 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13344 CmpLHS = Cmp.getOperand(0);
13345 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13348 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13349 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13350 CC == ISD::SETULT || CC == ISD::SETLT)) {
13351 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13352 CombineTo(TheSelect, Sqrt);
13357 // Cannot simplify select with vector condition
13358 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13360 // If this is a select from two identical things, try to pull the operation
13361 // through the select.
13362 if (LHS.getOpcode() != RHS.getOpcode() ||
13363 !LHS.hasOneUse() || !RHS.hasOneUse())
13366 // If this is a load and the token chain is identical, replace the select
13367 // of two loads with a load through a select of the address to load from.
13368 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13369 // constants have been dropped into the constant pool.
13370 if (LHS.getOpcode() == ISD::LOAD) {
13371 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13372 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13374 // Token chains must be identical.
13375 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13376 // Do not let this transformation reduce the number of volatile loads.
13377 LLD->isVolatile() || RLD->isVolatile() ||
13378 // FIXME: If either is a pre/post inc/dec load,
13379 // we'd need to split out the address adjustment.
13380 LLD->isIndexed() || RLD->isIndexed() ||
13381 // If this is an EXTLOAD, the VT's must match.
13382 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13383 // If this is an EXTLOAD, the kind of extension must match.
13384 (LLD->getExtensionType() != RLD->getExtensionType() &&
13385 // The only exception is if one of the extensions is anyext.
13386 LLD->getExtensionType() != ISD::EXTLOAD &&
13387 RLD->getExtensionType() != ISD::EXTLOAD) ||
13388 // FIXME: this discards src value information. This is
13389 // over-conservative. It would be beneficial to be able to remember
13390 // both potential memory locations. Since we are discarding
13391 // src value info, don't do the transformation if the memory
13392 // locations are not in the default address space.
13393 LLD->getPointerInfo().getAddrSpace() != 0 ||
13394 RLD->getPointerInfo().getAddrSpace() != 0 ||
13395 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13396 LLD->getBasePtr().getValueType()))
13399 // Check that the select condition doesn't reach either load. If so,
13400 // folding this will induce a cycle into the DAG. If not, this is safe to
13401 // xform, so create a select of the addresses.
13403 if (TheSelect->getOpcode() == ISD::SELECT) {
13404 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13405 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13406 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13408 // The loads must not depend on one another.
13409 if (LLD->isPredecessorOf(RLD) ||
13410 RLD->isPredecessorOf(LLD))
13412 Addr = DAG.getSelect(SDLoc(TheSelect),
13413 LLD->getBasePtr().getValueType(),
13414 TheSelect->getOperand(0), LLD->getBasePtr(),
13415 RLD->getBasePtr());
13416 } else { // Otherwise SELECT_CC
13417 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13418 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13420 if ((LLD->hasAnyUseOfValue(1) &&
13421 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13422 (RLD->hasAnyUseOfValue(1) &&
13423 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13426 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13427 LLD->getBasePtr().getValueType(),
13428 TheSelect->getOperand(0),
13429 TheSelect->getOperand(1),
13430 LLD->getBasePtr(), RLD->getBasePtr(),
13431 TheSelect->getOperand(4));
13435 // It is safe to replace the two loads if they have different alignments,
13436 // but the new load must be the minimum (most restrictive) alignment of the
13438 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13439 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13440 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13441 Load = DAG.getLoad(TheSelect->getValueType(0),
13443 // FIXME: Discards pointer and AA info.
13444 LLD->getChain(), Addr, MachinePointerInfo(),
13445 LLD->isVolatile(), LLD->isNonTemporal(),
13446 isInvariant, Alignment);
13448 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13449 RLD->getExtensionType() : LLD->getExtensionType(),
13451 TheSelect->getValueType(0),
13452 // FIXME: Discards pointer and AA info.
13453 LLD->getChain(), Addr, MachinePointerInfo(),
13454 LLD->getMemoryVT(), LLD->isVolatile(),
13455 LLD->isNonTemporal(), isInvariant, Alignment);
13458 // Users of the select now use the result of the load.
13459 CombineTo(TheSelect, Load);
13461 // Users of the old loads now use the new load's chain. We know the
13462 // old-load value is dead now.
13463 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13464 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13471 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13472 /// where 'cond' is the comparison specified by CC.
13473 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13474 SDValue N2, SDValue N3,
13475 ISD::CondCode CC, bool NotExtCompare) {
13476 // (x ? y : y) -> y.
13477 if (N2 == N3) return N2;
13479 EVT VT = N2.getValueType();
13480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13481 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13483 // Determine if the condition we're dealing with is constant
13484 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13485 N0, N1, CC, DL, false);
13486 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13488 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13489 // fold select_cc true, x, y -> x
13490 // fold select_cc false, x, y -> y
13491 return !SCCC->isNullValue() ? N2 : N3;
13494 // Check to see if we can simplify the select into an fabs node
13495 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13496 // Allow either -0.0 or 0.0
13497 if (CFP->isZero()) {
13498 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13499 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13500 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13501 N2 == N3.getOperand(0))
13502 return DAG.getNode(ISD::FABS, DL, VT, N0);
13504 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13505 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13506 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13507 N2.getOperand(0) == N3)
13508 return DAG.getNode(ISD::FABS, DL, VT, N3);
13512 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13513 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13514 // in it. This is a win when the constant is not otherwise available because
13515 // it replaces two constant pool loads with one. We only do this if the FP
13516 // type is known to be legal, because if it isn't, then we are before legalize
13517 // types an we want the other legalization to happen first (e.g. to avoid
13518 // messing with soft float) and if the ConstantFP is not legal, because if
13519 // it is legal, we may not need to store the FP constant in a constant pool.
13520 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13521 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13522 if (TLI.isTypeLegal(N2.getValueType()) &&
13523 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13524 TargetLowering::Legal &&
13525 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13526 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13527 // If both constants have multiple uses, then we won't need to do an
13528 // extra load, they are likely around in registers for other users.
13529 (TV->hasOneUse() || FV->hasOneUse())) {
13530 Constant *Elts[] = {
13531 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13532 const_cast<ConstantFP*>(TV->getConstantFPValue())
13534 Type *FPTy = Elts[0]->getType();
13535 const DataLayout &TD = DAG.getDataLayout();
13537 // Create a ConstantArray of the two constants.
13538 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13540 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13541 TD.getPrefTypeAlignment(FPTy));
13542 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13544 // Get the offsets to the 0 and 1 element of the array so that we can
13545 // select between them.
13546 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13547 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13548 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13550 SDValue Cond = DAG.getSetCC(DL,
13551 getSetCCResultType(N0.getValueType()),
13553 AddToWorklist(Cond.getNode());
13554 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13556 AddToWorklist(CstOffset.getNode());
13557 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13559 AddToWorklist(CPIdx.getNode());
13560 return DAG.getLoad(
13561 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13562 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13563 false, false, false, Alignment);
13567 // Check to see if we can perform the "gzip trick", transforming
13568 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13569 if (isNullConstant(N3) && CC == ISD::SETLT &&
13570 (isNullConstant(N1) || // (a < 0) ? b : 0
13571 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13572 EVT XType = N0.getValueType();
13573 EVT AType = N2.getValueType();
13574 if (XType.bitsGE(AType)) {
13575 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13576 // single-bit constant.
13577 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13578 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13579 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13580 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13581 getShiftAmountTy(N0.getValueType()));
13582 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13584 AddToWorklist(Shift.getNode());
13586 if (XType.bitsGT(AType)) {
13587 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13588 AddToWorklist(Shift.getNode());
13591 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13594 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13596 DAG.getConstant(XType.getSizeInBits() - 1,
13598 getShiftAmountTy(N0.getValueType())));
13599 AddToWorklist(Shift.getNode());
13601 if (XType.bitsGT(AType)) {
13602 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13603 AddToWorklist(Shift.getNode());
13606 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13610 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13611 // where y is has a single bit set.
13612 // A plaintext description would be, we can turn the SELECT_CC into an AND
13613 // when the condition can be materialized as an all-ones register. Any
13614 // single bit-test can be materialized as an all-ones register with
13615 // shift-left and shift-right-arith.
13616 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13617 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13618 SDValue AndLHS = N0->getOperand(0);
13619 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13620 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13621 // Shift the tested bit over the sign bit.
13622 APInt AndMask = ConstAndRHS->getAPIntValue();
13624 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13625 getShiftAmountTy(AndLHS.getValueType()));
13626 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13628 // Now arithmetic right shift it all the way over, so the result is either
13629 // all-ones, or zero.
13631 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13632 getShiftAmountTy(Shl.getValueType()));
13633 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13635 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13639 // fold select C, 16, 0 -> shl C, 4
13640 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13641 TLI.getBooleanContents(N0.getValueType()) ==
13642 TargetLowering::ZeroOrOneBooleanContent) {
13644 // If the caller doesn't want us to simplify this into a zext of a compare,
13646 if (NotExtCompare && N2C->isOne())
13649 // Get a SetCC of the condition
13650 // NOTE: Don't create a SETCC if it's not legal on this target.
13651 if (!LegalOperations ||
13652 TLI.isOperationLegal(ISD::SETCC,
13653 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13655 // cast from setcc result type to select result type
13657 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13659 if (N2.getValueType().bitsLT(SCC.getValueType()))
13660 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13661 N2.getValueType());
13663 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13664 N2.getValueType(), SCC);
13666 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13667 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13668 N2.getValueType(), SCC);
13671 AddToWorklist(SCC.getNode());
13672 AddToWorklist(Temp.getNode());
13677 // shl setcc result by log2 n2c
13678 return DAG.getNode(
13679 ISD::SHL, DL, N2.getValueType(), Temp,
13680 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13681 getShiftAmountTy(Temp.getValueType())));
13685 // Check to see if this is the equivalent of setcc
13686 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13687 // otherwise, go ahead with the folds.
13688 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13689 EVT XType = N0.getValueType();
13690 if (!LegalOperations ||
13691 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13692 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13693 if (Res.getValueType() != VT)
13694 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13698 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13699 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13700 (!LegalOperations ||
13701 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13702 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13703 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13704 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13706 getShiftAmountTy(Ctlz.getValueType())));
13708 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13709 if (isNullConstant(N1) && CC == ISD::SETGT) {
13711 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13712 XType, DAG.getConstant(0, DL, XType), N0);
13713 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13714 return DAG.getNode(ISD::SRL, DL, XType,
13715 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13716 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13717 getShiftAmountTy(XType)));
13719 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13720 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13722 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13723 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13724 getShiftAmountTy(N0.getValueType())));
13725 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13730 // Check to see if this is an integer abs.
13731 // select_cc setg[te] X, 0, X, -X ->
13732 // select_cc setgt X, -1, X, -X ->
13733 // select_cc setl[te] X, 0, -X, X ->
13734 // select_cc setlt X, 1, -X, X ->
13735 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13737 ConstantSDNode *SubC = nullptr;
13738 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13739 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13740 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13741 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13742 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13743 (N1C->isOne() && CC == ISD::SETLT)) &&
13744 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13745 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13747 EVT XType = N0.getValueType();
13748 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13750 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13752 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13753 getShiftAmountTy(N0.getValueType())));
13754 SDValue Add = DAG.getNode(ISD::ADD, DL,
13756 AddToWorklist(Shift.getNode());
13757 AddToWorklist(Add.getNode());
13758 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13765 /// This is a stub for TargetLowering::SimplifySetCC.
13766 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13767 SDValue N1, ISD::CondCode Cond,
13768 SDLoc DL, bool foldBooleans) {
13769 TargetLowering::DAGCombinerInfo
13770 DagCombineInfo(DAG, Level, false, this);
13771 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13774 /// Given an ISD::SDIV node expressing a divide by constant, return
13775 /// a DAG expression to select that will generate the same value by multiplying
13776 /// by a magic number.
13777 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13778 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13779 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13783 // Avoid division by zero.
13784 if (C->isNullValue())
13787 std::vector<SDNode*> Built;
13789 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13791 for (SDNode *N : Built)
13796 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13797 /// DAG expression that will generate the same value by right shifting.
13798 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13799 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13803 // Avoid division by zero.
13804 if (C->isNullValue())
13807 std::vector<SDNode *> Built;
13808 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13810 for (SDNode *N : Built)
13815 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13816 /// expression that will generate the same value by multiplying by a magic
13818 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13819 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13820 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13824 // Avoid division by zero.
13825 if (C->isNullValue())
13828 std::vector<SDNode*> Built;
13830 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13832 for (SDNode *N : Built)
13837 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13838 if (Level >= AfterLegalizeDAG)
13841 // Expose the DAG combiner to the target combiner implementations.
13842 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13844 unsigned Iterations = 0;
13845 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13847 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13848 // For the reciprocal, we need to find the zero of the function:
13849 // F(X) = A X - 1 [which has a zero at X = 1/A]
13851 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13852 // does not require additional intermediate precision]
13853 EVT VT = Op.getValueType();
13855 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13857 AddToWorklist(Est.getNode());
13859 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13860 for (unsigned i = 0; i < Iterations; ++i) {
13861 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13862 AddToWorklist(NewEst.getNode());
13864 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13865 AddToWorklist(NewEst.getNode());
13867 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13868 AddToWorklist(NewEst.getNode());
13870 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13871 AddToWorklist(Est.getNode());
13880 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13881 /// For the reciprocal sqrt, we need to find the zero of the function:
13882 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13884 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13885 /// As a result, we precompute A/2 prior to the iteration loop.
13886 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13887 unsigned Iterations) {
13888 EVT VT = Arg.getValueType();
13890 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13892 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13893 // this entire sequence requires only one FP constant.
13894 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13895 AddToWorklist(HalfArg.getNode());
13897 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13898 AddToWorklist(HalfArg.getNode());
13900 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13901 for (unsigned i = 0; i < Iterations; ++i) {
13902 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13903 AddToWorklist(NewEst.getNode());
13905 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13906 AddToWorklist(NewEst.getNode());
13908 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13909 AddToWorklist(NewEst.getNode());
13911 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13912 AddToWorklist(Est.getNode());
13917 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13918 /// For the reciprocal sqrt, we need to find the zero of the function:
13919 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13921 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13922 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13923 unsigned Iterations) {
13924 EVT VT = Arg.getValueType();
13926 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13927 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13929 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13930 for (unsigned i = 0; i < Iterations; ++i) {
13931 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13932 AddToWorklist(HalfEst.getNode());
13934 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13935 AddToWorklist(Est.getNode());
13937 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13938 AddToWorklist(Est.getNode());
13940 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13941 AddToWorklist(Est.getNode());
13943 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13944 AddToWorklist(Est.getNode());
13949 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13950 if (Level >= AfterLegalizeDAG)
13953 // Expose the DAG combiner to the target combiner implementations.
13954 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13955 unsigned Iterations = 0;
13956 bool UseOneConstNR = false;
13957 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13958 AddToWorklist(Est.getNode());
13960 Est = UseOneConstNR ?
13961 BuildRsqrtNROneConst(Op, Est, Iterations) :
13962 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13970 /// Return true if base is a frame index, which is known not to alias with
13971 /// anything but itself. Provides base object and offset as results.
13972 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13973 const GlobalValue *&GV, const void *&CV) {
13974 // Assume it is a primitive operation.
13975 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13977 // If it's an adding a simple constant then integrate the offset.
13978 if (Base.getOpcode() == ISD::ADD) {
13979 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13980 Base = Base.getOperand(0);
13981 Offset += C->getZExtValue();
13985 // Return the underlying GlobalValue, and update the Offset. Return false
13986 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13987 // by multiple nodes with different offsets.
13988 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13989 GV = G->getGlobal();
13990 Offset += G->getOffset();
13994 // Return the underlying Constant value, and update the Offset. Return false
13995 // for ConstantSDNodes since the same constant pool entry may be represented
13996 // by multiple nodes with different offsets.
13997 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13998 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13999 : (const void *)C->getConstVal();
14000 Offset += C->getOffset();
14003 // If it's any of the following then it can't alias with anything but itself.
14004 return isa<FrameIndexSDNode>(Base);
14007 /// Return true if there is any possibility that the two addresses overlap.
14008 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14009 // If they are the same then they must be aliases.
14010 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14012 // If they are both volatile then they cannot be reordered.
14013 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14015 // If one operation reads from invariant memory, and the other may store, they
14016 // cannot alias. These should really be checking the equivalent of mayWrite,
14017 // but it only matters for memory nodes other than load /store.
14018 if (Op0->isInvariant() && Op1->writeMem())
14021 if (Op1->isInvariant() && Op0->writeMem())
14024 // Gather base node and offset information.
14025 SDValue Base1, Base2;
14026 int64_t Offset1, Offset2;
14027 const GlobalValue *GV1, *GV2;
14028 const void *CV1, *CV2;
14029 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14030 Base1, Offset1, GV1, CV1);
14031 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14032 Base2, Offset2, GV2, CV2);
14034 // If they have a same base address then check to see if they overlap.
14035 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14036 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14037 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14039 // It is possible for different frame indices to alias each other, mostly
14040 // when tail call optimization reuses return address slots for arguments.
14041 // To catch this case, look up the actual index of frame indices to compute
14042 // the real alias relationship.
14043 if (isFrameIndex1 && isFrameIndex2) {
14044 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14045 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14046 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14047 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14048 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14051 // Otherwise, if we know what the bases are, and they aren't identical, then
14052 // we know they cannot alias.
14053 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14056 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14057 // compared to the size and offset of the access, we may be able to prove they
14058 // do not alias. This check is conservative for now to catch cases created by
14059 // splitting vector types.
14060 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14061 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14062 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14063 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14064 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14065 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14066 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14068 // There is no overlap between these relatively aligned accesses of similar
14069 // size, return no alias.
14070 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14071 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14075 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14077 : DAG.getSubtarget().useAA();
14079 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14080 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14084 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14085 // Use alias analysis information.
14086 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14087 Op1->getSrcValueOffset());
14088 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14089 Op0->getSrcValueOffset() - MinOffset;
14090 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14091 Op1->getSrcValueOffset() - MinOffset;
14092 AliasResult AAResult =
14093 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14094 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14095 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14096 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14097 if (AAResult == NoAlias)
14101 // Otherwise we have to assume they alias.
14105 /// Walk up chain skipping non-aliasing memory nodes,
14106 /// looking for aliasing nodes and adding them to the Aliases vector.
14107 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14108 SmallVectorImpl<SDValue> &Aliases) {
14109 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14110 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14112 // Get alias information for node.
14113 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14116 Chains.push_back(OriginalChain);
14117 unsigned Depth = 0;
14119 // Look at each chain and determine if it is an alias. If so, add it to the
14120 // aliases list. If not, then continue up the chain looking for the next
14122 while (!Chains.empty()) {
14123 SDValue Chain = Chains.pop_back_val();
14125 // For TokenFactor nodes, look at each operand and only continue up the
14126 // chain until we find two aliases. If we've seen two aliases, assume we'll
14127 // find more and revert to original chain since the xform is unlikely to be
14130 // FIXME: The depth check could be made to return the last non-aliasing
14131 // chain we found before we hit a tokenfactor rather than the original
14133 if (Depth > 6 || Aliases.size() == 2) {
14135 Aliases.push_back(OriginalChain);
14139 // Don't bother if we've been before.
14140 if (!Visited.insert(Chain.getNode()).second)
14143 switch (Chain.getOpcode()) {
14144 case ISD::EntryToken:
14145 // Entry token is ideal chain operand, but handled in FindBetterChain.
14150 // Get alias information for Chain.
14151 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14152 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14154 // If chain is alias then stop here.
14155 if (!(IsLoad && IsOpLoad) &&
14156 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14157 Aliases.push_back(Chain);
14159 // Look further up the chain.
14160 Chains.push_back(Chain.getOperand(0));
14166 case ISD::TokenFactor:
14167 // We have to check each of the operands of the token factor for "small"
14168 // token factors, so we queue them up. Adding the operands to the queue
14169 // (stack) in reverse order maintains the original order and increases the
14170 // likelihood that getNode will find a matching token factor (CSE.)
14171 if (Chain.getNumOperands() > 16) {
14172 Aliases.push_back(Chain);
14175 for (unsigned n = Chain.getNumOperands(); n;)
14176 Chains.push_back(Chain.getOperand(--n));
14181 // For all other instructions we will just have to take what we can get.
14182 Aliases.push_back(Chain);
14187 // We need to be careful here to also search for aliases through the
14188 // value operand of a store, etc. Consider the following situation:
14190 // L1 = load Token1, %52
14191 // S1 = store Token1, L1, %51
14192 // L2 = load Token1, %52+8
14193 // S2 = store Token1, L2, %51+8
14194 // Token2 = Token(S1, S2)
14195 // L3 = load Token2, %53
14196 // S3 = store Token2, L3, %52
14197 // L4 = load Token2, %53+8
14198 // S4 = store Token2, L4, %52+8
14199 // If we search for aliases of S3 (which loads address %52), and we look
14200 // only through the chain, then we'll miss the trivial dependence on L1
14201 // (which also loads from %52). We then might change all loads and
14202 // stores to use Token1 as their chain operand, which could result in
14203 // copying %53 into %52 before copying %52 into %51 (which should
14206 // The problem is, however, that searching for such data dependencies
14207 // can become expensive, and the cost is not directly related to the
14208 // chain depth. Instead, we'll rule out such configurations here by
14209 // insisting that we've visited all chain users (except for users
14210 // of the original chain, which is not necessary). When doing this,
14211 // we need to look through nodes we don't care about (otherwise, things
14212 // like register copies will interfere with trivial cases).
14214 SmallVector<const SDNode *, 16> Worklist;
14215 for (const SDNode *N : Visited)
14216 if (N != OriginalChain.getNode())
14217 Worklist.push_back(N);
14219 while (!Worklist.empty()) {
14220 const SDNode *M = Worklist.pop_back_val();
14222 // We have already visited M, and want to make sure we've visited any uses
14223 // of M that we care about. For uses that we've not visisted, and don't
14224 // care about, queue them to the worklist.
14226 for (SDNode::use_iterator UI = M->use_begin(),
14227 UIE = M->use_end(); UI != UIE; ++UI)
14228 if (UI.getUse().getValueType() == MVT::Other &&
14229 Visited.insert(*UI).second) {
14230 if (isa<MemSDNode>(*UI)) {
14231 // We've not visited this use, and we care about it (it could have an
14232 // ordering dependency with the original node).
14234 Aliases.push_back(OriginalChain);
14238 // We've not visited this use, but we don't care about it. Mark it as
14239 // visited and enqueue it to the worklist.
14240 Worklist.push_back(*UI);
14245 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14246 /// (aliasing node.)
14247 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14248 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14250 // Accumulate all the aliases to this node.
14251 GatherAllAliases(N, OldChain, Aliases);
14253 // If no operands then chain to entry token.
14254 if (Aliases.size() == 0)
14255 return DAG.getEntryNode();
14257 // If a single operand then chain to it. We don't need to revisit it.
14258 if (Aliases.size() == 1)
14261 // Construct a custom tailored token factor.
14262 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14265 /// This is the entry point for the file.
14266 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14267 CodeGenOpt::Level OptLevel) {
14268 /// This is the main entry point to this class.
14269 DAGCombiner(*this, AA, OptLevel).Run(Level);