1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/None.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetVector.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/ADT/SmallSet.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/MemoryLocation.h" 34 #include "llvm/CodeGen/DAGCombine.h" 35 #include "llvm/CodeGen/ISDOpcodes.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAG.h" 41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 42 #include "llvm/CodeGen/SelectionDAGNodes.h" 43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Attributes.h" 49 #include "llvm/IR/Constant.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CodeGen.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetMachine.h" 66 #include "llvm/Target/TargetOptions.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstdint> 70 #include <functional> 71 #include <iterator> 72 #include <string> 73 #include <tuple> 74 #include <utility> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "dagcombine" 79 80 STATISTIC(NodesCombined , "Number of dag nodes combined"); 81 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 82 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 83 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 84 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 85 STATISTIC(SlicedLoads, "Number of load sliced"); 86 87 static cl::opt<bool> 88 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 89 cl::desc("Enable DAG combiner's use of IR alias analysis")); 90 91 static cl::opt<bool> 92 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 93 cl::desc("Enable DAG combiner's use of TBAA")); 94 95 #ifndef NDEBUG 96 static cl::opt<std::string> 97 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 98 cl::desc("Only use DAG-combiner alias analysis in this" 99 " function")); 100 #endif 101 102 /// Hidden option to stress test load slicing, i.e., when this option 103 /// is enabled, load slicing bypasses most of its profitability guards. 104 static cl::opt<bool> 105 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 106 cl::desc("Bypass the profitability model of load slicing"), 107 cl::init(false)); 108 109 static cl::opt<bool> 110 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 111 cl::desc("DAG combiner may split indexing from loads")); 112 113 namespace { 114 115 class DAGCombiner { 116 SelectionDAG &DAG; 117 const TargetLowering &TLI; 118 CombineLevel Level; 119 CodeGenOpt::Level OptLevel; 120 bool LegalOperations = false; 121 bool LegalTypes = false; 122 bool ForCodeSize; 123 124 /// Worklist of all of the nodes that need to be simplified. 125 /// 126 /// This must behave as a stack -- new nodes to process are pushed onto the 127 /// back and when processing we pop off of the back. 128 /// 129 /// The worklist will not contain duplicates but may contain null entries 130 /// due to nodes being deleted from the underlying DAG. 131 SmallVector<SDNode *, 64> Worklist; 132 133 /// Mapping from an SDNode to its position on the worklist. 134 /// 135 /// This is used to find and remove nodes from the worklist (by nulling 136 /// them) when they are deleted from the underlying DAG. It relies on 137 /// stable indices of nodes within the worklist. 138 DenseMap<SDNode *, unsigned> WorklistMap; 139 140 /// Set of nodes which have been combined (at least once). 141 /// 142 /// This is used to allow us to reliably add any operands of a DAG node 143 /// which have not yet been combined to the worklist. 144 SmallPtrSet<SDNode *, 32> CombinedNodes; 145 146 // AA - Used for DAG load/store alias analysis. 147 AliasAnalysis *AA; 148 149 /// When an instruction is simplified, add all users of the instruction to 150 /// the work lists because they might get more simplified now. 151 void AddUsersToWorklist(SDNode *N) { 152 for (SDNode *Node : N->uses()) 153 AddToWorklist(Node); 154 } 155 156 /// Call the node-specific routine that folds each particular type of node. 157 SDValue visit(SDNode *N); 158 159 public: 160 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 161 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 162 OptLevel(OL), AA(AA) { 163 ForCodeSize = DAG.getMachineFunction().getFunction().optForSize(); 164 165 MaximumLegalStoreInBits = 0; 166 for (MVT VT : MVT::all_valuetypes()) 167 if (EVT(VT).isSimple() && VT != MVT::Other && 168 TLI.isTypeLegal(EVT(VT)) && 169 VT.getSizeInBits() >= MaximumLegalStoreInBits) 170 MaximumLegalStoreInBits = VT.getSizeInBits(); 171 } 172 173 /// Add to the worklist making sure its instance is at the back (next to be 174 /// processed.) 175 void AddToWorklist(SDNode *N) { 176 assert(N->getOpcode() != ISD::DELETED_NODE && 177 "Deleted Node added to Worklist"); 178 179 // Skip handle nodes as they can't usefully be combined and confuse the 180 // zero-use deletion strategy. 181 if (N->getOpcode() == ISD::HANDLENODE) 182 return; 183 184 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 185 Worklist.push_back(N); 186 } 187 188 /// Remove all instances of N from the worklist. 189 void removeFromWorklist(SDNode *N) { 190 CombinedNodes.erase(N); 191 192 auto It = WorklistMap.find(N); 193 if (It == WorklistMap.end()) 194 return; // Not in the worklist. 195 196 // Null out the entry rather than erasing it to avoid a linear operation. 197 Worklist[It->second] = nullptr; 198 WorklistMap.erase(It); 199 } 200 201 void deleteAndRecombine(SDNode *N); 202 bool recursivelyDeleteUnusedNodes(SDNode *N); 203 204 /// Replaces all uses of the results of one DAG node with new values. 205 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 206 bool AddTo = true); 207 208 /// Replaces all uses of the results of one DAG node with new values. 209 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 210 return CombineTo(N, &Res, 1, AddTo); 211 } 212 213 /// Replaces all uses of the results of one DAG node with new values. 214 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 215 bool AddTo = true) { 216 SDValue To[] = { Res0, Res1 }; 217 return CombineTo(N, To, 2, AddTo); 218 } 219 220 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 221 222 private: 223 unsigned MaximumLegalStoreInBits; 224 225 /// Check the specified integer node value to see if it can be simplified or 226 /// if things it uses can be simplified by bit propagation. 227 /// If so, return true. 228 bool SimplifyDemandedBits(SDValue Op) { 229 unsigned BitWidth = Op.getScalarValueSizeInBits(); 230 APInt Demanded = APInt::getAllOnesValue(BitWidth); 231 return SimplifyDemandedBits(Op, Demanded); 232 } 233 234 /// Check the specified vector node value to see if it can be simplified or 235 /// if things it uses can be simplified as it only uses some of the 236 /// elements. If so, return true. 237 bool SimplifyDemandedVectorElts(SDValue Op) { 238 unsigned NumElts = Op.getValueType().getVectorNumElements(); 239 APInt Demanded = APInt::getAllOnesValue(NumElts); 240 return SimplifyDemandedVectorElts(Op, Demanded); 241 } 242 243 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 244 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded, 245 bool AssumeSingleUse = false); 246 247 bool CombineToPreIndexedLoadStore(SDNode *N); 248 bool CombineToPostIndexedLoadStore(SDNode *N); 249 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 250 bool SliceUpLoad(SDNode *N); 251 252 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 253 /// load. 254 /// 255 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 256 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 257 /// \param EltNo index of the vector element to load. 258 /// \param OriginalLoad load that EVE came from to be replaced. 259 /// \returns EVE on success SDValue() on failure. 260 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 261 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 262 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 263 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 264 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 265 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 266 SDValue PromoteIntBinOp(SDValue Op); 267 SDValue PromoteIntShiftOp(SDValue Op); 268 SDValue PromoteExtend(SDValue Op); 269 bool PromoteLoad(SDValue Op); 270 271 /// Call the node-specific routine that knows how to fold each 272 /// particular type of node. If that doesn't do anything, try the 273 /// target-specific DAG combines. 274 SDValue combine(SDNode *N); 275 276 // Visitation implementation - Implement dag node combining for different 277 // node types. The semantics are as follows: 278 // Return Value: 279 // SDValue.getNode() == 0 - No change was made 280 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 281 // otherwise - N should be replaced by the returned Operand. 282 // 283 SDValue visitTokenFactor(SDNode *N); 284 SDValue visitMERGE_VALUES(SDNode *N); 285 SDValue visitADD(SDNode *N); 286 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 287 SDValue visitSUB(SDNode *N); 288 SDValue visitADDC(SDNode *N); 289 SDValue visitUADDO(SDNode *N); 290 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 291 SDValue visitSUBC(SDNode *N); 292 SDValue visitUSUBO(SDNode *N); 293 SDValue visitADDE(SDNode *N); 294 SDValue visitADDCARRY(SDNode *N); 295 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 296 SDValue visitSUBE(SDNode *N); 297 SDValue visitSUBCARRY(SDNode *N); 298 SDValue visitMUL(SDNode *N); 299 SDValue useDivRem(SDNode *N); 300 SDValue visitSDIV(SDNode *N); 301 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N); 302 SDValue visitUDIV(SDNode *N); 303 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N); 304 SDValue visitREM(SDNode *N); 305 SDValue visitMULHU(SDNode *N); 306 SDValue visitMULHS(SDNode *N); 307 SDValue visitSMUL_LOHI(SDNode *N); 308 SDValue visitUMUL_LOHI(SDNode *N); 309 SDValue visitSMULO(SDNode *N); 310 SDValue visitUMULO(SDNode *N); 311 SDValue visitIMINMAX(SDNode *N); 312 SDValue visitAND(SDNode *N); 313 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N); 314 SDValue visitOR(SDNode *N); 315 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N); 316 SDValue visitXOR(SDNode *N); 317 SDValue SimplifyVBinOp(SDNode *N); 318 SDValue visitSHL(SDNode *N); 319 SDValue visitSRA(SDNode *N); 320 SDValue visitSRL(SDNode *N); 321 SDValue visitRotate(SDNode *N); 322 SDValue visitABS(SDNode *N); 323 SDValue visitBSWAP(SDNode *N); 324 SDValue visitBITREVERSE(SDNode *N); 325 SDValue visitCTLZ(SDNode *N); 326 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 327 SDValue visitCTTZ(SDNode *N); 328 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 329 SDValue visitCTPOP(SDNode *N); 330 SDValue visitSELECT(SDNode *N); 331 SDValue visitVSELECT(SDNode *N); 332 SDValue visitSELECT_CC(SDNode *N); 333 SDValue visitSETCC(SDNode *N); 334 SDValue visitSETCCCARRY(SDNode *N); 335 SDValue visitSIGN_EXTEND(SDNode *N); 336 SDValue visitZERO_EXTEND(SDNode *N); 337 SDValue visitANY_EXTEND(SDNode *N); 338 SDValue visitAssertExt(SDNode *N); 339 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 340 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 341 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 342 SDValue visitTRUNCATE(SDNode *N); 343 SDValue visitBITCAST(SDNode *N); 344 SDValue visitBUILD_PAIR(SDNode *N); 345 SDValue visitFADD(SDNode *N); 346 SDValue visitFSUB(SDNode *N); 347 SDValue visitFMUL(SDNode *N); 348 SDValue visitFMA(SDNode *N); 349 SDValue visitFDIV(SDNode *N); 350 SDValue visitFREM(SDNode *N); 351 SDValue visitFSQRT(SDNode *N); 352 SDValue visitFCOPYSIGN(SDNode *N); 353 SDValue visitSINT_TO_FP(SDNode *N); 354 SDValue visitUINT_TO_FP(SDNode *N); 355 SDValue visitFP_TO_SINT(SDNode *N); 356 SDValue visitFP_TO_UINT(SDNode *N); 357 SDValue visitFP_ROUND(SDNode *N); 358 SDValue visitFP_ROUND_INREG(SDNode *N); 359 SDValue visitFP_EXTEND(SDNode *N); 360 SDValue visitFNEG(SDNode *N); 361 SDValue visitFABS(SDNode *N); 362 SDValue visitFCEIL(SDNode *N); 363 SDValue visitFTRUNC(SDNode *N); 364 SDValue visitFFLOOR(SDNode *N); 365 SDValue visitFMINNUM(SDNode *N); 366 SDValue visitFMAXNUM(SDNode *N); 367 SDValue visitBRCOND(SDNode *N); 368 SDValue visitBR_CC(SDNode *N); 369 SDValue visitLOAD(SDNode *N); 370 371 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 372 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 373 374 SDValue visitSTORE(SDNode *N); 375 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 376 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 377 SDValue visitBUILD_VECTOR(SDNode *N); 378 SDValue visitCONCAT_VECTORS(SDNode *N); 379 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 380 SDValue visitVECTOR_SHUFFLE(SDNode *N); 381 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 382 SDValue visitINSERT_SUBVECTOR(SDNode *N); 383 SDValue visitMLOAD(SDNode *N); 384 SDValue visitMSTORE(SDNode *N); 385 SDValue visitMGATHER(SDNode *N); 386 SDValue visitMSCATTER(SDNode *N); 387 SDValue visitFP_TO_FP16(SDNode *N); 388 SDValue visitFP16_TO_FP(SDNode *N); 389 390 SDValue visitFADDForFMACombine(SDNode *N); 391 SDValue visitFSUBForFMACombine(SDNode *N); 392 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 393 394 SDValue XformToShuffleWithZero(SDNode *N); 395 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 396 SDValue N1, SDNodeFlags Flags); 397 398 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 399 400 SDValue foldSelectOfConstants(SDNode *N); 401 SDValue foldVSelectOfConstants(SDNode *N); 402 SDValue foldBinOpIntoSelect(SDNode *BO); 403 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 404 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 405 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 406 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 407 SDValue N2, SDValue N3, ISD::CondCode CC, 408 bool NotExtCompare = false); 409 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 410 SDValue N2, SDValue N3, ISD::CondCode CC); 411 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 412 const SDLoc &DL); 413 SDValue unfoldMaskedMerge(SDNode *N); 414 SDValue unfoldExtremeBitClearingToShifts(SDNode *N); 415 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 416 const SDLoc &DL, bool foldBooleans); 417 SDValue rebuildSetCC(SDValue N); 418 419 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 420 SDValue &CC) const; 421 bool isOneUseSetCC(SDValue N) const; 422 423 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 424 unsigned HiOp); 425 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 426 SDValue CombineExtLoad(SDNode *N); 427 SDValue CombineZExtLogicopShiftLoad(SDNode *N); 428 SDValue combineRepeatedFPDivisors(SDNode *N); 429 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 430 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 431 SDValue BuildSDIV(SDNode *N); 432 SDValue BuildSDIVPow2(SDNode *N); 433 SDValue BuildUDIV(SDNode *N); 434 SDValue BuildLogBase2(SDValue V, const SDLoc &DL); 435 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 436 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 437 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 438 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 439 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, 440 SDNodeFlags Flags, bool Reciprocal); 441 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, 442 SDNodeFlags Flags, bool Reciprocal); 443 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 444 bool DemandHighBits = true); 445 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 446 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 447 SDValue InnerPos, SDValue InnerNeg, 448 unsigned PosOpcode, unsigned NegOpcode, 449 const SDLoc &DL); 450 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 451 SDValue MatchLoadCombine(SDNode *N); 452 SDValue ReduceLoadWidth(SDNode *N); 453 SDValue ReduceLoadOpStoreWidth(SDNode *N); 454 SDValue splitMergedValStore(StoreSDNode *ST); 455 SDValue TransformFPLoadStorePair(SDNode *N); 456 SDValue convertBuildVecZextToZext(SDNode *N); 457 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 458 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 459 SDValue reduceBuildVecToShuffle(SDNode *N); 460 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 461 ArrayRef<int> VectorMask, SDValue VecIn1, 462 SDValue VecIn2, unsigned LeftIdx); 463 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); 464 465 /// Walk up chain skipping non-aliasing memory nodes, 466 /// looking for aliasing nodes and adding them to the Aliases vector. 467 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 468 SmallVectorImpl<SDValue> &Aliases); 469 470 /// Return true if there is any possibility that the two addresses overlap. 471 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 472 473 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 474 /// chain (aliasing node.) 475 SDValue FindBetterChain(SDNode *N, SDValue Chain); 476 477 /// Try to replace a store and any possibly adjacent stores on 478 /// consecutive chains with better chains. Return true only if St is 479 /// replaced. 480 /// 481 /// Notice that other chains may still be replaced even if the function 482 /// returns false. 483 bool findBetterNeighborChains(StoreSDNode *St); 484 485 /// Holds a pointer to an LSBaseSDNode as well as information on where it 486 /// is located in a sequence of memory operations connected by a chain. 487 struct MemOpLink { 488 // Ptr to the mem node. 489 LSBaseSDNode *MemNode; 490 491 // Offset from the base ptr. 492 int64_t OffsetFromBase; 493 494 MemOpLink(LSBaseSDNode *N, int64_t Offset) 495 : MemNode(N), OffsetFromBase(Offset) {} 496 }; 497 498 /// This is a helper function for visitMUL to check the profitability 499 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 500 /// MulNode is the original multiply, AddNode is (add x, c1), 501 /// and ConstNode is c2. 502 bool isMulAddWithConstProfitable(SDNode *MulNode, 503 SDValue &AddNode, 504 SDValue &ConstNode); 505 506 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 507 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 508 /// the type of the loaded value to be extended. 509 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 510 EVT LoadResultTy, EVT &ExtVT); 511 512 /// Helper function to calculate whether the given Load/Store can have its 513 /// width reduced to ExtVT. 514 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, 515 EVT &MemVT, unsigned ShAmt = 0); 516 517 /// Used by BackwardsPropagateMask to find suitable loads. 518 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads, 519 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 520 ConstantSDNode *Mask, SDNode *&NodeToMask); 521 /// Attempt to propagate a given AND node back to load leaves so that they 522 /// can be combined into narrow loads. 523 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG); 524 525 /// Helper function for MergeConsecutiveStores which merges the 526 /// component store chains. 527 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 528 unsigned NumStores); 529 530 /// This is a helper function for MergeConsecutiveStores. When the 531 /// source elements of the consecutive stores are all constants or 532 /// all extracted vector elements, try to merge them into one 533 /// larger store introducing bitcasts if necessary. \return True 534 /// if a merged store was created. 535 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 536 EVT MemVT, unsigned NumStores, 537 bool IsConstantSrc, bool UseVector, 538 bool UseTrunc); 539 540 /// This is a helper function for MergeConsecutiveStores. Stores 541 /// that potentially may be merged with St are placed in 542 /// StoreNodes. RootNode is a chain predecessor to all store 543 /// candidates. 544 void getStoreMergeCandidates(StoreSDNode *St, 545 SmallVectorImpl<MemOpLink> &StoreNodes, 546 SDNode *&Root); 547 548 /// Helper function for MergeConsecutiveStores. Checks if 549 /// candidate stores have indirect dependency through their 550 /// operands. RootNode is the predecessor to all stores calculated 551 /// by getStoreMergeCandidates and is used to prune the dependency check. 552 /// \return True if safe to merge. 553 bool checkMergeStoreCandidatesForDependencies( 554 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 555 SDNode *RootNode); 556 557 /// Merge consecutive store operations into a wide store. 558 /// This optimization uses wide integers or vectors when possible. 559 /// \return number of stores that were merged into a merged store (the 560 /// affected nodes are stored as a prefix in \p StoreNodes). 561 bool MergeConsecutiveStores(StoreSDNode *St); 562 563 /// Try to transform a truncation where C is a constant: 564 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 565 /// 566 /// \p N needs to be a truncation and its first operand an AND. Other 567 /// requirements are checked by the function (e.g. that trunc is 568 /// single-use) and if missed an empty SDValue is returned. 569 SDValue distributeTruncateThroughAnd(SDNode *N); 570 571 /// Helper function to determine whether the target supports operation 572 /// given by \p Opcode for type \p VT, that is, whether the operation 573 /// is legal or custom before legalizing operations, and whether is 574 /// legal (but not custom) after legalization. 575 bool hasOperation(unsigned Opcode, EVT VT) { 576 if (LegalOperations) 577 return TLI.isOperationLegal(Opcode, VT); 578 return TLI.isOperationLegalOrCustom(Opcode, VT); 579 } 580 581 public: 582 /// Runs the dag combiner on all nodes in the work list 583 void Run(CombineLevel AtLevel); 584 585 SelectionDAG &getDAG() const { return DAG; } 586 587 /// Returns a type large enough to hold any valid shift amount - before type 588 /// legalization these can be huge. 589 EVT getShiftAmountTy(EVT LHSTy) { 590 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 591 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 592 } 593 594 /// This method returns true if we are running before type legalization or 595 /// if the specified VT is legal. 596 bool isTypeLegal(const EVT &VT) { 597 if (!LegalTypes) return true; 598 return TLI.isTypeLegal(VT); 599 } 600 601 /// Convenience wrapper around TargetLowering::getSetCCResultType 602 EVT getSetCCResultType(EVT VT) const { 603 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 604 } 605 606 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 607 SDValue OrigLoad, SDValue ExtLoad, 608 ISD::NodeType ExtType); 609 }; 610 611 /// This class is a DAGUpdateListener that removes any deleted 612 /// nodes from the worklist. 613 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 614 DAGCombiner &DC; 615 616 public: 617 explicit WorklistRemover(DAGCombiner &dc) 618 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 619 620 void NodeDeleted(SDNode *N, SDNode *E) override { 621 DC.removeFromWorklist(N); 622 } 623 }; 624 625 } // end anonymous namespace 626 627 //===----------------------------------------------------------------------===// 628 // TargetLowering::DAGCombinerInfo implementation 629 //===----------------------------------------------------------------------===// 630 631 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 632 ((DAGCombiner*)DC)->AddToWorklist(N); 633 } 634 635 SDValue TargetLowering::DAGCombinerInfo:: 636 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 637 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 638 } 639 640 SDValue TargetLowering::DAGCombinerInfo:: 641 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 642 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 643 } 644 645 SDValue TargetLowering::DAGCombinerInfo:: 646 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 647 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 648 } 649 650 void TargetLowering::DAGCombinerInfo:: 651 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 652 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 653 } 654 655 //===----------------------------------------------------------------------===// 656 // Helper Functions 657 //===----------------------------------------------------------------------===// 658 659 void DAGCombiner::deleteAndRecombine(SDNode *N) { 660 removeFromWorklist(N); 661 662 // If the operands of this node are only used by the node, they will now be 663 // dead. Make sure to re-visit them and recursively delete dead nodes. 664 for (const SDValue &Op : N->ops()) 665 // For an operand generating multiple values, one of the values may 666 // become dead allowing further simplification (e.g. split index 667 // arithmetic from an indexed load). 668 if (Op->hasOneUse() || Op->getNumValues() > 1) 669 AddToWorklist(Op.getNode()); 670 671 DAG.DeleteNode(N); 672 } 673 674 /// Return 1 if we can compute the negated form of the specified expression for 675 /// the same cost as the expression itself, or 2 if we can compute the negated 676 /// form more cheaply than the expression itself. 677 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 678 const TargetLowering &TLI, 679 const TargetOptions *Options, 680 unsigned Depth = 0) { 681 // fneg is removable even if it has multiple uses. 682 if (Op.getOpcode() == ISD::FNEG) return 2; 683 684 // Don't allow anything with multiple uses unless we know it is free. 685 EVT VT = Op.getValueType(); 686 const SDNodeFlags Flags = Op->getFlags(); 687 if (!Op.hasOneUse()) 688 if (!(Op.getOpcode() == ISD::FP_EXTEND && 689 TLI.isFPExtFree(VT, Op.getOperand(0).getValueType()))) 690 return 0; 691 692 // Don't recurse exponentially. 693 if (Depth > 6) return 0; 694 695 switch (Op.getOpcode()) { 696 default: return false; 697 case ISD::ConstantFP: { 698 if (!LegalOperations) 699 return 1; 700 701 // Don't invert constant FP values after legalization unless the target says 702 // the negated constant is legal. 703 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 704 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 705 } 706 case ISD::FADD: 707 if (!Options->UnsafeFPMath && !Flags.hasNoSignedZeros()) 708 return 0; 709 710 // After operation legalization, it might not be legal to create new FSUBs. 711 if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 712 return 0; 713 714 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 715 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 716 Options, Depth + 1)) 717 return V; 718 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 719 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 720 Depth + 1); 721 case ISD::FSUB: 722 // We can't turn -(A-B) into B-A when we honor signed zeros. 723 if (!Options->NoSignedZerosFPMath && 724 !Flags.hasNoSignedZeros()) 725 return 0; 726 727 // fold (fneg (fsub A, B)) -> (fsub B, A) 728 return 1; 729 730 case ISD::FMUL: 731 case ISD::FDIV: 732 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 733 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 734 Options, Depth + 1)) 735 return V; 736 737 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 738 Depth + 1); 739 740 case ISD::FP_EXTEND: 741 case ISD::FP_ROUND: 742 case ISD::FSIN: 743 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 744 Depth + 1); 745 } 746 } 747 748 /// If isNegatibleForFree returns true, return the newly negated expression. 749 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 750 bool LegalOperations, unsigned Depth = 0) { 751 const TargetOptions &Options = DAG.getTarget().Options; 752 // fneg is removable even if it has multiple uses. 753 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 754 755 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 756 757 const SDNodeFlags Flags = Op.getNode()->getFlags(); 758 759 switch (Op.getOpcode()) { 760 default: llvm_unreachable("Unknown code"); 761 case ISD::ConstantFP: { 762 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 763 V.changeSign(); 764 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 765 } 766 case ISD::FADD: 767 assert(Options.UnsafeFPMath || Flags.hasNoSignedZeros()); 768 769 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 770 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 771 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 772 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 773 GetNegatedExpression(Op.getOperand(0), DAG, 774 LegalOperations, Depth+1), 775 Op.getOperand(1), Flags); 776 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 777 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 778 GetNegatedExpression(Op.getOperand(1), DAG, 779 LegalOperations, Depth+1), 780 Op.getOperand(0), Flags); 781 case ISD::FSUB: 782 // fold (fneg (fsub 0, B)) -> B 783 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 784 if (N0CFP->isZero()) 785 return Op.getOperand(1); 786 787 // fold (fneg (fsub A, B)) -> (fsub B, A) 788 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 789 Op.getOperand(1), Op.getOperand(0), Flags); 790 791 case ISD::FMUL: 792 case ISD::FDIV: 793 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 794 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 795 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 796 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 797 GetNegatedExpression(Op.getOperand(0), DAG, 798 LegalOperations, Depth+1), 799 Op.getOperand(1), Flags); 800 801 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 802 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 803 Op.getOperand(0), 804 GetNegatedExpression(Op.getOperand(1), DAG, 805 LegalOperations, Depth+1), Flags); 806 807 case ISD::FP_EXTEND: 808 case ISD::FSIN: 809 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 810 GetNegatedExpression(Op.getOperand(0), DAG, 811 LegalOperations, Depth+1)); 812 case ISD::FP_ROUND: 813 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 814 GetNegatedExpression(Op.getOperand(0), DAG, 815 LegalOperations, Depth+1), 816 Op.getOperand(1)); 817 } 818 } 819 820 // APInts must be the same size for most operations, this helper 821 // function zero extends the shorter of the pair so that they match. 822 // We provide an Offset so that we can create bitwidths that won't overflow. 823 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 824 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 825 LHS = LHS.zextOrSelf(Bits); 826 RHS = RHS.zextOrSelf(Bits); 827 } 828 829 // Return true if this node is a setcc, or is a select_cc 830 // that selects between the target values used for true and false, making it 831 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 832 // the appropriate nodes based on the type of node we are checking. This 833 // simplifies life a bit for the callers. 834 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 835 SDValue &CC) const { 836 if (N.getOpcode() == ISD::SETCC) { 837 LHS = N.getOperand(0); 838 RHS = N.getOperand(1); 839 CC = N.getOperand(2); 840 return true; 841 } 842 843 if (N.getOpcode() != ISD::SELECT_CC || 844 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 845 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 846 return false; 847 848 if (TLI.getBooleanContents(N.getValueType()) == 849 TargetLowering::UndefinedBooleanContent) 850 return false; 851 852 LHS = N.getOperand(0); 853 RHS = N.getOperand(1); 854 CC = N.getOperand(4); 855 return true; 856 } 857 858 /// Return true if this is a SetCC-equivalent operation with only one use. 859 /// If this is true, it allows the users to invert the operation for free when 860 /// it is profitable to do so. 861 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 862 SDValue N0, N1, N2; 863 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 864 return true; 865 return false; 866 } 867 868 static SDValue peekThroughBitcast(SDValue V) { 869 while (V.getOpcode() == ISD::BITCAST) 870 V = V.getOperand(0); 871 return V; 872 } 873 874 // Returns the SDNode if it is a constant float BuildVector 875 // or constant float. 876 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 877 if (isa<ConstantFPSDNode>(N)) 878 return N.getNode(); 879 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 880 return N.getNode(); 881 return nullptr; 882 } 883 884 // Determines if it is a constant integer or a build vector of constant 885 // integers (and undefs). 886 // Do not permit build vector implicit truncation. 887 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 888 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 889 return !(Const->isOpaque() && NoOpaques); 890 if (N.getOpcode() != ISD::BUILD_VECTOR) 891 return false; 892 unsigned BitWidth = N.getScalarValueSizeInBits(); 893 for (const SDValue &Op : N->op_values()) { 894 if (Op.isUndef()) 895 continue; 896 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 897 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 898 (Const->isOpaque() && NoOpaques)) 899 return false; 900 } 901 return true; 902 } 903 904 // Determines if it is a constant null integer or a splatted vector of a 905 // constant null integer (with no undefs). 906 // Build vector implicit truncation is not an issue for null values. 907 static bool isNullConstantOrNullSplatConstant(SDValue N) { 908 // TODO: may want to use peekThroughBitcast() here. 909 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 910 return Splat->isNullValue(); 911 return false; 912 } 913 914 // Determines if it is a constant integer of one or a splatted vector of a 915 // constant integer of one (with no undefs). 916 // Do not permit build vector implicit truncation. 917 static bool isOneConstantOrOneSplatConstant(SDValue N) { 918 // TODO: may want to use peekThroughBitcast() here. 919 unsigned BitWidth = N.getScalarValueSizeInBits(); 920 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 921 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 922 return false; 923 } 924 925 // Determines if it is a constant integer of all ones or a splatted vector of a 926 // constant integer of all ones (with no undefs). 927 // Do not permit build vector implicit truncation. 928 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 929 N = peekThroughBitcast(N); 930 unsigned BitWidth = N.getScalarValueSizeInBits(); 931 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 932 return Splat->isAllOnesValue() && 933 Splat->getAPIntValue().getBitWidth() == BitWidth; 934 return false; 935 } 936 937 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 938 // undef's. 939 static bool isAnyConstantBuildVector(const SDNode *N) { 940 return ISD::isBuildVectorOfConstantSDNodes(N) || 941 ISD::isBuildVectorOfConstantFPSDNodes(N); 942 } 943 944 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 945 SDValue N1, SDNodeFlags Flags) { 946 // Don't reassociate reductions. 947 if (Flags.hasVectorReduction()) 948 return SDValue(); 949 950 EVT VT = N0.getValueType(); 951 if (N0.getOpcode() == Opc && !N0->getFlags().hasVectorReduction()) { 952 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 953 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 954 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 955 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 956 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 957 return SDValue(); 958 } 959 if (N0.hasOneUse()) { 960 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 961 // use 962 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 963 if (!OpNode.getNode()) 964 return SDValue(); 965 AddToWorklist(OpNode.getNode()); 966 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 967 } 968 } 969 } 970 971 if (N1.getOpcode() == Opc && !N1->getFlags().hasVectorReduction()) { 972 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 973 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 974 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 975 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 976 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 977 return SDValue(); 978 } 979 if (N1.hasOneUse()) { 980 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 981 // use 982 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 983 if (!OpNode.getNode()) 984 return SDValue(); 985 AddToWorklist(OpNode.getNode()); 986 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 987 } 988 } 989 } 990 991 return SDValue(); 992 } 993 994 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 995 bool AddTo) { 996 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 997 ++NodesCombined; 998 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 999 To[0].getNode()->dump(&DAG); 1000 dbgs() << " and " << NumTo - 1 << " other values\n"); 1001 for (unsigned i = 0, e = NumTo; i != e; ++i) 1002 assert((!To[i].getNode() || 1003 N->getValueType(i) == To[i].getValueType()) && 1004 "Cannot combine value to value of different type!"); 1005 1006 WorklistRemover DeadNodes(*this); 1007 DAG.ReplaceAllUsesWith(N, To); 1008 if (AddTo) { 1009 // Push the new nodes and any users onto the worklist 1010 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1011 if (To[i].getNode()) { 1012 AddToWorklist(To[i].getNode()); 1013 AddUsersToWorklist(To[i].getNode()); 1014 } 1015 } 1016 } 1017 1018 // Finally, if the node is now dead, remove it from the graph. The node 1019 // may not be dead if the replacement process recursively simplified to 1020 // something else needing this node. 1021 if (N->use_empty()) 1022 deleteAndRecombine(N); 1023 return SDValue(N, 0); 1024 } 1025 1026 void DAGCombiner:: 1027 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1028 // Replace all uses. If any nodes become isomorphic to other nodes and 1029 // are deleted, make sure to remove them from our worklist. 1030 WorklistRemover DeadNodes(*this); 1031 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1032 1033 // Push the new node and any (possibly new) users onto the worklist. 1034 AddToWorklist(TLO.New.getNode()); 1035 AddUsersToWorklist(TLO.New.getNode()); 1036 1037 // Finally, if the node is now dead, remove it from the graph. The node 1038 // may not be dead if the replacement process recursively simplified to 1039 // something else needing this node. 1040 if (TLO.Old.getNode()->use_empty()) 1041 deleteAndRecombine(TLO.Old.getNode()); 1042 } 1043 1044 /// Check the specified integer node value to see if it can be simplified or if 1045 /// things it uses can be simplified by bit propagation. If so, return true. 1046 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1047 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1048 KnownBits Known; 1049 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1050 return false; 1051 1052 // Revisit the node. 1053 AddToWorklist(Op.getNode()); 1054 1055 // Replace the old value with the new one. 1056 ++NodesCombined; 1057 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1058 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1059 dbgs() << '\n'); 1060 1061 CommitTargetLoweringOpt(TLO); 1062 return true; 1063 } 1064 1065 /// Check the specified vector node value to see if it can be simplified or 1066 /// if things it uses can be simplified as it only uses some of the elements. 1067 /// If so, return true. 1068 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded, 1069 bool AssumeSingleUse) { 1070 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1071 APInt KnownUndef, KnownZero; 1072 if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO, 1073 0, AssumeSingleUse)) 1074 return false; 1075 1076 // Revisit the node. 1077 AddToWorklist(Op.getNode()); 1078 1079 // Replace the old value with the new one. 1080 ++NodesCombined; 1081 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1082 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1083 dbgs() << '\n'); 1084 1085 CommitTargetLoweringOpt(TLO); 1086 return true; 1087 } 1088 1089 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1090 SDLoc DL(Load); 1091 EVT VT = Load->getValueType(0); 1092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1093 1094 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1095 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1096 WorklistRemover DeadNodes(*this); 1097 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1098 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1099 deleteAndRecombine(Load); 1100 AddToWorklist(Trunc.getNode()); 1101 } 1102 1103 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1104 Replace = false; 1105 SDLoc DL(Op); 1106 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1107 LoadSDNode *LD = cast<LoadSDNode>(Op); 1108 EVT MemVT = LD->getMemoryVT(); 1109 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1110 : LD->getExtensionType(); 1111 Replace = true; 1112 return DAG.getExtLoad(ExtType, DL, PVT, 1113 LD->getChain(), LD->getBasePtr(), 1114 MemVT, LD->getMemOperand()); 1115 } 1116 1117 unsigned Opc = Op.getOpcode(); 1118 switch (Opc) { 1119 default: break; 1120 case ISD::AssertSext: 1121 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1122 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1123 break; 1124 case ISD::AssertZext: 1125 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1126 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1127 break; 1128 case ISD::Constant: { 1129 unsigned ExtOpc = 1130 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1131 return DAG.getNode(ExtOpc, DL, PVT, Op); 1132 } 1133 } 1134 1135 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1136 return SDValue(); 1137 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1138 } 1139 1140 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1141 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1142 return SDValue(); 1143 EVT OldVT = Op.getValueType(); 1144 SDLoc DL(Op); 1145 bool Replace = false; 1146 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1147 if (!NewOp.getNode()) 1148 return SDValue(); 1149 AddToWorklist(NewOp.getNode()); 1150 1151 if (Replace) 1152 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1153 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1154 DAG.getValueType(OldVT)); 1155 } 1156 1157 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1158 EVT OldVT = Op.getValueType(); 1159 SDLoc DL(Op); 1160 bool Replace = false; 1161 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1162 if (!NewOp.getNode()) 1163 return SDValue(); 1164 AddToWorklist(NewOp.getNode()); 1165 1166 if (Replace) 1167 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1168 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1169 } 1170 1171 /// Promote the specified integer binary operation if the target indicates it is 1172 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1173 /// i32 since i16 instructions are longer. 1174 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1175 if (!LegalOperations) 1176 return SDValue(); 1177 1178 EVT VT = Op.getValueType(); 1179 if (VT.isVector() || !VT.isInteger()) 1180 return SDValue(); 1181 1182 // If operation type is 'undesirable', e.g. i16 on x86, consider 1183 // promoting it. 1184 unsigned Opc = Op.getOpcode(); 1185 if (TLI.isTypeDesirableForOp(Opc, VT)) 1186 return SDValue(); 1187 1188 EVT PVT = VT; 1189 // Consult target whether it is a good idea to promote this operation and 1190 // what's the right type to promote it to. 1191 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1192 assert(PVT != VT && "Don't know what type to promote to!"); 1193 1194 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1195 1196 bool Replace0 = false; 1197 SDValue N0 = Op.getOperand(0); 1198 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1199 1200 bool Replace1 = false; 1201 SDValue N1 = Op.getOperand(1); 1202 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1203 SDLoc DL(Op); 1204 1205 SDValue RV = 1206 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1207 1208 // We are always replacing N0/N1's use in N and only need 1209 // additional replacements if there are additional uses. 1210 Replace0 &= !N0->hasOneUse(); 1211 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1212 1213 // Combine Op here so it is preserved past replacements. 1214 CombineTo(Op.getNode(), RV); 1215 1216 // If operands have a use ordering, make sure we deal with 1217 // predecessor first. 1218 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1219 std::swap(N0, N1); 1220 std::swap(NN0, NN1); 1221 } 1222 1223 if (Replace0) { 1224 AddToWorklist(NN0.getNode()); 1225 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1226 } 1227 if (Replace1) { 1228 AddToWorklist(NN1.getNode()); 1229 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1230 } 1231 return Op; 1232 } 1233 return SDValue(); 1234 } 1235 1236 /// Promote the specified integer shift operation if the target indicates it is 1237 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1238 /// i32 since i16 instructions are longer. 1239 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1240 if (!LegalOperations) 1241 return SDValue(); 1242 1243 EVT VT = Op.getValueType(); 1244 if (VT.isVector() || !VT.isInteger()) 1245 return SDValue(); 1246 1247 // If operation type is 'undesirable', e.g. i16 on x86, consider 1248 // promoting it. 1249 unsigned Opc = Op.getOpcode(); 1250 if (TLI.isTypeDesirableForOp(Opc, VT)) 1251 return SDValue(); 1252 1253 EVT PVT = VT; 1254 // Consult target whether it is a good idea to promote this operation and 1255 // what's the right type to promote it to. 1256 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1257 assert(PVT != VT && "Don't know what type to promote to!"); 1258 1259 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1260 1261 bool Replace = false; 1262 SDValue N0 = Op.getOperand(0); 1263 SDValue N1 = Op.getOperand(1); 1264 if (Opc == ISD::SRA) 1265 N0 = SExtPromoteOperand(N0, PVT); 1266 else if (Opc == ISD::SRL) 1267 N0 = ZExtPromoteOperand(N0, PVT); 1268 else 1269 N0 = PromoteOperand(N0, PVT, Replace); 1270 1271 if (!N0.getNode()) 1272 return SDValue(); 1273 1274 SDLoc DL(Op); 1275 SDValue RV = 1276 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1277 1278 AddToWorklist(N0.getNode()); 1279 if (Replace) 1280 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1281 1282 // Deal with Op being deleted. 1283 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1284 return RV; 1285 } 1286 return SDValue(); 1287 } 1288 1289 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1290 if (!LegalOperations) 1291 return SDValue(); 1292 1293 EVT VT = Op.getValueType(); 1294 if (VT.isVector() || !VT.isInteger()) 1295 return SDValue(); 1296 1297 // If operation type is 'undesirable', e.g. i16 on x86, consider 1298 // promoting it. 1299 unsigned Opc = Op.getOpcode(); 1300 if (TLI.isTypeDesirableForOp(Opc, VT)) 1301 return SDValue(); 1302 1303 EVT PVT = VT; 1304 // Consult target whether it is a good idea to promote this operation and 1305 // what's the right type to promote it to. 1306 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1307 assert(PVT != VT && "Don't know what type to promote to!"); 1308 // fold (aext (aext x)) -> (aext x) 1309 // fold (aext (zext x)) -> (zext x) 1310 // fold (aext (sext x)) -> (sext x) 1311 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1312 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1313 } 1314 return SDValue(); 1315 } 1316 1317 bool DAGCombiner::PromoteLoad(SDValue Op) { 1318 if (!LegalOperations) 1319 return false; 1320 1321 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1322 return false; 1323 1324 EVT VT = Op.getValueType(); 1325 if (VT.isVector() || !VT.isInteger()) 1326 return false; 1327 1328 // If operation type is 'undesirable', e.g. i16 on x86, consider 1329 // promoting it. 1330 unsigned Opc = Op.getOpcode(); 1331 if (TLI.isTypeDesirableForOp(Opc, VT)) 1332 return false; 1333 1334 EVT PVT = VT; 1335 // Consult target whether it is a good idea to promote this operation and 1336 // what's the right type to promote it to. 1337 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1338 assert(PVT != VT && "Don't know what type to promote to!"); 1339 1340 SDLoc DL(Op); 1341 SDNode *N = Op.getNode(); 1342 LoadSDNode *LD = cast<LoadSDNode>(N); 1343 EVT MemVT = LD->getMemoryVT(); 1344 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1345 : LD->getExtensionType(); 1346 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1347 LD->getChain(), LD->getBasePtr(), 1348 MemVT, LD->getMemOperand()); 1349 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1350 1351 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1352 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1353 WorklistRemover DeadNodes(*this); 1354 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1355 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1356 deleteAndRecombine(N); 1357 AddToWorklist(Result.getNode()); 1358 return true; 1359 } 1360 return false; 1361 } 1362 1363 /// Recursively delete a node which has no uses and any operands for 1364 /// which it is the only use. 1365 /// 1366 /// Note that this both deletes the nodes and removes them from the worklist. 1367 /// It also adds any nodes who have had a user deleted to the worklist as they 1368 /// may now have only one use and subject to other combines. 1369 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1370 if (!N->use_empty()) 1371 return false; 1372 1373 SmallSetVector<SDNode *, 16> Nodes; 1374 Nodes.insert(N); 1375 do { 1376 N = Nodes.pop_back_val(); 1377 if (!N) 1378 continue; 1379 1380 if (N->use_empty()) { 1381 for (const SDValue &ChildN : N->op_values()) 1382 Nodes.insert(ChildN.getNode()); 1383 1384 removeFromWorklist(N); 1385 DAG.DeleteNode(N); 1386 } else { 1387 AddToWorklist(N); 1388 } 1389 } while (!Nodes.empty()); 1390 return true; 1391 } 1392 1393 //===----------------------------------------------------------------------===// 1394 // Main DAG Combiner implementation 1395 //===----------------------------------------------------------------------===// 1396 1397 void DAGCombiner::Run(CombineLevel AtLevel) { 1398 // set the instance variables, so that the various visit routines may use it. 1399 Level = AtLevel; 1400 LegalOperations = Level >= AfterLegalizeVectorOps; 1401 LegalTypes = Level >= AfterLegalizeTypes; 1402 1403 // Add all the dag nodes to the worklist. 1404 for (SDNode &Node : DAG.allnodes()) 1405 AddToWorklist(&Node); 1406 1407 // Create a dummy node (which is not added to allnodes), that adds a reference 1408 // to the root node, preventing it from being deleted, and tracking any 1409 // changes of the root. 1410 HandleSDNode Dummy(DAG.getRoot()); 1411 1412 // While the worklist isn't empty, find a node and try to combine it. 1413 while (!WorklistMap.empty()) { 1414 SDNode *N; 1415 // The Worklist holds the SDNodes in order, but it may contain null entries. 1416 do { 1417 N = Worklist.pop_back_val(); 1418 } while (!N); 1419 1420 bool GoodWorklistEntry = WorklistMap.erase(N); 1421 (void)GoodWorklistEntry; 1422 assert(GoodWorklistEntry && 1423 "Found a worklist entry without a corresponding map entry!"); 1424 1425 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1426 // N is deleted from the DAG, since they too may now be dead or may have a 1427 // reduced number of uses, allowing other xforms. 1428 if (recursivelyDeleteUnusedNodes(N)) 1429 continue; 1430 1431 WorklistRemover DeadNodes(*this); 1432 1433 // If this combine is running after legalizing the DAG, re-legalize any 1434 // nodes pulled off the worklist. 1435 if (Level == AfterLegalizeDAG) { 1436 SmallSetVector<SDNode *, 16> UpdatedNodes; 1437 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1438 1439 for (SDNode *LN : UpdatedNodes) { 1440 AddToWorklist(LN); 1441 AddUsersToWorklist(LN); 1442 } 1443 if (!NIsValid) 1444 continue; 1445 } 1446 1447 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1448 1449 // Add any operands of the new node which have not yet been combined to the 1450 // worklist as well. Because the worklist uniques things already, this 1451 // won't repeatedly process the same operand. 1452 CombinedNodes.insert(N); 1453 for (const SDValue &ChildN : N->op_values()) 1454 if (!CombinedNodes.count(ChildN.getNode())) 1455 AddToWorklist(ChildN.getNode()); 1456 1457 SDValue RV = combine(N); 1458 1459 if (!RV.getNode()) 1460 continue; 1461 1462 ++NodesCombined; 1463 1464 // If we get back the same node we passed in, rather than a new node or 1465 // zero, we know that the node must have defined multiple values and 1466 // CombineTo was used. Since CombineTo takes care of the worklist 1467 // mechanics for us, we have no work to do in this case. 1468 if (RV.getNode() == N) 1469 continue; 1470 1471 assert(N->getOpcode() != ISD::DELETED_NODE && 1472 RV.getOpcode() != ISD::DELETED_NODE && 1473 "Node was deleted but visit returned new node!"); 1474 1475 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1476 1477 if (N->getNumValues() == RV.getNode()->getNumValues()) 1478 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1479 else { 1480 assert(N->getValueType(0) == RV.getValueType() && 1481 N->getNumValues() == 1 && "Type mismatch"); 1482 DAG.ReplaceAllUsesWith(N, &RV); 1483 } 1484 1485 // Push the new node and any users onto the worklist 1486 AddToWorklist(RV.getNode()); 1487 AddUsersToWorklist(RV.getNode()); 1488 1489 // Finally, if the node is now dead, remove it from the graph. The node 1490 // may not be dead if the replacement process recursively simplified to 1491 // something else needing this node. This will also take care of adding any 1492 // operands which have lost a user to the worklist. 1493 recursivelyDeleteUnusedNodes(N); 1494 } 1495 1496 // If the root changed (e.g. it was a dead load, update the root). 1497 DAG.setRoot(Dummy.getValue()); 1498 DAG.RemoveDeadNodes(); 1499 } 1500 1501 SDValue DAGCombiner::visit(SDNode *N) { 1502 switch (N->getOpcode()) { 1503 default: break; 1504 case ISD::TokenFactor: return visitTokenFactor(N); 1505 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1506 case ISD::ADD: return visitADD(N); 1507 case ISD::SUB: return visitSUB(N); 1508 case ISD::ADDC: return visitADDC(N); 1509 case ISD::UADDO: return visitUADDO(N); 1510 case ISD::SUBC: return visitSUBC(N); 1511 case ISD::USUBO: return visitUSUBO(N); 1512 case ISD::ADDE: return visitADDE(N); 1513 case ISD::ADDCARRY: return visitADDCARRY(N); 1514 case ISD::SUBE: return visitSUBE(N); 1515 case ISD::SUBCARRY: return visitSUBCARRY(N); 1516 case ISD::MUL: return visitMUL(N); 1517 case ISD::SDIV: return visitSDIV(N); 1518 case ISD::UDIV: return visitUDIV(N); 1519 case ISD::SREM: 1520 case ISD::UREM: return visitREM(N); 1521 case ISD::MULHU: return visitMULHU(N); 1522 case ISD::MULHS: return visitMULHS(N); 1523 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1524 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1525 case ISD::SMULO: return visitSMULO(N); 1526 case ISD::UMULO: return visitUMULO(N); 1527 case ISD::SMIN: 1528 case ISD::SMAX: 1529 case ISD::UMIN: 1530 case ISD::UMAX: return visitIMINMAX(N); 1531 case ISD::AND: return visitAND(N); 1532 case ISD::OR: return visitOR(N); 1533 case ISD::XOR: return visitXOR(N); 1534 case ISD::SHL: return visitSHL(N); 1535 case ISD::SRA: return visitSRA(N); 1536 case ISD::SRL: return visitSRL(N); 1537 case ISD::ROTR: 1538 case ISD::ROTL: return visitRotate(N); 1539 case ISD::ABS: return visitABS(N); 1540 case ISD::BSWAP: return visitBSWAP(N); 1541 case ISD::BITREVERSE: return visitBITREVERSE(N); 1542 case ISD::CTLZ: return visitCTLZ(N); 1543 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1544 case ISD::CTTZ: return visitCTTZ(N); 1545 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1546 case ISD::CTPOP: return visitCTPOP(N); 1547 case ISD::SELECT: return visitSELECT(N); 1548 case ISD::VSELECT: return visitVSELECT(N); 1549 case ISD::SELECT_CC: return visitSELECT_CC(N); 1550 case ISD::SETCC: return visitSETCC(N); 1551 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1552 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1553 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1554 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1555 case ISD::AssertSext: 1556 case ISD::AssertZext: return visitAssertExt(N); 1557 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1558 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1559 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1560 case ISD::TRUNCATE: return visitTRUNCATE(N); 1561 case ISD::BITCAST: return visitBITCAST(N); 1562 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1563 case ISD::FADD: return visitFADD(N); 1564 case ISD::FSUB: return visitFSUB(N); 1565 case ISD::FMUL: return visitFMUL(N); 1566 case ISD::FMA: return visitFMA(N); 1567 case ISD::FDIV: return visitFDIV(N); 1568 case ISD::FREM: return visitFREM(N); 1569 case ISD::FSQRT: return visitFSQRT(N); 1570 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1571 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1572 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1573 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1574 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1575 case ISD::FP_ROUND: return visitFP_ROUND(N); 1576 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1577 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1578 case ISD::FNEG: return visitFNEG(N); 1579 case ISD::FABS: return visitFABS(N); 1580 case ISD::FFLOOR: return visitFFLOOR(N); 1581 case ISD::FMINNUM: return visitFMINNUM(N); 1582 case ISD::FMAXNUM: return visitFMAXNUM(N); 1583 case ISD::FCEIL: return visitFCEIL(N); 1584 case ISD::FTRUNC: return visitFTRUNC(N); 1585 case ISD::BRCOND: return visitBRCOND(N); 1586 case ISD::BR_CC: return visitBR_CC(N); 1587 case ISD::LOAD: return visitLOAD(N); 1588 case ISD::STORE: return visitSTORE(N); 1589 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1590 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1591 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1592 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1593 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1594 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1595 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1596 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1597 case ISD::MGATHER: return visitMGATHER(N); 1598 case ISD::MLOAD: return visitMLOAD(N); 1599 case ISD::MSCATTER: return visitMSCATTER(N); 1600 case ISD::MSTORE: return visitMSTORE(N); 1601 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1602 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1603 } 1604 return SDValue(); 1605 } 1606 1607 SDValue DAGCombiner::combine(SDNode *N) { 1608 SDValue RV = visit(N); 1609 1610 // If nothing happened, try a target-specific DAG combine. 1611 if (!RV.getNode()) { 1612 assert(N->getOpcode() != ISD::DELETED_NODE && 1613 "Node was deleted but visit returned NULL!"); 1614 1615 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1616 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1617 1618 // Expose the DAG combiner to the target combiner impls. 1619 TargetLowering::DAGCombinerInfo 1620 DagCombineInfo(DAG, Level, false, this); 1621 1622 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1623 } 1624 } 1625 1626 // If nothing happened still, try promoting the operation. 1627 if (!RV.getNode()) { 1628 switch (N->getOpcode()) { 1629 default: break; 1630 case ISD::ADD: 1631 case ISD::SUB: 1632 case ISD::MUL: 1633 case ISD::AND: 1634 case ISD::OR: 1635 case ISD::XOR: 1636 RV = PromoteIntBinOp(SDValue(N, 0)); 1637 break; 1638 case ISD::SHL: 1639 case ISD::SRA: 1640 case ISD::SRL: 1641 RV = PromoteIntShiftOp(SDValue(N, 0)); 1642 break; 1643 case ISD::SIGN_EXTEND: 1644 case ISD::ZERO_EXTEND: 1645 case ISD::ANY_EXTEND: 1646 RV = PromoteExtend(SDValue(N, 0)); 1647 break; 1648 case ISD::LOAD: 1649 if (PromoteLoad(SDValue(N, 0))) 1650 RV = SDValue(N, 0); 1651 break; 1652 } 1653 } 1654 1655 // If N is a commutative binary node, try eliminate it if the commuted 1656 // version is already present in the DAG. 1657 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1658 N->getNumValues() == 1) { 1659 SDValue N0 = N->getOperand(0); 1660 SDValue N1 = N->getOperand(1); 1661 1662 // Constant operands are canonicalized to RHS. 1663 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1664 SDValue Ops[] = {N1, N0}; 1665 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1666 N->getFlags()); 1667 if (CSENode) 1668 return SDValue(CSENode, 0); 1669 } 1670 } 1671 1672 return RV; 1673 } 1674 1675 /// Given a node, return its input chain if it has one, otherwise return a null 1676 /// sd operand. 1677 static SDValue getInputChainForNode(SDNode *N) { 1678 if (unsigned NumOps = N->getNumOperands()) { 1679 if (N->getOperand(0).getValueType() == MVT::Other) 1680 return N->getOperand(0); 1681 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1682 return N->getOperand(NumOps-1); 1683 for (unsigned i = 1; i < NumOps-1; ++i) 1684 if (N->getOperand(i).getValueType() == MVT::Other) 1685 return N->getOperand(i); 1686 } 1687 return SDValue(); 1688 } 1689 1690 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1691 // If N has two operands, where one has an input chain equal to the other, 1692 // the 'other' chain is redundant. 1693 if (N->getNumOperands() == 2) { 1694 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1695 return N->getOperand(0); 1696 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1697 return N->getOperand(1); 1698 } 1699 1700 // Don't simplify token factors if optnone. 1701 if (OptLevel == CodeGenOpt::None) 1702 return SDValue(); 1703 1704 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1705 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1706 SmallPtrSet<SDNode*, 16> SeenOps; 1707 bool Changed = false; // If we should replace this token factor. 1708 1709 // Start out with this token factor. 1710 TFs.push_back(N); 1711 1712 // Iterate through token factors. The TFs grows when new token factors are 1713 // encountered. 1714 for (unsigned i = 0; i < TFs.size(); ++i) { 1715 SDNode *TF = TFs[i]; 1716 1717 // Check each of the operands. 1718 for (const SDValue &Op : TF->op_values()) { 1719 switch (Op.getOpcode()) { 1720 case ISD::EntryToken: 1721 // Entry tokens don't need to be added to the list. They are 1722 // redundant. 1723 Changed = true; 1724 break; 1725 1726 case ISD::TokenFactor: 1727 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1728 // Queue up for processing. 1729 TFs.push_back(Op.getNode()); 1730 // Clean up in case the token factor is removed. 1731 AddToWorklist(Op.getNode()); 1732 Changed = true; 1733 break; 1734 } 1735 LLVM_FALLTHROUGH; 1736 1737 default: 1738 // Only add if it isn't already in the list. 1739 if (SeenOps.insert(Op.getNode()).second) 1740 Ops.push_back(Op); 1741 else 1742 Changed = true; 1743 break; 1744 } 1745 } 1746 } 1747 1748 // Remove Nodes that are chained to another node in the list. Do so 1749 // by walking up chains breath-first stopping when we've seen 1750 // another operand. In general we must climb to the EntryNode, but we can exit 1751 // early if we find all remaining work is associated with just one operand as 1752 // no further pruning is possible. 1753 1754 // List of nodes to search through and original Ops from which they originate. 1755 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1756 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1757 SmallPtrSet<SDNode *, 16> SeenChains; 1758 bool DidPruneOps = false; 1759 1760 unsigned NumLeftToConsider = 0; 1761 for (const SDValue &Op : Ops) { 1762 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1763 OpWorkCount.push_back(1); 1764 } 1765 1766 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1767 // If this is an Op, we can remove the op from the list. Remark any 1768 // search associated with it as from the current OpNumber. 1769 if (SeenOps.count(Op) != 0) { 1770 Changed = true; 1771 DidPruneOps = true; 1772 unsigned OrigOpNumber = 0; 1773 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1774 OrigOpNumber++; 1775 assert((OrigOpNumber != Ops.size()) && 1776 "expected to find TokenFactor Operand"); 1777 // Re-mark worklist from OrigOpNumber to OpNumber 1778 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1779 if (Worklist[i].second == OrigOpNumber) { 1780 Worklist[i].second = OpNumber; 1781 } 1782 } 1783 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1784 OpWorkCount[OrigOpNumber] = 0; 1785 NumLeftToConsider--; 1786 } 1787 // Add if it's a new chain 1788 if (SeenChains.insert(Op).second) { 1789 OpWorkCount[OpNumber]++; 1790 Worklist.push_back(std::make_pair(Op, OpNumber)); 1791 } 1792 }; 1793 1794 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1795 // We need at least be consider at least 2 Ops to prune. 1796 if (NumLeftToConsider <= 1) 1797 break; 1798 auto CurNode = Worklist[i].first; 1799 auto CurOpNumber = Worklist[i].second; 1800 assert((OpWorkCount[CurOpNumber] > 0) && 1801 "Node should not appear in worklist"); 1802 switch (CurNode->getOpcode()) { 1803 case ISD::EntryToken: 1804 // Hitting EntryToken is the only way for the search to terminate without 1805 // hitting 1806 // another operand's search. Prevent us from marking this operand 1807 // considered. 1808 NumLeftToConsider++; 1809 break; 1810 case ISD::TokenFactor: 1811 for (const SDValue &Op : CurNode->op_values()) 1812 AddToWorklist(i, Op.getNode(), CurOpNumber); 1813 break; 1814 case ISD::CopyFromReg: 1815 case ISD::CopyToReg: 1816 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1817 break; 1818 default: 1819 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1820 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1821 break; 1822 } 1823 OpWorkCount[CurOpNumber]--; 1824 if (OpWorkCount[CurOpNumber] == 0) 1825 NumLeftToConsider--; 1826 } 1827 1828 // If we've changed things around then replace token factor. 1829 if (Changed) { 1830 SDValue Result; 1831 if (Ops.empty()) { 1832 // The entry token is the only possible outcome. 1833 Result = DAG.getEntryNode(); 1834 } else { 1835 if (DidPruneOps) { 1836 SmallVector<SDValue, 8> PrunedOps; 1837 // 1838 for (const SDValue &Op : Ops) { 1839 if (SeenChains.count(Op.getNode()) == 0) 1840 PrunedOps.push_back(Op); 1841 } 1842 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1843 } else { 1844 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1845 } 1846 } 1847 return Result; 1848 } 1849 return SDValue(); 1850 } 1851 1852 /// MERGE_VALUES can always be eliminated. 1853 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1854 WorklistRemover DeadNodes(*this); 1855 // Replacing results may cause a different MERGE_VALUES to suddenly 1856 // be CSE'd with N, and carry its uses with it. Iterate until no 1857 // uses remain, to ensure that the node can be safely deleted. 1858 // First add the users of this node to the work list so that they 1859 // can be tried again once they have new operands. 1860 AddUsersToWorklist(N); 1861 do { 1862 // Do as a single replacement to avoid rewalking use lists. 1863 SmallVector<SDValue, 8> Ops; 1864 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1865 Ops.push_back(N->getOperand(i)); 1866 DAG.ReplaceAllUsesWith(N, Ops.data()); 1867 } while (!N->use_empty()); 1868 deleteAndRecombine(N); 1869 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1870 } 1871 1872 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1873 /// ConstantSDNode pointer else nullptr. 1874 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1875 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1876 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1877 } 1878 1879 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1880 assert(ISD::isBinaryOp(BO) && "Unexpected binary operator"); 1881 1882 // Don't do this unless the old select is going away. We want to eliminate the 1883 // binary operator, not replace a binop with a select. 1884 // TODO: Handle ISD::SELECT_CC. 1885 unsigned SelOpNo = 0; 1886 SDValue Sel = BO->getOperand(0); 1887 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 1888 SelOpNo = 1; 1889 Sel = BO->getOperand(1); 1890 } 1891 1892 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1893 return SDValue(); 1894 1895 SDValue CT = Sel.getOperand(1); 1896 if (!isConstantOrConstantVector(CT, true) && 1897 !isConstantFPBuildVectorOrConstantFP(CT)) 1898 return SDValue(); 1899 1900 SDValue CF = Sel.getOperand(2); 1901 if (!isConstantOrConstantVector(CF, true) && 1902 !isConstantFPBuildVectorOrConstantFP(CF)) 1903 return SDValue(); 1904 1905 // Bail out if any constants are opaque because we can't constant fold those. 1906 // The exception is "and" and "or" with either 0 or -1 in which case we can 1907 // propagate non constant operands into select. I.e.: 1908 // and (select Cond, 0, -1), X --> select Cond, 0, X 1909 // or X, (select Cond, -1, 0) --> select Cond, -1, X 1910 auto BinOpcode = BO->getOpcode(); 1911 bool CanFoldNonConst = (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 1912 (isNullConstantOrNullSplatConstant(CT) || 1913 isAllOnesConstantOrAllOnesSplatConstant(CT)) && 1914 (isNullConstantOrNullSplatConstant(CF) || 1915 isAllOnesConstantOrAllOnesSplatConstant(CF)); 1916 1917 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 1918 if (!CanFoldNonConst && 1919 !isConstantOrConstantVector(CBO, true) && 1920 !isConstantFPBuildVectorOrConstantFP(CBO)) 1921 return SDValue(); 1922 1923 EVT VT = Sel.getValueType(); 1924 1925 // In case of shift value and shift amount may have different VT. For instance 1926 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have 1927 // swapped operands and value types do not match. NB: x86 is fine if operands 1928 // are not swapped with shift amount VT being not bigger than shifted value. 1929 // TODO: that is possible to check for a shift operation, correct VTs and 1930 // still perform optimization on x86 if needed. 1931 if (SelOpNo && VT != CBO.getValueType()) 1932 return SDValue(); 1933 1934 // We have a select-of-constants followed by a binary operator with a 1935 // constant. Eliminate the binop by pulling the constant math into the select. 1936 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 1937 SDLoc DL(Sel); 1938 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 1939 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 1940 if (!CanFoldNonConst && !NewCT.isUndef() && 1941 !isConstantOrConstantVector(NewCT, true) && 1942 !isConstantFPBuildVectorOrConstantFP(NewCT)) 1943 return SDValue(); 1944 1945 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 1946 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 1947 if (!CanFoldNonConst && !NewCF.isUndef() && 1948 !isConstantOrConstantVector(NewCF, true) && 1949 !isConstantFPBuildVectorOrConstantFP(NewCF)) 1950 return SDValue(); 1951 1952 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1953 } 1954 1955 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 1956 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 1957 "Expecting add or sub"); 1958 1959 // Match a constant operand and a zext operand for the math instruction: 1960 // add Z, C 1961 // sub C, Z 1962 bool IsAdd = N->getOpcode() == ISD::ADD; 1963 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 1964 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 1965 auto *CN = dyn_cast<ConstantSDNode>(C); 1966 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 1967 return SDValue(); 1968 1969 // Match the zext operand as a setcc of a boolean. 1970 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 1971 Z.getOperand(0).getValueType() != MVT::i1) 1972 return SDValue(); 1973 1974 // Match the compare as: setcc (X & 1), 0, eq. 1975 SDValue SetCC = Z.getOperand(0); 1976 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 1977 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 1978 SetCC.getOperand(0).getOpcode() != ISD::AND || 1979 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 1980 return SDValue(); 1981 1982 // We are adding/subtracting a constant and an inverted low bit. Turn that 1983 // into a subtract/add of the low bit with incremented/decremented constant: 1984 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 1985 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 1986 EVT VT = C.getValueType(); 1987 SDLoc DL(N); 1988 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 1989 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 1990 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 1991 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 1992 } 1993 1994 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 1995 /// a shift and add with a different constant. 1996 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 1997 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 1998 "Expecting add or sub"); 1999 2000 // We need a constant operand for the add/sub, and the other operand is a 2001 // logical shift right: add (srl), C or sub C, (srl). 2002 bool IsAdd = N->getOpcode() == ISD::ADD; 2003 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2004 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2005 ConstantSDNode *C = isConstOrConstSplat(ConstantOp); 2006 if (!C || ShiftOp.getOpcode() != ISD::SRL) 2007 return SDValue(); 2008 2009 // The shift must be of a 'not' value. 2010 // TODO: Use isBitwiseNot() if it works with vectors. 2011 SDValue Not = ShiftOp.getOperand(0); 2012 if (!Not.hasOneUse() || Not.getOpcode() != ISD::XOR || 2013 !isAllOnesConstantOrAllOnesSplatConstant(Not.getOperand(1))) 2014 return SDValue(); 2015 2016 // The shift must be moving the sign bit to the least-significant-bit. 2017 EVT VT = ShiftOp.getValueType(); 2018 SDValue ShAmt = ShiftOp.getOperand(1); 2019 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2020 if (!ShAmtC || ShAmtC->getZExtValue() != VT.getScalarSizeInBits() - 1) 2021 return SDValue(); 2022 2023 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2024 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2025 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2026 SDLoc DL(N); 2027 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2028 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2029 APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1; 2030 return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT)); 2031 } 2032 2033 SDValue DAGCombiner::visitADD(SDNode *N) { 2034 SDValue N0 = N->getOperand(0); 2035 SDValue N1 = N->getOperand(1); 2036 EVT VT = N0.getValueType(); 2037 SDLoc DL(N); 2038 2039 // fold vector ops 2040 if (VT.isVector()) { 2041 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2042 return FoldedVOp; 2043 2044 // fold (add x, 0) -> x, vector edition 2045 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2046 return N0; 2047 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2048 return N1; 2049 } 2050 2051 // fold (add x, undef) -> undef 2052 if (N0.isUndef()) 2053 return N0; 2054 2055 if (N1.isUndef()) 2056 return N1; 2057 2058 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2059 // canonicalize constant to RHS 2060 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2061 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2062 // fold (add c1, c2) -> c1+c2 2063 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 2064 N1.getNode()); 2065 } 2066 2067 // fold (add x, 0) -> x 2068 if (isNullConstant(N1)) 2069 return N0; 2070 2071 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2072 // fold ((c1-A)+c2) -> (c1+c2)-A 2073 if (N0.getOpcode() == ISD::SUB && 2074 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2075 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 2076 return DAG.getNode(ISD::SUB, DL, VT, 2077 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 2078 N0.getOperand(1)); 2079 } 2080 2081 // add (sext i1 X), 1 -> zext (not i1 X) 2082 // We don't transform this pattern: 2083 // add (zext i1 X), -1 -> sext (not i1 X) 2084 // because most (?) targets generate better code for the zext form. 2085 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2086 isOneConstantOrOneSplatConstant(N1)) { 2087 SDValue X = N0.getOperand(0); 2088 if ((!LegalOperations || 2089 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2090 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2091 X.getScalarValueSizeInBits() == 1) { 2092 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2093 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2094 } 2095 } 2096 2097 // Undo the add -> or combine to merge constant offsets from a frame index. 2098 if (N0.getOpcode() == ISD::OR && 2099 isa<FrameIndexSDNode>(N0.getOperand(0)) && 2100 isa<ConstantSDNode>(N0.getOperand(1)) && 2101 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2102 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 2103 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2104 } 2105 } 2106 2107 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2108 return NewSel; 2109 2110 // reassociate add 2111 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) 2112 return RADD; 2113 2114 // fold ((0-A) + B) -> B-A 2115 if (N0.getOpcode() == ISD::SUB && 2116 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2117 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2118 2119 // fold (A + (0-B)) -> A-B 2120 if (N1.getOpcode() == ISD::SUB && 2121 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2122 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2123 2124 // fold (A+(B-A)) -> B 2125 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2126 return N1.getOperand(0); 2127 2128 // fold ((B-A)+A) -> B 2129 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2130 return N0.getOperand(0); 2131 2132 // fold (A+(B-(A+C))) to (B-C) 2133 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2134 N0 == N1.getOperand(1).getOperand(0)) 2135 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2136 N1.getOperand(1).getOperand(1)); 2137 2138 // fold (A+(B-(C+A))) to (B-C) 2139 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2140 N0 == N1.getOperand(1).getOperand(1)) 2141 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2142 N1.getOperand(1).getOperand(0)); 2143 2144 // fold (A+((B-A)+or-C)) to (B+or-C) 2145 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2146 N1.getOperand(0).getOpcode() == ISD::SUB && 2147 N0 == N1.getOperand(0).getOperand(1)) 2148 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2149 N1.getOperand(1)); 2150 2151 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2152 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2153 SDValue N00 = N0.getOperand(0); 2154 SDValue N01 = N0.getOperand(1); 2155 SDValue N10 = N1.getOperand(0); 2156 SDValue N11 = N1.getOperand(1); 2157 2158 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2159 return DAG.getNode(ISD::SUB, DL, VT, 2160 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2161 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2162 } 2163 2164 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2165 return V; 2166 2167 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2168 return V; 2169 2170 if (SimplifyDemandedBits(SDValue(N, 0))) 2171 return SDValue(N, 0); 2172 2173 // fold (a+b) -> (a|b) iff a and b share no bits. 2174 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2175 DAG.haveNoCommonBitsSet(N0, N1)) 2176 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2177 2178 // fold (add (xor a, -1), 1) -> (sub 0, a) 2179 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) 2180 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2181 N0.getOperand(0)); 2182 2183 if (SDValue Combined = visitADDLike(N0, N1, N)) 2184 return Combined; 2185 2186 if (SDValue Combined = visitADDLike(N1, N0, N)) 2187 return Combined; 2188 2189 return SDValue(); 2190 } 2191 2192 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2193 bool Masked = false; 2194 2195 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2196 while (true) { 2197 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2198 V = V.getOperand(0); 2199 continue; 2200 } 2201 2202 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2203 Masked = true; 2204 V = V.getOperand(0); 2205 continue; 2206 } 2207 2208 break; 2209 } 2210 2211 // If this is not a carry, return. 2212 if (V.getResNo() != 1) 2213 return SDValue(); 2214 2215 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2216 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2217 return SDValue(); 2218 2219 // If the result is masked, then no matter what kind of bool it is we can 2220 // return. If it isn't, then we need to make sure the bool type is either 0 or 2221 // 1 and not other values. 2222 if (Masked || 2223 TLI.getBooleanContents(V.getValueType()) == 2224 TargetLoweringBase::ZeroOrOneBooleanContent) 2225 return V; 2226 2227 return SDValue(); 2228 } 2229 2230 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2231 EVT VT = N0.getValueType(); 2232 SDLoc DL(LocReference); 2233 2234 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2235 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2236 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2237 return DAG.getNode(ISD::SUB, DL, VT, N0, 2238 DAG.getNode(ISD::SHL, DL, VT, 2239 N1.getOperand(0).getOperand(1), 2240 N1.getOperand(1))); 2241 2242 if (N1.getOpcode() == ISD::AND) { 2243 SDValue AndOp0 = N1.getOperand(0); 2244 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2245 unsigned DestBits = VT.getScalarSizeInBits(); 2246 2247 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2248 // and similar xforms where the inner op is either ~0 or 0. 2249 if (NumSignBits == DestBits && 2250 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2251 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2252 } 2253 2254 // add (sext i1), X -> sub X, (zext i1) 2255 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2256 N0.getOperand(0).getValueType() == MVT::i1 && 2257 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2258 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2259 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2260 } 2261 2262 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2263 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2264 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2265 if (TN->getVT() == MVT::i1) { 2266 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2267 DAG.getConstant(1, DL, VT)); 2268 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2269 } 2270 } 2271 2272 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2273 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2274 N1.getResNo() == 0) 2275 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2276 N0, N1.getOperand(0), N1.getOperand(2)); 2277 2278 // (add X, Carry) -> (addcarry X, 0, Carry) 2279 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2280 if (SDValue Carry = getAsCarry(TLI, N1)) 2281 return DAG.getNode(ISD::ADDCARRY, DL, 2282 DAG.getVTList(VT, Carry.getValueType()), N0, 2283 DAG.getConstant(0, DL, VT), Carry); 2284 2285 return SDValue(); 2286 } 2287 2288 SDValue DAGCombiner::visitADDC(SDNode *N) { 2289 SDValue N0 = N->getOperand(0); 2290 SDValue N1 = N->getOperand(1); 2291 EVT VT = N0.getValueType(); 2292 SDLoc DL(N); 2293 2294 // If the flag result is dead, turn this into an ADD. 2295 if (!N->hasAnyUseOfValue(1)) 2296 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2297 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2298 2299 // canonicalize constant to RHS. 2300 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2301 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2302 if (N0C && !N1C) 2303 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2304 2305 // fold (addc x, 0) -> x + no carry out 2306 if (isNullConstant(N1)) 2307 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2308 DL, MVT::Glue)); 2309 2310 // If it cannot overflow, transform into an add. 2311 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2312 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2313 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2314 2315 return SDValue(); 2316 } 2317 2318 static SDValue flipBoolean(SDValue V, const SDLoc &DL, EVT VT, 2319 SelectionDAG &DAG, const TargetLowering &TLI) { 2320 SDValue Cst; 2321 switch (TLI.getBooleanContents(VT)) { 2322 case TargetLowering::ZeroOrOneBooleanContent: 2323 case TargetLowering::UndefinedBooleanContent: 2324 Cst = DAG.getConstant(1, DL, VT); 2325 break; 2326 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2327 Cst = DAG.getConstant(-1, DL, VT); 2328 break; 2329 } 2330 2331 return DAG.getNode(ISD::XOR, DL, VT, V, Cst); 2332 } 2333 2334 static bool isBooleanFlip(SDValue V, EVT VT, const TargetLowering &TLI) { 2335 if (V.getOpcode() != ISD::XOR) return false; 2336 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V.getOperand(1)); 2337 if (!Const) return false; 2338 2339 switch(TLI.getBooleanContents(VT)) { 2340 case TargetLowering::ZeroOrOneBooleanContent: 2341 return Const->isOne(); 2342 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2343 return Const->isAllOnesValue(); 2344 case TargetLowering::UndefinedBooleanContent: 2345 return (Const->getAPIntValue() & 0x01) == 1; 2346 } 2347 llvm_unreachable("Unsupported boolean content"); 2348 } 2349 2350 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2351 SDValue N0 = N->getOperand(0); 2352 SDValue N1 = N->getOperand(1); 2353 EVT VT = N0.getValueType(); 2354 if (VT.isVector()) 2355 return SDValue(); 2356 2357 EVT CarryVT = N->getValueType(1); 2358 SDLoc DL(N); 2359 2360 // If the flag result is dead, turn this into an ADD. 2361 if (!N->hasAnyUseOfValue(1)) 2362 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2363 DAG.getUNDEF(CarryVT)); 2364 2365 // canonicalize constant to RHS. 2366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2368 if (N0C && !N1C) 2369 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2370 2371 // fold (uaddo x, 0) -> x + no carry out 2372 if (isNullConstant(N1)) 2373 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2374 2375 // If it cannot overflow, transform into an add. 2376 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2377 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2378 DAG.getConstant(0, DL, CarryVT)); 2379 2380 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2381 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) { 2382 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2383 DAG.getConstant(0, DL, VT), 2384 N0.getOperand(0)); 2385 return CombineTo(N, Sub, 2386 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2387 } 2388 2389 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2390 return Combined; 2391 2392 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2393 return Combined; 2394 2395 return SDValue(); 2396 } 2397 2398 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2399 auto VT = N0.getValueType(); 2400 2401 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2402 // If Y + 1 cannot overflow. 2403 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2404 SDValue Y = N1.getOperand(0); 2405 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2406 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2407 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2408 N1.getOperand(2)); 2409 } 2410 2411 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2412 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2413 if (SDValue Carry = getAsCarry(TLI, N1)) 2414 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2415 DAG.getConstant(0, SDLoc(N), VT), Carry); 2416 2417 return SDValue(); 2418 } 2419 2420 SDValue DAGCombiner::visitADDE(SDNode *N) { 2421 SDValue N0 = N->getOperand(0); 2422 SDValue N1 = N->getOperand(1); 2423 SDValue CarryIn = N->getOperand(2); 2424 2425 // canonicalize constant to RHS 2426 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2428 if (N0C && !N1C) 2429 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2430 N1, N0, CarryIn); 2431 2432 // fold (adde x, y, false) -> (addc x, y) 2433 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2434 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2435 2436 return SDValue(); 2437 } 2438 2439 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2440 SDValue N0 = N->getOperand(0); 2441 SDValue N1 = N->getOperand(1); 2442 SDValue CarryIn = N->getOperand(2); 2443 SDLoc DL(N); 2444 2445 // canonicalize constant to RHS 2446 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2447 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2448 if (N0C && !N1C) 2449 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2450 2451 // fold (addcarry x, y, false) -> (uaddo x, y) 2452 if (isNullConstant(CarryIn)) { 2453 if (!LegalOperations || 2454 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2455 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2456 } 2457 2458 EVT CarryVT = CarryIn.getValueType(); 2459 2460 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2461 if (isNullConstant(N0) && isNullConstant(N1)) { 2462 EVT VT = N0.getValueType(); 2463 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2464 AddToWorklist(CarryExt.getNode()); 2465 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2466 DAG.getConstant(1, DL, VT)), 2467 DAG.getConstant(0, DL, CarryVT)); 2468 } 2469 2470 // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry. 2471 if (isBitwiseNot(N0) && isNullConstant(N1) && 2472 isBooleanFlip(CarryIn, CarryVT, TLI)) { 2473 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), 2474 DAG.getConstant(0, DL, N0.getValueType()), 2475 N0.getOperand(0), CarryIn.getOperand(0)); 2476 return CombineTo(N, Sub, 2477 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2478 } 2479 2480 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2481 return Combined; 2482 2483 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2484 return Combined; 2485 2486 return SDValue(); 2487 } 2488 2489 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2490 SDNode *N) { 2491 // Iff the flag result is dead: 2492 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2493 if ((N0.getOpcode() == ISD::ADD || 2494 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2495 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2496 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2497 N0.getOperand(0), N0.getOperand(1), CarryIn); 2498 2499 /** 2500 * When one of the addcarry argument is itself a carry, we may be facing 2501 * a diamond carry propagation. In which case we try to transform the DAG 2502 * to ensure linear carry propagation if that is possible. 2503 * 2504 * We are trying to get: 2505 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2506 */ 2507 if (auto Y = getAsCarry(TLI, N1)) { 2508 /** 2509 * (uaddo A, B) 2510 * / \ 2511 * Carry Sum 2512 * | \ 2513 * | (addcarry *, 0, Z) 2514 * | / 2515 * \ Carry 2516 * | / 2517 * (addcarry X, *, *) 2518 */ 2519 if (Y.getOpcode() == ISD::UADDO && 2520 CarryIn.getResNo() == 1 && 2521 CarryIn.getOpcode() == ISD::ADDCARRY && 2522 isNullConstant(CarryIn.getOperand(1)) && 2523 CarryIn.getOperand(0) == Y.getValue(0)) { 2524 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2525 Y.getOperand(0), Y.getOperand(1), 2526 CarryIn.getOperand(2)); 2527 AddToWorklist(NewY.getNode()); 2528 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2529 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2530 NewY.getValue(1)); 2531 } 2532 } 2533 2534 return SDValue(); 2535 } 2536 2537 // Since it may not be valid to emit a fold to zero for vector initializers 2538 // check if we can before folding. 2539 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2540 SelectionDAG &DAG, bool LegalOperations, 2541 bool LegalTypes) { 2542 if (!VT.isVector()) 2543 return DAG.getConstant(0, DL, VT); 2544 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2545 return DAG.getConstant(0, DL, VT); 2546 return SDValue(); 2547 } 2548 2549 SDValue DAGCombiner::visitSUB(SDNode *N) { 2550 SDValue N0 = N->getOperand(0); 2551 SDValue N1 = N->getOperand(1); 2552 EVT VT = N0.getValueType(); 2553 SDLoc DL(N); 2554 2555 // fold vector ops 2556 if (VT.isVector()) { 2557 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2558 return FoldedVOp; 2559 2560 // fold (sub x, 0) -> x, vector edition 2561 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2562 return N0; 2563 } 2564 2565 // fold (sub x, x) -> 0 2566 // FIXME: Refactor this and xor and other similar operations together. 2567 if (N0 == N1) 2568 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2569 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2570 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2571 // fold (sub c1, c2) -> c1-c2 2572 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2573 N1.getNode()); 2574 } 2575 2576 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2577 return NewSel; 2578 2579 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2580 2581 // fold (sub x, c) -> (add x, -c) 2582 if (N1C) { 2583 return DAG.getNode(ISD::ADD, DL, VT, N0, 2584 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2585 } 2586 2587 if (isNullConstantOrNullSplatConstant(N0)) { 2588 unsigned BitWidth = VT.getScalarSizeInBits(); 2589 // Right-shifting everything out but the sign bit followed by negation is 2590 // the same as flipping arithmetic/logical shift type without the negation: 2591 // -(X >>u 31) -> (X >>s 31) 2592 // -(X >>s 31) -> (X >>u 31) 2593 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2594 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2595 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2596 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2597 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2598 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2599 } 2600 } 2601 2602 // 0 - X --> 0 if the sub is NUW. 2603 if (N->getFlags().hasNoUnsignedWrap()) 2604 return N0; 2605 2606 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2607 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2608 // N1 must be 0 because negating the minimum signed value is undefined. 2609 if (N->getFlags().hasNoSignedWrap()) 2610 return N0; 2611 2612 // 0 - X --> X if X is 0 or the minimum signed value. 2613 return N1; 2614 } 2615 } 2616 2617 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2618 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2619 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2620 2621 // fold (A - (0-B)) -> A+B 2622 if (N1.getOpcode() == ISD::SUB && 2623 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2624 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 2625 2626 // fold A-(A-B) -> B 2627 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2628 return N1.getOperand(1); 2629 2630 // fold (A+B)-A -> B 2631 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2632 return N0.getOperand(1); 2633 2634 // fold (A+B)-B -> A 2635 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2636 return N0.getOperand(0); 2637 2638 // fold C2-(A+C1) -> (C2-C1)-A 2639 if (N1.getOpcode() == ISD::ADD) { 2640 SDValue N11 = N1.getOperand(1); 2641 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2642 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2643 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2644 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2645 } 2646 } 2647 2648 // fold ((A+(B+or-C))-B) -> A+or-C 2649 if (N0.getOpcode() == ISD::ADD && 2650 (N0.getOperand(1).getOpcode() == ISD::SUB || 2651 N0.getOperand(1).getOpcode() == ISD::ADD) && 2652 N0.getOperand(1).getOperand(0) == N1) 2653 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2654 N0.getOperand(1).getOperand(1)); 2655 2656 // fold ((A+(C+B))-B) -> A+C 2657 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2658 N0.getOperand(1).getOperand(1) == N1) 2659 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2660 N0.getOperand(1).getOperand(0)); 2661 2662 // fold ((A-(B-C))-C) -> A-B 2663 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2664 N0.getOperand(1).getOperand(1) == N1) 2665 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2666 N0.getOperand(1).getOperand(0)); 2667 2668 // fold (A-(B-C)) -> A+(C-B) 2669 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 2670 return DAG.getNode(ISD::ADD, DL, VT, N0, 2671 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 2672 N1.getOperand(0))); 2673 2674 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 2675 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 2676 if (N1.getOperand(0).getOpcode() == ISD::SUB && 2677 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) { 2678 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2679 N1.getOperand(0).getOperand(1), 2680 N1.getOperand(1)); 2681 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2682 } 2683 if (N1.getOperand(1).getOpcode() == ISD::SUB && 2684 isNullConstantOrNullSplatConstant(N1.getOperand(1).getOperand(0))) { 2685 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2686 N1.getOperand(0), 2687 N1.getOperand(1).getOperand(1)); 2688 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2689 } 2690 } 2691 2692 // If either operand of a sub is undef, the result is undef 2693 if (N0.isUndef()) 2694 return N0; 2695 if (N1.isUndef()) 2696 return N1; 2697 2698 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2699 return V; 2700 2701 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2702 return V; 2703 2704 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 2705 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 2706 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 2707 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 2708 SDValue S0 = N1.getOperand(0); 2709 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) { 2710 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 2711 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 2712 if (C->getAPIntValue() == (OpSizeInBits - 1)) 2713 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 2714 } 2715 } 2716 } 2717 2718 // If the relocation model supports it, consider symbol offsets. 2719 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2720 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2721 // fold (sub Sym, c) -> Sym-c 2722 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2723 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2724 GA->getOffset() - 2725 (uint64_t)N1C->getSExtValue()); 2726 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2727 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2728 if (GA->getGlobal() == GB->getGlobal()) 2729 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2730 DL, VT); 2731 } 2732 2733 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2734 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2735 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2736 if (TN->getVT() == MVT::i1) { 2737 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2738 DAG.getConstant(1, DL, VT)); 2739 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2740 } 2741 } 2742 2743 // Prefer an add for more folding potential and possibly better codegen: 2744 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 2745 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 2746 SDValue ShAmt = N1.getOperand(1); 2747 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2748 if (ShAmtC && ShAmtC->getZExtValue() == N1.getScalarValueSizeInBits() - 1) { 2749 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 2750 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 2751 } 2752 } 2753 2754 return SDValue(); 2755 } 2756 2757 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2758 SDValue N0 = N->getOperand(0); 2759 SDValue N1 = N->getOperand(1); 2760 EVT VT = N0.getValueType(); 2761 SDLoc DL(N); 2762 2763 // If the flag result is dead, turn this into an SUB. 2764 if (!N->hasAnyUseOfValue(1)) 2765 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2766 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2767 2768 // fold (subc x, x) -> 0 + no borrow 2769 if (N0 == N1) 2770 return CombineTo(N, DAG.getConstant(0, DL, VT), 2771 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2772 2773 // fold (subc x, 0) -> x + no borrow 2774 if (isNullConstant(N1)) 2775 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2776 2777 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2778 if (isAllOnesConstant(N0)) 2779 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2780 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2781 2782 return SDValue(); 2783 } 2784 2785 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2786 SDValue N0 = N->getOperand(0); 2787 SDValue N1 = N->getOperand(1); 2788 EVT VT = N0.getValueType(); 2789 if (VT.isVector()) 2790 return SDValue(); 2791 2792 EVT CarryVT = N->getValueType(1); 2793 SDLoc DL(N); 2794 2795 // If the flag result is dead, turn this into an SUB. 2796 if (!N->hasAnyUseOfValue(1)) 2797 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2798 DAG.getUNDEF(CarryVT)); 2799 2800 // fold (usubo x, x) -> 0 + no borrow 2801 if (N0 == N1) 2802 return CombineTo(N, DAG.getConstant(0, DL, VT), 2803 DAG.getConstant(0, DL, CarryVT)); 2804 2805 // fold (usubo x, 0) -> x + no borrow 2806 if (isNullConstant(N1)) 2807 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2808 2809 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2810 if (isAllOnesConstant(N0)) 2811 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2812 DAG.getConstant(0, DL, CarryVT)); 2813 2814 return SDValue(); 2815 } 2816 2817 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2818 SDValue N0 = N->getOperand(0); 2819 SDValue N1 = N->getOperand(1); 2820 SDValue CarryIn = N->getOperand(2); 2821 2822 // fold (sube x, y, false) -> (subc x, y) 2823 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2824 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2825 2826 return SDValue(); 2827 } 2828 2829 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2830 SDValue N0 = N->getOperand(0); 2831 SDValue N1 = N->getOperand(1); 2832 SDValue CarryIn = N->getOperand(2); 2833 2834 // fold (subcarry x, y, false) -> (usubo x, y) 2835 if (isNullConstant(CarryIn)) { 2836 if (!LegalOperations || 2837 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 2838 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2839 } 2840 2841 return SDValue(); 2842 } 2843 2844 SDValue DAGCombiner::visitMUL(SDNode *N) { 2845 SDValue N0 = N->getOperand(0); 2846 SDValue N1 = N->getOperand(1); 2847 EVT VT = N0.getValueType(); 2848 2849 // fold (mul x, undef) -> 0 2850 if (N0.isUndef() || N1.isUndef()) 2851 return DAG.getConstant(0, SDLoc(N), VT); 2852 2853 bool N0IsConst = false; 2854 bool N1IsConst = false; 2855 bool N1IsOpaqueConst = false; 2856 bool N0IsOpaqueConst = false; 2857 APInt ConstValue0, ConstValue1; 2858 // fold vector ops 2859 if (VT.isVector()) { 2860 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2861 return FoldedVOp; 2862 2863 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2864 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2865 assert((!N0IsConst || 2866 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2867 "Splat APInt should be element width"); 2868 assert((!N1IsConst || 2869 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2870 "Splat APInt should be element width"); 2871 } else { 2872 N0IsConst = isa<ConstantSDNode>(N0); 2873 if (N0IsConst) { 2874 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2875 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2876 } 2877 N1IsConst = isa<ConstantSDNode>(N1); 2878 if (N1IsConst) { 2879 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2880 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2881 } 2882 } 2883 2884 // fold (mul c1, c2) -> c1*c2 2885 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2886 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2887 N0.getNode(), N1.getNode()); 2888 2889 // canonicalize constant to RHS (vector doesn't have to splat) 2890 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2891 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2892 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2893 // fold (mul x, 0) -> 0 2894 if (N1IsConst && ConstValue1.isNullValue()) 2895 return N1; 2896 // fold (mul x, 1) -> x 2897 if (N1IsConst && ConstValue1.isOneValue()) 2898 return N0; 2899 2900 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2901 return NewSel; 2902 2903 // fold (mul x, -1) -> 0-x 2904 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2905 SDLoc DL(N); 2906 return DAG.getNode(ISD::SUB, DL, VT, 2907 DAG.getConstant(0, DL, VT), N0); 2908 } 2909 // fold (mul x, (1 << c)) -> x << c 2910 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2911 DAG.isKnownToBeAPowerOfTwo(N1) && 2912 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 2913 SDLoc DL(N); 2914 SDValue LogBase2 = BuildLogBase2(N1, DL); 2915 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2916 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2917 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2918 } 2919 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2920 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2921 unsigned Log2Val = (-ConstValue1).logBase2(); 2922 SDLoc DL(N); 2923 // FIXME: If the input is something that is easily negated (e.g. a 2924 // single-use add), we should put the negate there. 2925 return DAG.getNode(ISD::SUB, DL, VT, 2926 DAG.getConstant(0, DL, VT), 2927 DAG.getNode(ISD::SHL, DL, VT, N0, 2928 DAG.getConstant(Log2Val, DL, 2929 getShiftAmountTy(N0.getValueType())))); 2930 } 2931 2932 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2933 if (N0.getOpcode() == ISD::SHL && 2934 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2935 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2936 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2937 if (isConstantOrConstantVector(C3)) 2938 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2939 } 2940 2941 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2942 // use. 2943 { 2944 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2945 2946 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2947 if (N0.getOpcode() == ISD::SHL && 2948 isConstantOrConstantVector(N0.getOperand(1)) && 2949 N0.getNode()->hasOneUse()) { 2950 Sh = N0; Y = N1; 2951 } else if (N1.getOpcode() == ISD::SHL && 2952 isConstantOrConstantVector(N1.getOperand(1)) && 2953 N1.getNode()->hasOneUse()) { 2954 Sh = N1; Y = N0; 2955 } 2956 2957 if (Sh.getNode()) { 2958 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2959 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2960 } 2961 } 2962 2963 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2964 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2965 N0.getOpcode() == ISD::ADD && 2966 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2967 isMulAddWithConstProfitable(N, N0, N1)) 2968 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2969 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2970 N0.getOperand(0), N1), 2971 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2972 N0.getOperand(1), N1)); 2973 2974 // reassociate mul 2975 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) 2976 return RMUL; 2977 2978 return SDValue(); 2979 } 2980 2981 /// Return true if divmod libcall is available. 2982 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2983 const TargetLowering &TLI) { 2984 RTLIB::Libcall LC; 2985 EVT NodeType = Node->getValueType(0); 2986 if (!NodeType.isSimple()) 2987 return false; 2988 switch (NodeType.getSimpleVT().SimpleTy) { 2989 default: return false; // No libcall for vector types. 2990 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2991 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2992 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2993 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2994 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2995 } 2996 2997 return TLI.getLibcallName(LC) != nullptr; 2998 } 2999 3000 /// Issue divrem if both quotient and remainder are needed. 3001 SDValue DAGCombiner::useDivRem(SDNode *Node) { 3002 if (Node->use_empty()) 3003 return SDValue(); // This is a dead node, leave it alone. 3004 3005 unsigned Opcode = Node->getOpcode(); 3006 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 3007 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3008 3009 // DivMod lib calls can still work on non-legal types if using lib-calls. 3010 EVT VT = Node->getValueType(0); 3011 if (VT.isVector() || !VT.isInteger()) 3012 return SDValue(); 3013 3014 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 3015 return SDValue(); 3016 3017 // If DIVREM is going to get expanded into a libcall, 3018 // but there is no libcall available, then don't combine. 3019 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 3020 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 3021 return SDValue(); 3022 3023 // If div is legal, it's better to do the normal expansion 3024 unsigned OtherOpcode = 0; 3025 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 3026 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 3027 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 3028 return SDValue(); 3029 } else { 3030 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3031 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 3032 return SDValue(); 3033 } 3034 3035 SDValue Op0 = Node->getOperand(0); 3036 SDValue Op1 = Node->getOperand(1); 3037 SDValue combined; 3038 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 3039 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 3040 SDNode *User = *UI; 3041 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 3042 User->use_empty()) 3043 continue; 3044 // Convert the other matching node(s), too; 3045 // otherwise, the DIVREM may get target-legalized into something 3046 // target-specific that we won't be able to recognize. 3047 unsigned UserOpc = User->getOpcode(); 3048 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 3049 User->getOperand(0) == Op0 && 3050 User->getOperand(1) == Op1) { 3051 if (!combined) { 3052 if (UserOpc == OtherOpcode) { 3053 SDVTList VTs = DAG.getVTList(VT, VT); 3054 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 3055 } else if (UserOpc == DivRemOpc) { 3056 combined = SDValue(User, 0); 3057 } else { 3058 assert(UserOpc == Opcode); 3059 continue; 3060 } 3061 } 3062 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 3063 CombineTo(User, combined); 3064 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 3065 CombineTo(User, combined.getValue(1)); 3066 } 3067 } 3068 return combined; 3069 } 3070 3071 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 3072 SDValue N0 = N->getOperand(0); 3073 SDValue N1 = N->getOperand(1); 3074 EVT VT = N->getValueType(0); 3075 SDLoc DL(N); 3076 3077 unsigned Opc = N->getOpcode(); 3078 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); 3079 3080 // X / undef -> undef 3081 // X % undef -> undef 3082 // X / 0 -> undef 3083 // X % 0 -> undef 3084 // NOTE: This includes vectors where any divisor element is zero/undef. 3085 if (DAG.isUndef(Opc, {N0, N1})) 3086 return DAG.getUNDEF(VT); 3087 3088 // undef / X -> 0 3089 // undef % X -> 0 3090 if (N0.isUndef()) 3091 return DAG.getConstant(0, DL, VT); 3092 3093 // TODO: 0 / X -> 0 3094 // TODO: 0 % X -> 0 3095 3096 // X / X -> 1 3097 // X % X -> 0 3098 if (N0 == N1) 3099 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); 3100 3101 // TODO: X / 1 -> X 3102 // TODO: X % 1 -> 0 3103 // If this is a boolean op (single-bit element type), we can't have 3104 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 3105 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1. 3106 3107 return SDValue(); 3108 } 3109 3110 SDValue DAGCombiner::visitSDIV(SDNode *N) { 3111 SDValue N0 = N->getOperand(0); 3112 SDValue N1 = N->getOperand(1); 3113 EVT VT = N->getValueType(0); 3114 EVT CCVT = getSetCCResultType(VT); 3115 3116 // fold vector ops 3117 if (VT.isVector()) 3118 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3119 return FoldedVOp; 3120 3121 SDLoc DL(N); 3122 3123 // fold (sdiv c1, c2) -> c1/c2 3124 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3125 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3126 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 3127 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 3128 // fold (sdiv X, 1) -> X 3129 if (N1C && N1C->isOne()) 3130 return N0; 3131 // fold (sdiv X, -1) -> 0-X 3132 if (N1C && N1C->isAllOnesValue()) 3133 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 3134 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 3135 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 3136 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3137 DAG.getConstant(1, DL, VT), 3138 DAG.getConstant(0, DL, VT)); 3139 3140 if (SDValue V = simplifyDivRem(N, DAG)) 3141 return V; 3142 3143 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3144 return NewSel; 3145 3146 // If we know the sign bits of both operands are zero, strength reduce to a 3147 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 3148 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3149 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 3150 3151 if (SDValue V = visitSDIVLike(N0, N1, N)) 3152 return V; 3153 3154 // sdiv, srem -> sdivrem 3155 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3156 // true. Otherwise, we break the simplification logic in visitREM(). 3157 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3158 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3159 if (SDValue DivRem = useDivRem(N)) 3160 return DivRem; 3161 3162 return SDValue(); 3163 } 3164 3165 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3166 SDLoc DL(N); 3167 EVT VT = N->getValueType(0); 3168 EVT CCVT = getSetCCResultType(VT); 3169 unsigned BitWidth = VT.getScalarSizeInBits(); 3170 3171 // Helper for determining whether a value is a power-2 constant scalar or a 3172 // vector of such elements. 3173 auto IsPowerOfTwo = [](ConstantSDNode *C) { 3174 if (C->isNullValue() || C->isOpaque()) 3175 return false; 3176 if (C->getAPIntValue().isPowerOf2()) 3177 return true; 3178 if ((-C->getAPIntValue()).isPowerOf2()) 3179 return true; 3180 return false; 3181 }; 3182 3183 // fold (sdiv X, pow2) -> simple ops after legalize 3184 // FIXME: We check for the exact bit here because the generic lowering gives 3185 // better results in that case. The target-specific lowering should learn how 3186 // to handle exact sdivs efficiently. 3187 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { 3188 // Target-specific implementation of sdiv x, pow2. 3189 if (SDValue Res = BuildSDIVPow2(N)) 3190 return Res; 3191 3192 // Create constants that are functions of the shift amount value. 3193 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 3194 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 3195 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 3196 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 3197 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 3198 if (!isConstantOrConstantVector(Inexact)) 3199 return SDValue(); 3200 3201 // Splat the sign bit into the register 3202 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 3203 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 3204 AddToWorklist(Sign.getNode()); 3205 3206 // Add (N0 < 0) ? abs2 - 1 : 0; 3207 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 3208 AddToWorklist(Srl.getNode()); 3209 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 3210 AddToWorklist(Add.getNode()); 3211 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 3212 AddToWorklist(Sra.getNode()); 3213 3214 // Special case: (sdiv X, 1) -> X 3215 // Special Case: (sdiv X, -1) -> 0-X 3216 SDValue One = DAG.getConstant(1, DL, VT); 3217 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 3218 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 3219 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 3220 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 3221 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 3222 3223 // If dividing by a positive value, we're done. Otherwise, the result must 3224 // be negated. 3225 SDValue Zero = DAG.getConstant(0, DL, VT); 3226 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 3227 3228 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 3229 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 3230 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 3231 return Res; 3232 } 3233 3234 // If integer divide is expensive and we satisfy the requirements, emit an 3235 // alternate sequence. Targets may check function attributes for size/speed 3236 // trade-offs. 3237 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3238 if (isConstantOrConstantVector(N1) && 3239 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3240 if (SDValue Op = BuildSDIV(N)) 3241 return Op; 3242 3243 return SDValue(); 3244 } 3245 3246 SDValue DAGCombiner::visitUDIV(SDNode *N) { 3247 SDValue N0 = N->getOperand(0); 3248 SDValue N1 = N->getOperand(1); 3249 EVT VT = N->getValueType(0); 3250 EVT CCVT = getSetCCResultType(VT); 3251 3252 // fold vector ops 3253 if (VT.isVector()) 3254 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3255 return FoldedVOp; 3256 3257 SDLoc DL(N); 3258 3259 // fold (udiv c1, c2) -> c1/c2 3260 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3261 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3262 if (N0C && N1C) 3263 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 3264 N0C, N1C)) 3265 return Folded; 3266 // fold (udiv X, 1) -> X 3267 if (N1C && N1C->isOne()) 3268 return N0; 3269 // fold (udiv X, -1) -> select(X == -1, 1, 0) 3270 if (N1C && N1C->getAPIntValue().isAllOnesValue()) 3271 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3272 DAG.getConstant(1, DL, VT), 3273 DAG.getConstant(0, DL, VT)); 3274 3275 if (SDValue V = simplifyDivRem(N, DAG)) 3276 return V; 3277 3278 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3279 return NewSel; 3280 3281 if (SDValue V = visitUDIVLike(N0, N1, N)) 3282 return V; 3283 3284 // sdiv, srem -> sdivrem 3285 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3286 // true. Otherwise, we break the simplification logic in visitREM(). 3287 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3288 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3289 if (SDValue DivRem = useDivRem(N)) 3290 return DivRem; 3291 3292 return SDValue(); 3293 } 3294 3295 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3296 SDLoc DL(N); 3297 EVT VT = N->getValueType(0); 3298 3299 // fold (udiv x, (1 << c)) -> x >>u c 3300 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3301 DAG.isKnownToBeAPowerOfTwo(N1)) { 3302 SDValue LogBase2 = BuildLogBase2(N1, DL); 3303 AddToWorklist(LogBase2.getNode()); 3304 3305 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3306 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3307 AddToWorklist(Trunc.getNode()); 3308 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3309 } 3310 3311 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 3312 if (N1.getOpcode() == ISD::SHL) { 3313 SDValue N10 = N1.getOperand(0); 3314 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 3315 DAG.isKnownToBeAPowerOfTwo(N10)) { 3316 SDValue LogBase2 = BuildLogBase2(N10, DL); 3317 AddToWorklist(LogBase2.getNode()); 3318 3319 EVT ADDVT = N1.getOperand(1).getValueType(); 3320 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 3321 AddToWorklist(Trunc.getNode()); 3322 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 3323 AddToWorklist(Add.getNode()); 3324 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 3325 } 3326 } 3327 3328 // fold (udiv x, c) -> alternate 3329 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3330 if (isConstantOrConstantVector(N1) && 3331 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3332 if (SDValue Op = BuildUDIV(N)) 3333 return Op; 3334 3335 return SDValue(); 3336 } 3337 3338 // handles ISD::SREM and ISD::UREM 3339 SDValue DAGCombiner::visitREM(SDNode *N) { 3340 unsigned Opcode = N->getOpcode(); 3341 SDValue N0 = N->getOperand(0); 3342 SDValue N1 = N->getOperand(1); 3343 EVT VT = N->getValueType(0); 3344 EVT CCVT = getSetCCResultType(VT); 3345 3346 bool isSigned = (Opcode == ISD::SREM); 3347 SDLoc DL(N); 3348 3349 // fold (rem c1, c2) -> c1%c2 3350 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3351 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3352 if (N0C && N1C) 3353 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3354 return Folded; 3355 // fold (urem X, -1) -> select(X == -1, 0, x) 3356 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) 3357 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3358 DAG.getConstant(0, DL, VT), N0); 3359 3360 if (SDValue V = simplifyDivRem(N, DAG)) 3361 return V; 3362 3363 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3364 return NewSel; 3365 3366 if (isSigned) { 3367 // If we know the sign bits of both operands are zero, strength reduce to a 3368 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3369 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3370 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3371 } else { 3372 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3373 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3374 // fold (urem x, pow2) -> (and x, pow2-1) 3375 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3376 AddToWorklist(Add.getNode()); 3377 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3378 } 3379 if (N1.getOpcode() == ISD::SHL && 3380 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3381 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3382 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3383 AddToWorklist(Add.getNode()); 3384 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3385 } 3386 } 3387 3388 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3389 3390 // If X/C can be simplified by the division-by-constant logic, lower 3391 // X%C to the equivalent of X-X/C*C. 3392 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 3393 // speculative DIV must not cause a DIVREM conversion. We guard against this 3394 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 3395 // combine will not return a DIVREM. Regardless, checking cheapness here 3396 // makes sense since the simplification results in fatter code. 3397 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 3398 SDValue OptimizedDiv = 3399 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 3400 if (OptimizedDiv.getNode() && OptimizedDiv.getOpcode() != ISD::UDIVREM && 3401 OptimizedDiv.getOpcode() != ISD::SDIVREM) { 3402 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3403 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3404 AddToWorklist(OptimizedDiv.getNode()); 3405 AddToWorklist(Mul.getNode()); 3406 return Sub; 3407 } 3408 } 3409 3410 // sdiv, srem -> sdivrem 3411 if (SDValue DivRem = useDivRem(N)) 3412 return DivRem.getValue(1); 3413 3414 return SDValue(); 3415 } 3416 3417 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3418 SDValue N0 = N->getOperand(0); 3419 SDValue N1 = N->getOperand(1); 3420 EVT VT = N->getValueType(0); 3421 SDLoc DL(N); 3422 3423 if (VT.isVector()) { 3424 // fold (mulhs x, 0) -> 0 3425 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3426 return N1; 3427 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3428 return N0; 3429 } 3430 3431 // fold (mulhs x, 0) -> 0 3432 if (isNullConstant(N1)) 3433 return N1; 3434 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3435 if (isOneConstant(N1)) 3436 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3437 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3438 getShiftAmountTy(N0.getValueType()))); 3439 3440 // fold (mulhs x, undef) -> 0 3441 if (N0.isUndef() || N1.isUndef()) 3442 return DAG.getConstant(0, DL, VT); 3443 3444 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3445 // plus a shift. 3446 if (VT.isSimple() && !VT.isVector()) { 3447 MVT Simple = VT.getSimpleVT(); 3448 unsigned SimpleSize = Simple.getSizeInBits(); 3449 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3450 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3451 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3452 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3453 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3454 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3455 DAG.getConstant(SimpleSize, DL, 3456 getShiftAmountTy(N1.getValueType()))); 3457 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3458 } 3459 } 3460 3461 return SDValue(); 3462 } 3463 3464 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3465 SDValue N0 = N->getOperand(0); 3466 SDValue N1 = N->getOperand(1); 3467 EVT VT = N->getValueType(0); 3468 SDLoc DL(N); 3469 3470 if (VT.isVector()) { 3471 // fold (mulhu x, 0) -> 0 3472 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3473 return N1; 3474 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3475 return N0; 3476 } 3477 3478 // fold (mulhu x, 0) -> 0 3479 if (isNullConstant(N1)) 3480 return N1; 3481 // fold (mulhu x, 1) -> 0 3482 if (isOneConstant(N1)) 3483 return DAG.getConstant(0, DL, N0.getValueType()); 3484 // fold (mulhu x, undef) -> 0 3485 if (N0.isUndef() || N1.isUndef()) 3486 return DAG.getConstant(0, DL, VT); 3487 3488 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) 3489 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3490 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { 3491 SDLoc DL(N); 3492 unsigned NumEltBits = VT.getScalarSizeInBits(); 3493 SDValue LogBase2 = BuildLogBase2(N1, DL); 3494 SDValue SRLAmt = DAG.getNode( 3495 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); 3496 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3497 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); 3498 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3499 } 3500 3501 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3502 // plus a shift. 3503 if (VT.isSimple() && !VT.isVector()) { 3504 MVT Simple = VT.getSimpleVT(); 3505 unsigned SimpleSize = Simple.getSizeInBits(); 3506 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3507 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3508 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3509 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3510 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3511 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3512 DAG.getConstant(SimpleSize, DL, 3513 getShiftAmountTy(N1.getValueType()))); 3514 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3515 } 3516 } 3517 3518 return SDValue(); 3519 } 3520 3521 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3522 /// give the opcodes for the two computations that are being performed. Return 3523 /// true if a simplification was made. 3524 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3525 unsigned HiOp) { 3526 // If the high half is not needed, just compute the low half. 3527 bool HiExists = N->hasAnyUseOfValue(1); 3528 if (!HiExists && 3529 (!LegalOperations || 3530 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3531 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3532 return CombineTo(N, Res, Res); 3533 } 3534 3535 // If the low half is not needed, just compute the high half. 3536 bool LoExists = N->hasAnyUseOfValue(0); 3537 if (!LoExists && 3538 (!LegalOperations || 3539 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3540 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3541 return CombineTo(N, Res, Res); 3542 } 3543 3544 // If both halves are used, return as it is. 3545 if (LoExists && HiExists) 3546 return SDValue(); 3547 3548 // If the two computed results can be simplified separately, separate them. 3549 if (LoExists) { 3550 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3551 AddToWorklist(Lo.getNode()); 3552 SDValue LoOpt = combine(Lo.getNode()); 3553 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3554 (!LegalOperations || 3555 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3556 return CombineTo(N, LoOpt, LoOpt); 3557 } 3558 3559 if (HiExists) { 3560 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3561 AddToWorklist(Hi.getNode()); 3562 SDValue HiOpt = combine(Hi.getNode()); 3563 if (HiOpt.getNode() && HiOpt != Hi && 3564 (!LegalOperations || 3565 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3566 return CombineTo(N, HiOpt, HiOpt); 3567 } 3568 3569 return SDValue(); 3570 } 3571 3572 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3573 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3574 return Res; 3575 3576 EVT VT = N->getValueType(0); 3577 SDLoc DL(N); 3578 3579 // If the type is twice as wide is legal, transform the mulhu to a wider 3580 // multiply plus a shift. 3581 if (VT.isSimple() && !VT.isVector()) { 3582 MVT Simple = VT.getSimpleVT(); 3583 unsigned SimpleSize = Simple.getSizeInBits(); 3584 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3585 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3586 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3587 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3588 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3589 // Compute the high part as N1. 3590 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3591 DAG.getConstant(SimpleSize, DL, 3592 getShiftAmountTy(Lo.getValueType()))); 3593 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3594 // Compute the low part as N0. 3595 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3596 return CombineTo(N, Lo, Hi); 3597 } 3598 } 3599 3600 return SDValue(); 3601 } 3602 3603 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3604 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3605 return Res; 3606 3607 EVT VT = N->getValueType(0); 3608 SDLoc DL(N); 3609 3610 // If the type is twice as wide is legal, transform the mulhu to a wider 3611 // multiply plus a shift. 3612 if (VT.isSimple() && !VT.isVector()) { 3613 MVT Simple = VT.getSimpleVT(); 3614 unsigned SimpleSize = Simple.getSizeInBits(); 3615 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3616 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3617 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3618 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3619 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3620 // Compute the high part as N1. 3621 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3622 DAG.getConstant(SimpleSize, DL, 3623 getShiftAmountTy(Lo.getValueType()))); 3624 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3625 // Compute the low part as N0. 3626 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3627 return CombineTo(N, Lo, Hi); 3628 } 3629 } 3630 3631 return SDValue(); 3632 } 3633 3634 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3635 // (smulo x, 2) -> (saddo x, x) 3636 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3637 if (C2->getAPIntValue() == 2) 3638 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3639 N->getOperand(0), N->getOperand(0)); 3640 3641 return SDValue(); 3642 } 3643 3644 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3645 // (umulo x, 2) -> (uaddo x, x) 3646 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3647 if (C2->getAPIntValue() == 2) 3648 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3649 N->getOperand(0), N->getOperand(0)); 3650 3651 return SDValue(); 3652 } 3653 3654 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3655 SDValue N0 = N->getOperand(0); 3656 SDValue N1 = N->getOperand(1); 3657 EVT VT = N0.getValueType(); 3658 3659 // fold vector ops 3660 if (VT.isVector()) 3661 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3662 return FoldedVOp; 3663 3664 // fold operation with constant operands. 3665 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3666 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3667 if (N0C && N1C) 3668 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3669 3670 // canonicalize constant to RHS 3671 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3672 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3673 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3674 3675 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 3676 // Only do this if the current op isn't legal and the flipped is. 3677 unsigned Opcode = N->getOpcode(); 3678 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3679 if (!TLI.isOperationLegal(Opcode, VT) && 3680 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 3681 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 3682 unsigned AltOpcode; 3683 switch (Opcode) { 3684 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 3685 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 3686 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 3687 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 3688 default: llvm_unreachable("Unknown MINMAX opcode"); 3689 } 3690 if (TLI.isOperationLegal(AltOpcode, VT)) 3691 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 3692 } 3693 3694 return SDValue(); 3695 } 3696 3697 /// If this is a binary operator with two operands of the same opcode, try to 3698 /// simplify it. 3699 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3700 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3701 EVT VT = N0.getValueType(); 3702 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3703 3704 // Bail early if none of these transforms apply. 3705 if (N0.getNumOperands() == 0) return SDValue(); 3706 3707 // For each of OP in AND/OR/XOR: 3708 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3709 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3710 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3711 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3712 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3713 // 3714 // do not sink logical op inside of a vector extend, since it may combine 3715 // into a vsetcc. 3716 EVT Op0VT = N0.getOperand(0).getValueType(); 3717 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3718 N0.getOpcode() == ISD::SIGN_EXTEND || 3719 N0.getOpcode() == ISD::BSWAP || 3720 // Avoid infinite looping with PromoteIntBinOp. 3721 (N0.getOpcode() == ISD::ANY_EXTEND && 3722 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3723 (N0.getOpcode() == ISD::TRUNCATE && 3724 (!TLI.isZExtFree(VT, Op0VT) || 3725 !TLI.isTruncateFree(Op0VT, VT)) && 3726 TLI.isTypeLegal(Op0VT))) && 3727 !VT.isVector() && 3728 Op0VT == N1.getOperand(0).getValueType() && 3729 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3730 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3731 N0.getOperand(0).getValueType(), 3732 N0.getOperand(0), N1.getOperand(0)); 3733 AddToWorklist(ORNode.getNode()); 3734 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3735 } 3736 3737 // For each of OP in SHL/SRL/SRA/AND... 3738 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3739 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3740 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3741 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3742 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3743 N0.getOperand(1) == N1.getOperand(1)) { 3744 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3745 N0.getOperand(0).getValueType(), 3746 N0.getOperand(0), N1.getOperand(0)); 3747 AddToWorklist(ORNode.getNode()); 3748 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3749 ORNode, N0.getOperand(1)); 3750 } 3751 3752 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3753 // Only perform this optimization up until type legalization, before 3754 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3755 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3756 // we don't want to undo this promotion. 3757 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3758 // on scalars. 3759 if ((N0.getOpcode() == ISD::BITCAST || 3760 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3761 Level <= AfterLegalizeTypes) { 3762 SDValue In0 = N0.getOperand(0); 3763 SDValue In1 = N1.getOperand(0); 3764 EVT In0Ty = In0.getValueType(); 3765 EVT In1Ty = In1.getValueType(); 3766 SDLoc DL(N); 3767 // If both incoming values are integers, and the original types are the 3768 // same. 3769 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3770 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3771 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3772 AddToWorklist(Op.getNode()); 3773 return BC; 3774 } 3775 } 3776 3777 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3778 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3779 // If both shuffles use the same mask, and both shuffle within a single 3780 // vector, then it is worthwhile to move the swizzle after the operation. 3781 // The type-legalizer generates this pattern when loading illegal 3782 // vector types from memory. In many cases this allows additional shuffle 3783 // optimizations. 3784 // There are other cases where moving the shuffle after the xor/and/or 3785 // is profitable even if shuffles don't perform a swizzle. 3786 // If both shuffles use the same mask, and both shuffles have the same first 3787 // or second operand, then it might still be profitable to move the shuffle 3788 // after the xor/and/or operation. 3789 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3790 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3791 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3792 3793 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3794 "Inputs to shuffles are not the same type"); 3795 3796 // Check that both shuffles use the same mask. The masks are known to be of 3797 // the same length because the result vector type is the same. 3798 // Check also that shuffles have only one use to avoid introducing extra 3799 // instructions. 3800 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3801 SVN0->getMask().equals(SVN1->getMask())) { 3802 SDValue ShOp = N0->getOperand(1); 3803 3804 // Don't try to fold this node if it requires introducing a 3805 // build vector of all zeros that might be illegal at this stage. 3806 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3807 if (!LegalTypes) 3808 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3809 else 3810 ShOp = SDValue(); 3811 } 3812 3813 // (AND (shuf (A, C), shuf (B, C))) -> shuf (AND (A, B), C) 3814 // (OR (shuf (A, C), shuf (B, C))) -> shuf (OR (A, B), C) 3815 // (XOR (shuf (A, C), shuf (B, C))) -> shuf (XOR (A, B), V_0) 3816 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3817 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3818 N0->getOperand(0), N1->getOperand(0)); 3819 AddToWorklist(NewNode.getNode()); 3820 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3821 SVN0->getMask()); 3822 } 3823 3824 // Don't try to fold this node if it requires introducing a 3825 // build vector of all zeros that might be illegal at this stage. 3826 ShOp = N0->getOperand(0); 3827 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3828 if (!LegalTypes) 3829 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3830 else 3831 ShOp = SDValue(); 3832 } 3833 3834 // (AND (shuf (C, A), shuf (C, B))) -> shuf (C, AND (A, B)) 3835 // (OR (shuf (C, A), shuf (C, B))) -> shuf (C, OR (A, B)) 3836 // (XOR (shuf (C, A), shuf (C, B))) -> shuf (V_0, XOR (A, B)) 3837 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3838 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3839 N0->getOperand(1), N1->getOperand(1)); 3840 AddToWorklist(NewNode.getNode()); 3841 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3842 SVN0->getMask()); 3843 } 3844 } 3845 } 3846 3847 return SDValue(); 3848 } 3849 3850 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3851 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3852 const SDLoc &DL) { 3853 SDValue LL, LR, RL, RR, N0CC, N1CC; 3854 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3855 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3856 return SDValue(); 3857 3858 assert(N0.getValueType() == N1.getValueType() && 3859 "Unexpected operand types for bitwise logic op"); 3860 assert(LL.getValueType() == LR.getValueType() && 3861 RL.getValueType() == RR.getValueType() && 3862 "Unexpected operand types for setcc"); 3863 3864 // If we're here post-legalization or the logic op type is not i1, the logic 3865 // op type must match a setcc result type. Also, all folds require new 3866 // operations on the left and right operands, so those types must match. 3867 EVT VT = N0.getValueType(); 3868 EVT OpVT = LL.getValueType(); 3869 if (LegalOperations || VT.getScalarType() != MVT::i1) 3870 if (VT != getSetCCResultType(OpVT)) 3871 return SDValue(); 3872 if (OpVT != RL.getValueType()) 3873 return SDValue(); 3874 3875 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3876 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3877 bool IsInteger = OpVT.isInteger(); 3878 if (LR == RR && CC0 == CC1 && IsInteger) { 3879 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3880 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3881 3882 // All bits clear? 3883 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3884 // All sign bits clear? 3885 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3886 // Any bits set? 3887 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3888 // Any sign bits set? 3889 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3890 3891 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3892 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3893 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3894 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3895 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3896 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3897 AddToWorklist(Or.getNode()); 3898 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3899 } 3900 3901 // All bits set? 3902 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3903 // All sign bits set? 3904 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3905 // Any bits clear? 3906 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3907 // Any sign bits clear? 3908 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3909 3910 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3911 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3912 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3913 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3914 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3915 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3916 AddToWorklist(And.getNode()); 3917 return DAG.getSetCC(DL, VT, And, LR, CC1); 3918 } 3919 } 3920 3921 // TODO: What is the 'or' equivalent of this fold? 3922 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3923 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 3924 IsInteger && CC0 == ISD::SETNE && 3925 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3926 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3927 SDValue One = DAG.getConstant(1, DL, OpVT); 3928 SDValue Two = DAG.getConstant(2, DL, OpVT); 3929 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3930 AddToWorklist(Add.getNode()); 3931 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3932 } 3933 3934 // Try more general transforms if the predicates match and the only user of 3935 // the compares is the 'and' or 'or'. 3936 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3937 N0.hasOneUse() && N1.hasOneUse()) { 3938 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3939 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3940 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3941 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3942 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3943 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3944 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3945 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3946 } 3947 } 3948 3949 // Canonicalize equivalent operands to LL == RL. 3950 if (LL == RR && LR == RL) { 3951 CC1 = ISD::getSetCCSwappedOperands(CC1); 3952 std::swap(RL, RR); 3953 } 3954 3955 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3956 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3957 if (LL == RL && LR == RR) { 3958 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3959 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3960 if (NewCC != ISD::SETCC_INVALID && 3961 (!LegalOperations || 3962 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3963 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3964 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3965 } 3966 3967 return SDValue(); 3968 } 3969 3970 /// This contains all DAGCombine rules which reduce two values combined by 3971 /// an And operation to a single value. This makes them reusable in the context 3972 /// of visitSELECT(). Rules involving constants are not included as 3973 /// visitSELECT() already handles those cases. 3974 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3975 EVT VT = N1.getValueType(); 3976 SDLoc DL(N); 3977 3978 // fold (and x, undef) -> 0 3979 if (N0.isUndef() || N1.isUndef()) 3980 return DAG.getConstant(0, DL, VT); 3981 3982 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3983 return V; 3984 3985 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3986 VT.getSizeInBits() <= 64) { 3987 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3988 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3989 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3990 // immediate for an add, but it is legal if its top c2 bits are set, 3991 // transform the ADD so the immediate doesn't need to be materialized 3992 // in a register. 3993 APInt ADDC = ADDI->getAPIntValue(); 3994 APInt SRLC = SRLI->getAPIntValue(); 3995 if (ADDC.getMinSignedBits() <= 64 && 3996 SRLC.ult(VT.getSizeInBits()) && 3997 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3998 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3999 SRLC.getZExtValue()); 4000 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 4001 ADDC |= Mask; 4002 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 4003 SDLoc DL0(N0); 4004 SDValue NewAdd = 4005 DAG.getNode(ISD::ADD, DL0, VT, 4006 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 4007 CombineTo(N0.getNode(), NewAdd); 4008 // Return N so it doesn't get rechecked! 4009 return SDValue(N, 0); 4010 } 4011 } 4012 } 4013 } 4014 } 4015 } 4016 4017 // Reduce bit extract of low half of an integer to the narrower type. 4018 // (and (srl i64:x, K), KMask) -> 4019 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 4020 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4021 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 4022 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4023 unsigned Size = VT.getSizeInBits(); 4024 const APInt &AndMask = CAnd->getAPIntValue(); 4025 unsigned ShiftBits = CShift->getZExtValue(); 4026 4027 // Bail out, this node will probably disappear anyway. 4028 if (ShiftBits == 0) 4029 return SDValue(); 4030 4031 unsigned MaskBits = AndMask.countTrailingOnes(); 4032 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 4033 4034 if (AndMask.isMask() && 4035 // Required bits must not span the two halves of the integer and 4036 // must fit in the half size type. 4037 (ShiftBits + MaskBits <= Size / 2) && 4038 TLI.isNarrowingProfitable(VT, HalfVT) && 4039 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 4040 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 4041 TLI.isTruncateFree(VT, HalfVT) && 4042 TLI.isZExtFree(HalfVT, VT)) { 4043 // The isNarrowingProfitable is to avoid regressions on PPC and 4044 // AArch64 which match a few 64-bit bit insert / bit extract patterns 4045 // on downstream users of this. Those patterns could probably be 4046 // extended to handle extensions mixed in. 4047 4048 SDValue SL(N0); 4049 assert(MaskBits <= Size); 4050 4051 // Extracting the highest bit of the low half. 4052 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 4053 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 4054 N0.getOperand(0)); 4055 4056 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 4057 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 4058 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 4059 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 4060 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 4061 } 4062 } 4063 } 4064 } 4065 4066 return SDValue(); 4067 } 4068 4069 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 4070 EVT LoadResultTy, EVT &ExtVT) { 4071 if (!AndC->getAPIntValue().isMask()) 4072 return false; 4073 4074 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 4075 4076 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4077 EVT LoadedVT = LoadN->getMemoryVT(); 4078 4079 if (ExtVT == LoadedVT && 4080 (!LegalOperations || 4081 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 4082 // ZEXTLOAD will match without needing to change the size of the value being 4083 // loaded. 4084 return true; 4085 } 4086 4087 // Do not change the width of a volatile load. 4088 if (LoadN->isVolatile()) 4089 return false; 4090 4091 // Do not generate loads of non-round integer types since these can 4092 // be expensive (and would be wrong if the type is not byte sized). 4093 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 4094 return false; 4095 4096 if (LegalOperations && 4097 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 4098 return false; 4099 4100 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 4101 return false; 4102 4103 return true; 4104 } 4105 4106 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 4107 ISD::LoadExtType ExtType, EVT &MemVT, 4108 unsigned ShAmt) { 4109 if (!LDST) 4110 return false; 4111 // Only allow byte offsets. 4112 if (ShAmt % 8) 4113 return false; 4114 4115 // Do not generate loads of non-round integer types since these can 4116 // be expensive (and would be wrong if the type is not byte sized). 4117 if (!MemVT.isRound()) 4118 return false; 4119 4120 // Don't change the width of a volatile load. 4121 if (LDST->isVolatile()) 4122 return false; 4123 4124 // Verify that we are actually reducing a load width here. 4125 if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits()) 4126 return false; 4127 4128 // Ensure that this isn't going to produce an unsupported unaligned access. 4129 if (ShAmt && 4130 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4131 LDST->getAddressSpace(), ShAmt / 8)) 4132 return false; 4133 4134 // It's not possible to generate a constant of extended or untyped type. 4135 EVT PtrType = LDST->getBasePtr().getValueType(); 4136 if (PtrType == MVT::Untyped || PtrType.isExtended()) 4137 return false; 4138 4139 if (isa<LoadSDNode>(LDST)) { 4140 LoadSDNode *Load = cast<LoadSDNode>(LDST); 4141 // Don't transform one with multiple uses, this would require adding a new 4142 // load. 4143 if (!SDValue(Load, 0).hasOneUse()) 4144 return false; 4145 4146 if (LegalOperations && 4147 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 4148 return false; 4149 4150 // For the transform to be legal, the load must produce only two values 4151 // (the value loaded and the chain). Don't transform a pre-increment 4152 // load, for example, which produces an extra value. Otherwise the 4153 // transformation is not equivalent, and the downstream logic to replace 4154 // uses gets things wrong. 4155 if (Load->getNumValues() > 2) 4156 return false; 4157 4158 // If the load that we're shrinking is an extload and we're not just 4159 // discarding the extension we can't simply shrink the load. Bail. 4160 // TODO: It would be possible to merge the extensions in some cases. 4161 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 4162 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4163 return false; 4164 4165 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 4166 return false; 4167 } else { 4168 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 4169 StoreSDNode *Store = cast<StoreSDNode>(LDST); 4170 // Can't write outside the original store 4171 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4172 return false; 4173 4174 if (LegalOperations && 4175 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 4176 return false; 4177 } 4178 return true; 4179 } 4180 4181 bool DAGCombiner::SearchForAndLoads(SDNode *N, 4182 SmallPtrSetImpl<LoadSDNode*> &Loads, 4183 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 4184 ConstantSDNode *Mask, 4185 SDNode *&NodeToMask) { 4186 // Recursively search for the operands, looking for loads which can be 4187 // narrowed. 4188 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 4189 SDValue Op = N->getOperand(i); 4190 4191 if (Op.getValueType().isVector()) 4192 return false; 4193 4194 // Some constants may need fixing up later if they are too large. 4195 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4196 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 4197 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 4198 NodesWithConsts.insert(N); 4199 continue; 4200 } 4201 4202 if (!Op.hasOneUse()) 4203 return false; 4204 4205 switch(Op.getOpcode()) { 4206 case ISD::LOAD: { 4207 auto *Load = cast<LoadSDNode>(Op); 4208 EVT ExtVT; 4209 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 4210 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 4211 4212 // ZEXTLOAD is already small enough. 4213 if (Load->getExtensionType() == ISD::ZEXTLOAD && 4214 ExtVT.bitsGE(Load->getMemoryVT())) 4215 continue; 4216 4217 // Use LE to convert equal sized loads to zext. 4218 if (ExtVT.bitsLE(Load->getMemoryVT())) 4219 Loads.insert(Load); 4220 4221 continue; 4222 } 4223 return false; 4224 } 4225 case ISD::ZERO_EXTEND: 4226 case ISD::AssertZext: { 4227 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 4228 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4229 EVT VT = Op.getOpcode() == ISD::AssertZext ? 4230 cast<VTSDNode>(Op.getOperand(1))->getVT() : 4231 Op.getOperand(0).getValueType(); 4232 4233 // We can accept extending nodes if the mask is wider or an equal 4234 // width to the original type. 4235 if (ExtVT.bitsGE(VT)) 4236 continue; 4237 break; 4238 } 4239 case ISD::OR: 4240 case ISD::XOR: 4241 case ISD::AND: 4242 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 4243 NodeToMask)) 4244 return false; 4245 continue; 4246 } 4247 4248 // Allow one node which will masked along with any loads found. 4249 if (NodeToMask) 4250 return false; 4251 4252 // Also ensure that the node to be masked only produces one data result. 4253 NodeToMask = Op.getNode(); 4254 if (NodeToMask->getNumValues() > 1) { 4255 bool HasValue = false; 4256 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 4257 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 4258 if (VT != MVT::Glue && VT != MVT::Other) { 4259 if (HasValue) { 4260 NodeToMask = nullptr; 4261 return false; 4262 } 4263 HasValue = true; 4264 } 4265 } 4266 assert(HasValue && "Node to be masked has no data result?"); 4267 } 4268 } 4269 return true; 4270 } 4271 4272 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 4273 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4274 if (!Mask) 4275 return false; 4276 4277 if (!Mask->getAPIntValue().isMask()) 4278 return false; 4279 4280 // No need to do anything if the and directly uses a load. 4281 if (isa<LoadSDNode>(N->getOperand(0))) 4282 return false; 4283 4284 SmallPtrSet<LoadSDNode*, 8> Loads; 4285 SmallPtrSet<SDNode*, 2> NodesWithConsts; 4286 SDNode *FixupNode = nullptr; 4287 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 4288 if (Loads.size() == 0) 4289 return false; 4290 4291 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 4292 SDValue MaskOp = N->getOperand(1); 4293 4294 // If it exists, fixup the single node we allow in the tree that needs 4295 // masking. 4296 if (FixupNode) { 4297 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 4298 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 4299 FixupNode->getValueType(0), 4300 SDValue(FixupNode, 0), MaskOp); 4301 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 4302 if (And.getOpcode() == ISD ::AND) 4303 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 4304 } 4305 4306 // Narrow any constants that need it. 4307 for (auto *LogicN : NodesWithConsts) { 4308 SDValue Op0 = LogicN->getOperand(0); 4309 SDValue Op1 = LogicN->getOperand(1); 4310 4311 if (isa<ConstantSDNode>(Op0)) 4312 std::swap(Op0, Op1); 4313 4314 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 4315 Op1, MaskOp); 4316 4317 DAG.UpdateNodeOperands(LogicN, Op0, And); 4318 } 4319 4320 // Create narrow loads. 4321 for (auto *Load : Loads) { 4322 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 4323 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 4324 SDValue(Load, 0), MaskOp); 4325 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 4326 if (And.getOpcode() == ISD ::AND) 4327 And = SDValue( 4328 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 4329 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 4330 assert(NewLoad && 4331 "Shouldn't be masking the load if it can't be narrowed"); 4332 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 4333 } 4334 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 4335 return true; 4336 } 4337 return false; 4338 } 4339 4340 // Unfold 4341 // x & (-1 'logical shift' y) 4342 // To 4343 // (x 'opposite logical shift' y) 'logical shift' y 4344 // if it is better for performance. 4345 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 4346 assert(N->getOpcode() == ISD::AND); 4347 4348 SDValue N0 = N->getOperand(0); 4349 SDValue N1 = N->getOperand(1); 4350 4351 // Do we actually prefer shifts over mask? 4352 if (!TLI.preferShiftsToClearExtremeBits(N0)) 4353 return SDValue(); 4354 4355 // Try to match (-1 '[outer] logical shift' y) 4356 unsigned OuterShift; 4357 unsigned InnerShift; // The opposite direction to the OuterShift. 4358 SDValue Y; // Shift amount. 4359 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 4360 if (!M.hasOneUse()) 4361 return false; 4362 OuterShift = M->getOpcode(); 4363 if (OuterShift == ISD::SHL) 4364 InnerShift = ISD::SRL; 4365 else if (OuterShift == ISD::SRL) 4366 InnerShift = ISD::SHL; 4367 else 4368 return false; 4369 if (!isAllOnesConstant(M->getOperand(0))) 4370 return false; 4371 Y = M->getOperand(1); 4372 return true; 4373 }; 4374 4375 SDValue X; 4376 if (matchMask(N1)) 4377 X = N0; 4378 else if (matchMask(N0)) 4379 X = N1; 4380 else 4381 return SDValue(); 4382 4383 SDLoc DL(N); 4384 EVT VT = N->getValueType(0); 4385 4386 // tmp = x 'opposite logical shift' y 4387 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 4388 // ret = tmp 'logical shift' y 4389 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 4390 4391 return T1; 4392 } 4393 4394 SDValue DAGCombiner::visitAND(SDNode *N) { 4395 SDValue N0 = N->getOperand(0); 4396 SDValue N1 = N->getOperand(1); 4397 EVT VT = N1.getValueType(); 4398 4399 // x & x --> x 4400 if (N0 == N1) 4401 return N0; 4402 4403 // fold vector ops 4404 if (VT.isVector()) { 4405 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4406 return FoldedVOp; 4407 4408 // fold (and x, 0) -> 0, vector edition 4409 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4410 // do not return N0, because undef node may exist in N0 4411 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 4412 SDLoc(N), N0.getValueType()); 4413 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4414 // do not return N1, because undef node may exist in N1 4415 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 4416 SDLoc(N), N1.getValueType()); 4417 4418 // fold (and x, -1) -> x, vector edition 4419 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4420 return N1; 4421 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4422 return N0; 4423 } 4424 4425 // fold (and c1, c2) -> c1&c2 4426 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4427 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4428 if (N0C && N1C && !N1C->isOpaque()) 4429 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 4430 // canonicalize constant to RHS 4431 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4432 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4433 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 4434 // fold (and x, -1) -> x 4435 if (isAllOnesConstant(N1)) 4436 return N0; 4437 // if (and x, c) is known to be zero, return 0 4438 unsigned BitWidth = VT.getScalarSizeInBits(); 4439 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4440 APInt::getAllOnesValue(BitWidth))) 4441 return DAG.getConstant(0, SDLoc(N), VT); 4442 4443 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4444 return NewSel; 4445 4446 // reassociate and 4447 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) 4448 return RAND; 4449 4450 // Try to convert a constant mask AND into a shuffle clear mask. 4451 if (VT.isVector()) 4452 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4453 return Shuffle; 4454 4455 // fold (and (or x, C), D) -> D if (C & D) == D 4456 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4457 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4458 }; 4459 if (N0.getOpcode() == ISD::OR && 4460 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4461 return N1; 4462 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4463 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4464 SDValue N0Op0 = N0.getOperand(0); 4465 APInt Mask = ~N1C->getAPIntValue(); 4466 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4467 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4468 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4469 N0.getValueType(), N0Op0); 4470 4471 // Replace uses of the AND with uses of the Zero extend node. 4472 CombineTo(N, Zext); 4473 4474 // We actually want to replace all uses of the any_extend with the 4475 // zero_extend, to avoid duplicating things. This will later cause this 4476 // AND to be folded. 4477 CombineTo(N0.getNode(), Zext); 4478 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4479 } 4480 } 4481 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4482 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4483 // already be zero by virtue of the width of the base type of the load. 4484 // 4485 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4486 // more cases. 4487 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4488 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4489 N0.getOperand(0).getOpcode() == ISD::LOAD && 4490 N0.getOperand(0).getResNo() == 0) || 4491 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4492 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4493 N0 : N0.getOperand(0) ); 4494 4495 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4496 // This can be a pure constant or a vector splat, in which case we treat the 4497 // vector as a scalar and use the splat value. 4498 APInt Constant = APInt::getNullValue(1); 4499 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4500 Constant = C->getAPIntValue(); 4501 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4502 APInt SplatValue, SplatUndef; 4503 unsigned SplatBitSize; 4504 bool HasAnyUndefs; 4505 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4506 SplatBitSize, HasAnyUndefs); 4507 if (IsSplat) { 4508 // Undef bits can contribute to a possible optimisation if set, so 4509 // set them. 4510 SplatValue |= SplatUndef; 4511 4512 // The splat value may be something like "0x00FFFFFF", which means 0 for 4513 // the first vector value and FF for the rest, repeating. We need a mask 4514 // that will apply equally to all members of the vector, so AND all the 4515 // lanes of the constant together. 4516 EVT VT = Vector->getValueType(0); 4517 unsigned BitWidth = VT.getScalarSizeInBits(); 4518 4519 // If the splat value has been compressed to a bitlength lower 4520 // than the size of the vector lane, we need to re-expand it to 4521 // the lane size. 4522 if (BitWidth > SplatBitSize) 4523 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4524 SplatBitSize < BitWidth; 4525 SplatBitSize = SplatBitSize * 2) 4526 SplatValue |= SplatValue.shl(SplatBitSize); 4527 4528 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4529 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4530 if (SplatBitSize % BitWidth == 0) { 4531 Constant = APInt::getAllOnesValue(BitWidth); 4532 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4533 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4534 } 4535 } 4536 } 4537 4538 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4539 // actually legal and isn't going to get expanded, else this is a false 4540 // optimisation. 4541 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4542 Load->getValueType(0), 4543 Load->getMemoryVT()); 4544 4545 // Resize the constant to the same size as the original memory access before 4546 // extension. If it is still the AllOnesValue then this AND is completely 4547 // unneeded. 4548 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4549 4550 bool B; 4551 switch (Load->getExtensionType()) { 4552 default: B = false; break; 4553 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4554 case ISD::ZEXTLOAD: 4555 case ISD::NON_EXTLOAD: B = true; break; 4556 } 4557 4558 if (B && Constant.isAllOnesValue()) { 4559 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4560 // preserve semantics once we get rid of the AND. 4561 SDValue NewLoad(Load, 0); 4562 4563 // Fold the AND away. NewLoad may get replaced immediately. 4564 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4565 4566 if (Load->getExtensionType() == ISD::EXTLOAD) { 4567 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4568 Load->getValueType(0), SDLoc(Load), 4569 Load->getChain(), Load->getBasePtr(), 4570 Load->getOffset(), Load->getMemoryVT(), 4571 Load->getMemOperand()); 4572 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4573 if (Load->getNumValues() == 3) { 4574 // PRE/POST_INC loads have 3 values. 4575 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4576 NewLoad.getValue(2) }; 4577 CombineTo(Load, To, 3, true); 4578 } else { 4579 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4580 } 4581 } 4582 4583 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4584 } 4585 } 4586 4587 // fold (and (load x), 255) -> (zextload x, i8) 4588 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4589 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4590 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4591 (N0.getOpcode() == ISD::ANY_EXTEND && 4592 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4593 if (SDValue Res = ReduceLoadWidth(N)) { 4594 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4595 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4596 4597 AddToWorklist(N); 4598 CombineTo(LN0, Res, Res.getValue(1)); 4599 return SDValue(N, 0); 4600 } 4601 } 4602 4603 if (Level >= AfterLegalizeTypes) { 4604 // Attempt to propagate the AND back up to the leaves which, if they're 4605 // loads, can be combined to narrow loads and the AND node can be removed. 4606 // Perform after legalization so that extend nodes will already be 4607 // combined into the loads. 4608 if (BackwardsPropagateMask(N, DAG)) { 4609 return SDValue(N, 0); 4610 } 4611 } 4612 4613 if (SDValue Combined = visitANDLike(N0, N1, N)) 4614 return Combined; 4615 4616 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4617 if (N0.getOpcode() == N1.getOpcode()) 4618 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4619 return Tmp; 4620 4621 // Masking the negated extension of a boolean is just the zero-extended 4622 // boolean: 4623 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4624 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4625 // 4626 // Note: the SimplifyDemandedBits fold below can make an information-losing 4627 // transform, and then we have no way to find this better fold. 4628 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4629 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4630 SDValue SubRHS = N0.getOperand(1); 4631 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4632 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4633 return SubRHS; 4634 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4635 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4636 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4637 } 4638 } 4639 4640 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4641 // fold (and (sra)) -> (and (srl)) when possible. 4642 if (SimplifyDemandedBits(SDValue(N, 0))) 4643 return SDValue(N, 0); 4644 4645 // fold (zext_inreg (extload x)) -> (zextload x) 4646 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4647 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4648 EVT MemVT = LN0->getMemoryVT(); 4649 // If we zero all the possible extended bits, then we can turn this into 4650 // a zextload if we are running before legalize or the operation is legal. 4651 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4652 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4653 BitWidth - MemVT.getScalarSizeInBits())) && 4654 ((!LegalOperations && !LN0->isVolatile()) || 4655 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4656 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4657 LN0->getChain(), LN0->getBasePtr(), 4658 MemVT, LN0->getMemOperand()); 4659 AddToWorklist(N); 4660 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4661 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4662 } 4663 } 4664 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4665 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4666 N0.hasOneUse()) { 4667 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4668 EVT MemVT = LN0->getMemoryVT(); 4669 // If we zero all the possible extended bits, then we can turn this into 4670 // a zextload if we are running before legalize or the operation is legal. 4671 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4672 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4673 BitWidth - MemVT.getScalarSizeInBits())) && 4674 ((!LegalOperations && !LN0->isVolatile()) || 4675 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4676 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4677 LN0->getChain(), LN0->getBasePtr(), 4678 MemVT, LN0->getMemOperand()); 4679 AddToWorklist(N); 4680 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4681 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4682 } 4683 } 4684 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4685 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4686 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4687 N0.getOperand(1), false)) 4688 return BSwap; 4689 } 4690 4691 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 4692 return Shifts; 4693 4694 return SDValue(); 4695 } 4696 4697 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4698 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4699 bool DemandHighBits) { 4700 if (!LegalOperations) 4701 return SDValue(); 4702 4703 EVT VT = N->getValueType(0); 4704 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4705 return SDValue(); 4706 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4707 return SDValue(); 4708 4709 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4710 bool LookPassAnd0 = false; 4711 bool LookPassAnd1 = false; 4712 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4713 std::swap(N0, N1); 4714 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4715 std::swap(N0, N1); 4716 if (N0.getOpcode() == ISD::AND) { 4717 if (!N0.getNode()->hasOneUse()) 4718 return SDValue(); 4719 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4720 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 4721 // This is needed for X86. 4722 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 4723 N01C->getZExtValue() != 0xFFFF)) 4724 return SDValue(); 4725 N0 = N0.getOperand(0); 4726 LookPassAnd0 = true; 4727 } 4728 4729 if (N1.getOpcode() == ISD::AND) { 4730 if (!N1.getNode()->hasOneUse()) 4731 return SDValue(); 4732 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4733 if (!N11C || N11C->getZExtValue() != 0xFF) 4734 return SDValue(); 4735 N1 = N1.getOperand(0); 4736 LookPassAnd1 = true; 4737 } 4738 4739 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4740 std::swap(N0, N1); 4741 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4742 return SDValue(); 4743 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4744 return SDValue(); 4745 4746 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4747 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4748 if (!N01C || !N11C) 4749 return SDValue(); 4750 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4751 return SDValue(); 4752 4753 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4754 SDValue N00 = N0->getOperand(0); 4755 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4756 if (!N00.getNode()->hasOneUse()) 4757 return SDValue(); 4758 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4759 if (!N001C || N001C->getZExtValue() != 0xFF) 4760 return SDValue(); 4761 N00 = N00.getOperand(0); 4762 LookPassAnd0 = true; 4763 } 4764 4765 SDValue N10 = N1->getOperand(0); 4766 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4767 if (!N10.getNode()->hasOneUse()) 4768 return SDValue(); 4769 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4770 // Also allow 0xFFFF since the bits will be shifted out. This is needed 4771 // for X86. 4772 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 4773 N101C->getZExtValue() != 0xFFFF)) 4774 return SDValue(); 4775 N10 = N10.getOperand(0); 4776 LookPassAnd1 = true; 4777 } 4778 4779 if (N00 != N10) 4780 return SDValue(); 4781 4782 // Make sure everything beyond the low halfword gets set to zero since the SRL 4783 // 16 will clear the top bits. 4784 unsigned OpSizeInBits = VT.getSizeInBits(); 4785 if (DemandHighBits && OpSizeInBits > 16) { 4786 // If the left-shift isn't masked out then the only way this is a bswap is 4787 // if all bits beyond the low 8 are 0. In that case the entire pattern 4788 // reduces to a left shift anyway: leave it for other parts of the combiner. 4789 if (!LookPassAnd0) 4790 return SDValue(); 4791 4792 // However, if the right shift isn't masked out then it might be because 4793 // it's not needed. See if we can spot that too. 4794 if (!LookPassAnd1 && 4795 !DAG.MaskedValueIsZero( 4796 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4797 return SDValue(); 4798 } 4799 4800 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4801 if (OpSizeInBits > 16) { 4802 SDLoc DL(N); 4803 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4804 DAG.getConstant(OpSizeInBits - 16, DL, 4805 getShiftAmountTy(VT))); 4806 } 4807 return Res; 4808 } 4809 4810 /// Return true if the specified node is an element that makes up a 32-bit 4811 /// packed halfword byteswap. 4812 /// ((x & 0x000000ff) << 8) | 4813 /// ((x & 0x0000ff00) >> 8) | 4814 /// ((x & 0x00ff0000) << 8) | 4815 /// ((x & 0xff000000) >> 8) 4816 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4817 if (!N.getNode()->hasOneUse()) 4818 return false; 4819 4820 unsigned Opc = N.getOpcode(); 4821 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4822 return false; 4823 4824 SDValue N0 = N.getOperand(0); 4825 unsigned Opc0 = N0.getOpcode(); 4826 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4827 return false; 4828 4829 ConstantSDNode *N1C = nullptr; 4830 // SHL or SRL: look upstream for AND mask operand 4831 if (Opc == ISD::AND) 4832 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4833 else if (Opc0 == ISD::AND) 4834 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4835 if (!N1C) 4836 return false; 4837 4838 unsigned MaskByteOffset; 4839 switch (N1C->getZExtValue()) { 4840 default: 4841 return false; 4842 case 0xFF: MaskByteOffset = 0; break; 4843 case 0xFF00: MaskByteOffset = 1; break; 4844 case 0xFFFF: 4845 // In case demanded bits didn't clear the bits that will be shifted out. 4846 // This is needed for X86. 4847 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 4848 MaskByteOffset = 1; 4849 break; 4850 } 4851 return false; 4852 case 0xFF0000: MaskByteOffset = 2; break; 4853 case 0xFF000000: MaskByteOffset = 3; break; 4854 } 4855 4856 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4857 if (Opc == ISD::AND) { 4858 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4859 // (x >> 8) & 0xff 4860 // (x >> 8) & 0xff0000 4861 if (Opc0 != ISD::SRL) 4862 return false; 4863 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4864 if (!C || C->getZExtValue() != 8) 4865 return false; 4866 } else { 4867 // (x << 8) & 0xff00 4868 // (x << 8) & 0xff000000 4869 if (Opc0 != ISD::SHL) 4870 return false; 4871 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4872 if (!C || C->getZExtValue() != 8) 4873 return false; 4874 } 4875 } else if (Opc == ISD::SHL) { 4876 // (x & 0xff) << 8 4877 // (x & 0xff0000) << 8 4878 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4879 return false; 4880 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4881 if (!C || C->getZExtValue() != 8) 4882 return false; 4883 } else { // Opc == ISD::SRL 4884 // (x & 0xff00) >> 8 4885 // (x & 0xff000000) >> 8 4886 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4887 return false; 4888 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4889 if (!C || C->getZExtValue() != 8) 4890 return false; 4891 } 4892 4893 if (Parts[MaskByteOffset]) 4894 return false; 4895 4896 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4897 return true; 4898 } 4899 4900 /// Match a 32-bit packed halfword bswap. That is 4901 /// ((x & 0x000000ff) << 8) | 4902 /// ((x & 0x0000ff00) >> 8) | 4903 /// ((x & 0x00ff0000) << 8) | 4904 /// ((x & 0xff000000) >> 8) 4905 /// => (rotl (bswap x), 16) 4906 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4907 if (!LegalOperations) 4908 return SDValue(); 4909 4910 EVT VT = N->getValueType(0); 4911 if (VT != MVT::i32) 4912 return SDValue(); 4913 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4914 return SDValue(); 4915 4916 // Look for either 4917 // (or (or (and), (and)), (or (and), (and))) 4918 // (or (or (or (and), (and)), (and)), (and)) 4919 if (N0.getOpcode() != ISD::OR) 4920 return SDValue(); 4921 SDValue N00 = N0.getOperand(0); 4922 SDValue N01 = N0.getOperand(1); 4923 SDNode *Parts[4] = {}; 4924 4925 if (N1.getOpcode() == ISD::OR && 4926 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4927 // (or (or (and), (and)), (or (and), (and))) 4928 if (!isBSwapHWordElement(N00, Parts)) 4929 return SDValue(); 4930 4931 if (!isBSwapHWordElement(N01, Parts)) 4932 return SDValue(); 4933 SDValue N10 = N1.getOperand(0); 4934 if (!isBSwapHWordElement(N10, Parts)) 4935 return SDValue(); 4936 SDValue N11 = N1.getOperand(1); 4937 if (!isBSwapHWordElement(N11, Parts)) 4938 return SDValue(); 4939 } else { 4940 // (or (or (or (and), (and)), (and)), (and)) 4941 if (!isBSwapHWordElement(N1, Parts)) 4942 return SDValue(); 4943 if (!isBSwapHWordElement(N01, Parts)) 4944 return SDValue(); 4945 if (N00.getOpcode() != ISD::OR) 4946 return SDValue(); 4947 SDValue N000 = N00.getOperand(0); 4948 if (!isBSwapHWordElement(N000, Parts)) 4949 return SDValue(); 4950 SDValue N001 = N00.getOperand(1); 4951 if (!isBSwapHWordElement(N001, Parts)) 4952 return SDValue(); 4953 } 4954 4955 // Make sure the parts are all coming from the same node. 4956 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4957 return SDValue(); 4958 4959 SDLoc DL(N); 4960 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4961 SDValue(Parts[0], 0)); 4962 4963 // Result of the bswap should be rotated by 16. If it's not legal, then 4964 // do (x << 16) | (x >> 16). 4965 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4966 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4967 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4968 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4969 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4970 return DAG.getNode(ISD::OR, DL, VT, 4971 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4972 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4973 } 4974 4975 /// This contains all DAGCombine rules which reduce two values combined by 4976 /// an Or operation to a single value \see visitANDLike(). 4977 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4978 EVT VT = N1.getValueType(); 4979 SDLoc DL(N); 4980 4981 // fold (or x, undef) -> -1 4982 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4983 return DAG.getAllOnesConstant(DL, VT); 4984 4985 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4986 return V; 4987 4988 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4989 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4990 // Don't increase # computations. 4991 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4992 // We can only do this xform if we know that bits from X that are set in C2 4993 // but not in C1 are already zero. Likewise for Y. 4994 if (const ConstantSDNode *N0O1C = 4995 getAsNonOpaqueConstant(N0.getOperand(1))) { 4996 if (const ConstantSDNode *N1O1C = 4997 getAsNonOpaqueConstant(N1.getOperand(1))) { 4998 // We can only do this xform if we know that bits from X that are set in 4999 // C2 but not in C1 are already zero. Likewise for Y. 5000 const APInt &LHSMask = N0O1C->getAPIntValue(); 5001 const APInt &RHSMask = N1O1C->getAPIntValue(); 5002 5003 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 5004 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 5005 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5006 N0.getOperand(0), N1.getOperand(0)); 5007 return DAG.getNode(ISD::AND, DL, VT, X, 5008 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 5009 } 5010 } 5011 } 5012 } 5013 5014 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 5015 if (N0.getOpcode() == ISD::AND && 5016 N1.getOpcode() == ISD::AND && 5017 N0.getOperand(0) == N1.getOperand(0) && 5018 // Don't increase # computations. 5019 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 5020 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5021 N0.getOperand(1), N1.getOperand(1)); 5022 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 5023 } 5024 5025 return SDValue(); 5026 } 5027 5028 SDValue DAGCombiner::visitOR(SDNode *N) { 5029 SDValue N0 = N->getOperand(0); 5030 SDValue N1 = N->getOperand(1); 5031 EVT VT = N1.getValueType(); 5032 5033 // x | x --> x 5034 if (N0 == N1) 5035 return N0; 5036 5037 // fold vector ops 5038 if (VT.isVector()) { 5039 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5040 return FoldedVOp; 5041 5042 // fold (or x, 0) -> x, vector edition 5043 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5044 return N1; 5045 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5046 return N0; 5047 5048 // fold (or x, -1) -> -1, vector edition 5049 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5050 // do not return N0, because undef node may exist in N0 5051 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 5052 if (ISD::isBuildVectorAllOnes(N1.getNode())) 5053 // do not return N1, because undef node may exist in N1 5054 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 5055 5056 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 5057 // Do this only if the resulting shuffle is legal. 5058 if (isa<ShuffleVectorSDNode>(N0) && 5059 isa<ShuffleVectorSDNode>(N1) && 5060 // Avoid folding a node with illegal type. 5061 TLI.isTypeLegal(VT)) { 5062 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 5063 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 5064 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5065 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 5066 // Ensure both shuffles have a zero input. 5067 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 5068 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 5069 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 5070 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 5071 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 5072 bool CanFold = true; 5073 int NumElts = VT.getVectorNumElements(); 5074 SmallVector<int, 4> Mask(NumElts); 5075 5076 for (int i = 0; i != NumElts; ++i) { 5077 int M0 = SV0->getMaskElt(i); 5078 int M1 = SV1->getMaskElt(i); 5079 5080 // Determine if either index is pointing to a zero vector. 5081 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 5082 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 5083 5084 // If one element is zero and the otherside is undef, keep undef. 5085 // This also handles the case that both are undef. 5086 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 5087 Mask[i] = -1; 5088 continue; 5089 } 5090 5091 // Make sure only one of the elements is zero. 5092 if (M0Zero == M1Zero) { 5093 CanFold = false; 5094 break; 5095 } 5096 5097 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 5098 5099 // We have a zero and non-zero element. If the non-zero came from 5100 // SV0 make the index a LHS index. If it came from SV1, make it 5101 // a RHS index. We need to mod by NumElts because we don't care 5102 // which operand it came from in the original shuffles. 5103 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 5104 } 5105 5106 if (CanFold) { 5107 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 5108 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 5109 5110 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5111 if (!LegalMask) { 5112 std::swap(NewLHS, NewRHS); 5113 ShuffleVectorSDNode::commuteMask(Mask); 5114 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5115 } 5116 5117 if (LegalMask) 5118 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 5119 } 5120 } 5121 } 5122 } 5123 5124 // fold (or c1, c2) -> c1|c2 5125 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5126 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5127 if (N0C && N1C && !N1C->isOpaque()) 5128 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 5129 // canonicalize constant to RHS 5130 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5131 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5132 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 5133 // fold (or x, 0) -> x 5134 if (isNullConstant(N1)) 5135 return N0; 5136 // fold (or x, -1) -> -1 5137 if (isAllOnesConstant(N1)) 5138 return N1; 5139 5140 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5141 return NewSel; 5142 5143 // fold (or x, c) -> c iff (x & ~c) == 0 5144 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 5145 return N1; 5146 5147 if (SDValue Combined = visitORLike(N0, N1, N)) 5148 return Combined; 5149 5150 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 5151 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 5152 return BSwap; 5153 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 5154 return BSwap; 5155 5156 // reassociate or 5157 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) 5158 return ROR; 5159 5160 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 5161 // iff (c1 & c2) != 0. 5162 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 5163 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 5164 }; 5165 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5166 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 5167 if (SDValue COR = DAG.FoldConstantArithmetic( 5168 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 5169 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 5170 AddToWorklist(IOR.getNode()); 5171 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 5172 } 5173 } 5174 5175 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 5176 if (N0.getOpcode() == N1.getOpcode()) 5177 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5178 return Tmp; 5179 5180 // See if this is some rotate idiom. 5181 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 5182 return SDValue(Rot, 0); 5183 5184 if (SDValue Load = MatchLoadCombine(N)) 5185 return Load; 5186 5187 // Simplify the operands using demanded-bits information. 5188 if (SimplifyDemandedBits(SDValue(N, 0))) 5189 return SDValue(N, 0); 5190 5191 return SDValue(); 5192 } 5193 5194 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 5195 if (Op.getOpcode() == ISD::AND && 5196 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 5197 Mask = Op.getOperand(1); 5198 return Op.getOperand(0); 5199 } 5200 return Op; 5201 } 5202 5203 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 5204 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 5205 SDValue &Mask) { 5206 Op = stripConstantMask(DAG, Op, Mask); 5207 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 5208 Shift = Op; 5209 return true; 5210 } 5211 return false; 5212 } 5213 5214 /// Helper function for visitOR to extract the needed side of a rotate idiom 5215 /// from a shl/srl/mul/udiv. This is meant to handle cases where 5216 /// InstCombine merged some outside op with one of the shifts from 5217 /// the rotate pattern. 5218 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 5219 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 5220 /// patterns: 5221 /// 5222 /// (or (mul v c0) (shrl (mul v c1) c2)): 5223 /// expands (mul v c0) -> (shl (mul v c1) c3) 5224 /// 5225 /// (or (udiv v c0) (shl (udiv v c1) c2)): 5226 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 5227 /// 5228 /// (or (shl v c0) (shrl (shl v c1) c2)): 5229 /// expands (shl v c0) -> (shl (shl v c1) c3) 5230 /// 5231 /// (or (shrl v c0) (shl (shrl v c1) c2)): 5232 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 5233 /// 5234 /// Such that in all cases, c3+c2==bitwidth(op v c1). 5235 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 5236 SDValue ExtractFrom, SDValue &Mask, 5237 const SDLoc &DL) { 5238 assert(OppShift && ExtractFrom && "Empty SDValue"); 5239 assert( 5240 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 5241 "Existing shift must be valid as a rotate half"); 5242 5243 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 5244 // Preconditions: 5245 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 5246 // 5247 // Find opcode of the needed shift to be extracted from (op0 v c0). 5248 unsigned Opcode = ISD::DELETED_NODE; 5249 bool IsMulOrDiv = false; 5250 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 5251 // opcode or its arithmetic (mul or udiv) variant. 5252 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 5253 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 5254 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 5255 return false; 5256 Opcode = NeededShift; 5257 return true; 5258 }; 5259 // op0 must be either the needed shift opcode or the mul/udiv equivalent 5260 // that the needed shift can be extracted from. 5261 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 5262 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 5263 return SDValue(); 5264 5265 // op0 must be the same opcode on both sides, have the same LHS argument, 5266 // and produce the same value type. 5267 SDValue OppShiftLHS = OppShift.getOperand(0); 5268 EVT ShiftedVT = OppShiftLHS.getValueType(); 5269 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 5270 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 5271 ShiftedVT != ExtractFrom.getValueType()) 5272 return SDValue(); 5273 5274 // Amount of the existing shift. 5275 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 5276 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 5277 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 5278 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 5279 ConstantSDNode *ExtractFromCst = 5280 isConstOrConstSplat(ExtractFrom.getOperand(1)); 5281 // TODO: We should be able to handle non-uniform constant vectors for these values 5282 // Check that we have constant values. 5283 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 5284 !OppLHSCst || !OppLHSCst->getAPIntValue() || 5285 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 5286 return SDValue(); 5287 5288 // Compute the shift amount we need to extract to complete the rotate. 5289 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 5290 if (OppShiftCst->getAPIntValue().ugt(VTWidth)) 5291 return SDValue(); 5292 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 5293 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 5294 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 5295 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 5296 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 5297 5298 // Now try extract the needed shift from the ExtractFrom op and see if the 5299 // result matches up with the existing shift's LHS op. 5300 if (IsMulOrDiv) { 5301 // Op to extract from is a mul or udiv by a constant. 5302 // Check: 5303 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 5304 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 5305 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 5306 NeededShiftAmt.getZExtValue()); 5307 APInt ResultAmt; 5308 APInt Rem; 5309 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 5310 if (Rem != 0 || ResultAmt != OppLHSAmt) 5311 return SDValue(); 5312 } else { 5313 // Op to extract from is a shift by a constant. 5314 // Check: 5315 // c2 - (bitwidth(op0 v c0) - c1) == c0 5316 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 5317 ExtractFromAmt.getBitWidth())) 5318 return SDValue(); 5319 } 5320 5321 // Return the expanded shift op that should allow a rotate to be formed. 5322 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 5323 EVT ResVT = ExtractFrom.getValueType(); 5324 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 5325 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 5326 } 5327 5328 // Return true if we can prove that, whenever Neg and Pos are both in the 5329 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 5330 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 5331 // 5332 // (or (shift1 X, Neg), (shift2 X, Pos)) 5333 // 5334 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 5335 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 5336 // to consider shift amounts with defined behavior. 5337 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 5338 SelectionDAG &DAG) { 5339 // If EltSize is a power of 2 then: 5340 // 5341 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 5342 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 5343 // 5344 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 5345 // for the stronger condition: 5346 // 5347 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 5348 // 5349 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 5350 // we can just replace Neg with Neg' for the rest of the function. 5351 // 5352 // In other cases we check for the even stronger condition: 5353 // 5354 // Neg == EltSize - Pos [B] 5355 // 5356 // for all Neg and Pos. Note that the (or ...) then invokes undefined 5357 // behavior if Pos == 0 (and consequently Neg == EltSize). 5358 // 5359 // We could actually use [A] whenever EltSize is a power of 2, but the 5360 // only extra cases that it would match are those uninteresting ones 5361 // where Neg and Pos are never in range at the same time. E.g. for 5362 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 5363 // as well as (sub 32, Pos), but: 5364 // 5365 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 5366 // 5367 // always invokes undefined behavior for 32-bit X. 5368 // 5369 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 5370 unsigned MaskLoBits = 0; 5371 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 5372 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 5373 KnownBits Known; 5374 DAG.computeKnownBits(Neg.getOperand(0), Known); 5375 unsigned Bits = Log2_64(EltSize); 5376 if (NegC->getAPIntValue().getActiveBits() <= Bits && 5377 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 5378 Neg = Neg.getOperand(0); 5379 MaskLoBits = Bits; 5380 } 5381 } 5382 } 5383 5384 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 5385 if (Neg.getOpcode() != ISD::SUB) 5386 return false; 5387 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 5388 if (!NegC) 5389 return false; 5390 SDValue NegOp1 = Neg.getOperand(1); 5391 5392 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 5393 // Pos'. The truncation is redundant for the purpose of the equality. 5394 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 5395 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 5396 KnownBits Known; 5397 DAG.computeKnownBits(Pos.getOperand(0), Known); 5398 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 5399 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 5400 MaskLoBits)) 5401 Pos = Pos.getOperand(0); 5402 } 5403 } 5404 5405 // The condition we need is now: 5406 // 5407 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 5408 // 5409 // If NegOp1 == Pos then we need: 5410 // 5411 // EltSize & Mask == NegC & Mask 5412 // 5413 // (because "x & Mask" is a truncation and distributes through subtraction). 5414 APInt Width; 5415 if (Pos == NegOp1) 5416 Width = NegC->getAPIntValue(); 5417 5418 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 5419 // Then the condition we want to prove becomes: 5420 // 5421 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 5422 // 5423 // which, again because "x & Mask" is a truncation, becomes: 5424 // 5425 // NegC & Mask == (EltSize - PosC) & Mask 5426 // EltSize & Mask == (NegC + PosC) & Mask 5427 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 5428 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 5429 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 5430 else 5431 return false; 5432 } else 5433 return false; 5434 5435 // Now we just need to check that EltSize & Mask == Width & Mask. 5436 if (MaskLoBits) 5437 // EltSize & Mask is 0 since Mask is EltSize - 1. 5438 return Width.getLoBits(MaskLoBits) == 0; 5439 return Width == EltSize; 5440 } 5441 5442 // A subroutine of MatchRotate used once we have found an OR of two opposite 5443 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 5444 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 5445 // former being preferred if supported. InnerPos and InnerNeg are Pos and 5446 // Neg with outer conversions stripped away. 5447 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 5448 SDValue Neg, SDValue InnerPos, 5449 SDValue InnerNeg, unsigned PosOpcode, 5450 unsigned NegOpcode, const SDLoc &DL) { 5451 // fold (or (shl x, (*ext y)), 5452 // (srl x, (*ext (sub 32, y)))) -> 5453 // (rotl x, y) or (rotr x, (sub 32, y)) 5454 // 5455 // fold (or (shl x, (*ext (sub 32, y))), 5456 // (srl x, (*ext y))) -> 5457 // (rotr x, y) or (rotl x, (sub 32, y)) 5458 EVT VT = Shifted.getValueType(); 5459 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) { 5460 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 5461 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 5462 HasPos ? Pos : Neg).getNode(); 5463 } 5464 5465 return nullptr; 5466 } 5467 5468 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 5469 // idioms for rotate, and if the target supports rotation instructions, generate 5470 // a rot[lr]. 5471 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 5472 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 5473 EVT VT = LHS.getValueType(); 5474 if (!TLI.isTypeLegal(VT)) return nullptr; 5475 5476 // The target must have at least one rotate flavor. 5477 bool HasROTL = hasOperation(ISD::ROTL, VT); 5478 bool HasROTR = hasOperation(ISD::ROTR, VT); 5479 if (!HasROTL && !HasROTR) return nullptr; 5480 5481 // Check for truncated rotate. 5482 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 5483 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 5484 assert(LHS.getValueType() == RHS.getValueType()); 5485 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 5486 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 5487 SDValue(Rot, 0)).getNode(); 5488 } 5489 } 5490 5491 // Match "(X shl/srl V1) & V2" where V2 may not be present. 5492 SDValue LHSShift; // The shift. 5493 SDValue LHSMask; // AND value if any. 5494 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 5495 5496 SDValue RHSShift; // The shift. 5497 SDValue RHSMask; // AND value if any. 5498 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 5499 5500 // If neither side matched a rotate half, bail 5501 if (!LHSShift && !RHSShift) 5502 return nullptr; 5503 5504 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 5505 // side of the rotate, so try to handle that here. In all cases we need to 5506 // pass the matched shift from the opposite side to compute the opcode and 5507 // needed shift amount to extract. We still want to do this if both sides 5508 // matched a rotate half because one half may be a potential overshift that 5509 // can be broken down (ie if InstCombine merged two shl or srl ops into a 5510 // single one). 5511 5512 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 5513 if (LHSShift) 5514 if (SDValue NewRHSShift = 5515 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 5516 RHSShift = NewRHSShift; 5517 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 5518 if (RHSShift) 5519 if (SDValue NewLHSShift = 5520 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 5521 LHSShift = NewLHSShift; 5522 5523 // If a side is still missing, nothing else we can do. 5524 if (!RHSShift || !LHSShift) 5525 return nullptr; 5526 5527 // At this point we've matched or extracted a shift op on each side. 5528 5529 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 5530 return nullptr; // Not shifting the same value. 5531 5532 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 5533 return nullptr; // Shifts must disagree. 5534 5535 // Canonicalize shl to left side in a shl/srl pair. 5536 if (RHSShift.getOpcode() == ISD::SHL) { 5537 std::swap(LHS, RHS); 5538 std::swap(LHSShift, RHSShift); 5539 std::swap(LHSMask, RHSMask); 5540 } 5541 5542 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5543 SDValue LHSShiftArg = LHSShift.getOperand(0); 5544 SDValue LHSShiftAmt = LHSShift.getOperand(1); 5545 SDValue RHSShiftArg = RHSShift.getOperand(0); 5546 SDValue RHSShiftAmt = RHSShift.getOperand(1); 5547 5548 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 5549 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 5550 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 5551 ConstantSDNode *RHS) { 5552 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 5553 }; 5554 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 5555 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 5556 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 5557 5558 // If there is an AND of either shifted operand, apply it to the result. 5559 if (LHSMask.getNode() || RHSMask.getNode()) { 5560 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 5561 SDValue Mask = AllOnes; 5562 5563 if (LHSMask.getNode()) { 5564 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 5565 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5566 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 5567 } 5568 if (RHSMask.getNode()) { 5569 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 5570 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5571 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 5572 } 5573 5574 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 5575 } 5576 5577 return Rot.getNode(); 5578 } 5579 5580 // If there is a mask here, and we have a variable shift, we can't be sure 5581 // that we're masking out the right stuff. 5582 if (LHSMask.getNode() || RHSMask.getNode()) 5583 return nullptr; 5584 5585 // If the shift amount is sign/zext/any-extended just peel it off. 5586 SDValue LExtOp0 = LHSShiftAmt; 5587 SDValue RExtOp0 = RHSShiftAmt; 5588 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5589 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5590 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5591 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 5592 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5593 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5594 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5595 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 5596 LExtOp0 = LHSShiftAmt.getOperand(0); 5597 RExtOp0 = RHSShiftAmt.getOperand(0); 5598 } 5599 5600 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 5601 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 5602 if (TryL) 5603 return TryL; 5604 5605 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 5606 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 5607 if (TryR) 5608 return TryR; 5609 5610 return nullptr; 5611 } 5612 5613 namespace { 5614 5615 /// Represents known origin of an individual byte in load combine pattern. The 5616 /// value of the byte is either constant zero or comes from memory. 5617 struct ByteProvider { 5618 // For constant zero providers Load is set to nullptr. For memory providers 5619 // Load represents the node which loads the byte from memory. 5620 // ByteOffset is the offset of the byte in the value produced by the load. 5621 LoadSDNode *Load = nullptr; 5622 unsigned ByteOffset = 0; 5623 5624 ByteProvider() = default; 5625 5626 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5627 return ByteProvider(Load, ByteOffset); 5628 } 5629 5630 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5631 5632 bool isConstantZero() const { return !Load; } 5633 bool isMemory() const { return Load; } 5634 5635 bool operator==(const ByteProvider &Other) const { 5636 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5637 } 5638 5639 private: 5640 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5641 : Load(Load), ByteOffset(ByteOffset) {} 5642 }; 5643 5644 } // end anonymous namespace 5645 5646 /// Recursively traverses the expression calculating the origin of the requested 5647 /// byte of the given value. Returns None if the provider can't be calculated. 5648 /// 5649 /// For all the values except the root of the expression verifies that the value 5650 /// has exactly one use and if it's not true return None. This way if the origin 5651 /// of the byte is returned it's guaranteed that the values which contribute to 5652 /// the byte are not used outside of this expression. 5653 /// 5654 /// Because the parts of the expression are not allowed to have more than one 5655 /// use this function iterates over trees, not DAGs. So it never visits the same 5656 /// node more than once. 5657 static const Optional<ByteProvider> 5658 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5659 bool Root = false) { 5660 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5661 if (Depth == 10) 5662 return None; 5663 5664 if (!Root && !Op.hasOneUse()) 5665 return None; 5666 5667 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5668 unsigned BitWidth = Op.getValueSizeInBits(); 5669 if (BitWidth % 8 != 0) 5670 return None; 5671 unsigned ByteWidth = BitWidth / 8; 5672 assert(Index < ByteWidth && "invalid index requested"); 5673 (void) ByteWidth; 5674 5675 switch (Op.getOpcode()) { 5676 case ISD::OR: { 5677 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5678 if (!LHS) 5679 return None; 5680 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5681 if (!RHS) 5682 return None; 5683 5684 if (LHS->isConstantZero()) 5685 return RHS; 5686 if (RHS->isConstantZero()) 5687 return LHS; 5688 return None; 5689 } 5690 case ISD::SHL: { 5691 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5692 if (!ShiftOp) 5693 return None; 5694 5695 uint64_t BitShift = ShiftOp->getZExtValue(); 5696 if (BitShift % 8 != 0) 5697 return None; 5698 uint64_t ByteShift = BitShift / 8; 5699 5700 return Index < ByteShift 5701 ? ByteProvider::getConstantZero() 5702 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5703 Depth + 1); 5704 } 5705 case ISD::ANY_EXTEND: 5706 case ISD::SIGN_EXTEND: 5707 case ISD::ZERO_EXTEND: { 5708 SDValue NarrowOp = Op->getOperand(0); 5709 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5710 if (NarrowBitWidth % 8 != 0) 5711 return None; 5712 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5713 5714 if (Index >= NarrowByteWidth) 5715 return Op.getOpcode() == ISD::ZERO_EXTEND 5716 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5717 : None; 5718 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5719 } 5720 case ISD::BSWAP: 5721 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5722 Depth + 1); 5723 case ISD::LOAD: { 5724 auto L = cast<LoadSDNode>(Op.getNode()); 5725 if (L->isVolatile() || L->isIndexed()) 5726 return None; 5727 5728 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5729 if (NarrowBitWidth % 8 != 0) 5730 return None; 5731 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5732 5733 if (Index >= NarrowByteWidth) 5734 return L->getExtensionType() == ISD::ZEXTLOAD 5735 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5736 : None; 5737 return ByteProvider::getMemory(L, Index); 5738 } 5739 } 5740 5741 return None; 5742 } 5743 5744 /// Match a pattern where a wide type scalar value is loaded by several narrow 5745 /// loads and combined by shifts and ors. Fold it into a single load or a load 5746 /// and a BSWAP if the targets supports it. 5747 /// 5748 /// Assuming little endian target: 5749 /// i8 *a = ... 5750 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5751 /// => 5752 /// i32 val = *((i32)a) 5753 /// 5754 /// i8 *a = ... 5755 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5756 /// => 5757 /// i32 val = BSWAP(*((i32)a)) 5758 /// 5759 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5760 /// interact well with the worklist mechanism. When a part of the pattern is 5761 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5762 /// but the root node of the pattern which triggers the load combine is not 5763 /// necessarily a direct user of the changed node. For example, once the address 5764 /// of t28 load is reassociated load combine won't be triggered: 5765 /// t25: i32 = add t4, Constant:i32<2> 5766 /// t26: i64 = sign_extend t25 5767 /// t27: i64 = add t2, t26 5768 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5769 /// t29: i32 = zero_extend t28 5770 /// t32: i32 = shl t29, Constant:i8<8> 5771 /// t33: i32 = or t23, t32 5772 /// As a possible fix visitLoad can check if the load can be a part of a load 5773 /// combine pattern and add corresponding OR roots to the worklist. 5774 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5775 assert(N->getOpcode() == ISD::OR && 5776 "Can only match load combining against OR nodes"); 5777 5778 // Handles simple types only 5779 EVT VT = N->getValueType(0); 5780 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5781 return SDValue(); 5782 unsigned ByteWidth = VT.getSizeInBits() / 8; 5783 5784 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5785 // Before legalize we can introduce too wide illegal loads which will be later 5786 // split into legal sized loads. This enables us to combine i64 load by i8 5787 // patterns to a couple of i32 loads on 32 bit targets. 5788 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5789 return SDValue(); 5790 5791 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5792 unsigned BW, unsigned i) { return i; }; 5793 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5794 unsigned BW, unsigned i) { return BW - i - 1; }; 5795 5796 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5797 auto MemoryByteOffset = [&] (ByteProvider P) { 5798 assert(P.isMemory() && "Must be a memory byte provider"); 5799 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5800 assert(LoadBitWidth % 8 == 0 && 5801 "can only analyze providers for individual bytes not bit"); 5802 unsigned LoadByteWidth = LoadBitWidth / 8; 5803 return IsBigEndianTarget 5804 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5805 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5806 }; 5807 5808 Optional<BaseIndexOffset> Base; 5809 SDValue Chain; 5810 5811 SmallPtrSet<LoadSDNode *, 8> Loads; 5812 Optional<ByteProvider> FirstByteProvider; 5813 int64_t FirstOffset = INT64_MAX; 5814 5815 // Check if all the bytes of the OR we are looking at are loaded from the same 5816 // base address. Collect bytes offsets from Base address in ByteOffsets. 5817 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5818 for (unsigned i = 0; i < ByteWidth; i++) { 5819 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5820 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5821 return SDValue(); 5822 5823 LoadSDNode *L = P->Load; 5824 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5825 "Must be enforced by calculateByteProvider"); 5826 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5827 5828 // All loads must share the same chain 5829 SDValue LChain = L->getChain(); 5830 if (!Chain) 5831 Chain = LChain; 5832 else if (Chain != LChain) 5833 return SDValue(); 5834 5835 // Loads must share the same base address 5836 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 5837 int64_t ByteOffsetFromBase = 0; 5838 if (!Base) 5839 Base = Ptr; 5840 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5841 return SDValue(); 5842 5843 // Calculate the offset of the current byte from the base address 5844 ByteOffsetFromBase += MemoryByteOffset(*P); 5845 ByteOffsets[i] = ByteOffsetFromBase; 5846 5847 // Remember the first byte load 5848 if (ByteOffsetFromBase < FirstOffset) { 5849 FirstByteProvider = P; 5850 FirstOffset = ByteOffsetFromBase; 5851 } 5852 5853 Loads.insert(L); 5854 } 5855 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5856 "memory, so there must be at least one load which produces the value"); 5857 assert(Base && "Base address of the accessed memory location must be set"); 5858 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5859 5860 // Check if the bytes of the OR we are looking at match with either big or 5861 // little endian value load 5862 bool BigEndian = true, LittleEndian = true; 5863 for (unsigned i = 0; i < ByteWidth; i++) { 5864 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5865 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5866 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5867 if (!BigEndian && !LittleEndian) 5868 return SDValue(); 5869 } 5870 assert((BigEndian != LittleEndian) && "should be either or"); 5871 assert(FirstByteProvider && "must be set"); 5872 5873 // Ensure that the first byte is loaded from zero offset of the first load. 5874 // So the combined value can be loaded from the first load address. 5875 if (MemoryByteOffset(*FirstByteProvider) != 0) 5876 return SDValue(); 5877 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5878 5879 // The node we are looking at matches with the pattern, check if we can 5880 // replace it with a single load and bswap if needed. 5881 5882 // If the load needs byte swap check if the target supports it 5883 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5884 5885 // Before legalize we can introduce illegal bswaps which will be later 5886 // converted to an explicit bswap sequence. This way we end up with a single 5887 // load and byte shuffling instead of several loads and byte shuffling. 5888 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5889 return SDValue(); 5890 5891 // Check that a load of the wide type is both allowed and fast on the target 5892 bool Fast = false; 5893 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5894 VT, FirstLoad->getAddressSpace(), 5895 FirstLoad->getAlignment(), &Fast); 5896 if (!Allowed || !Fast) 5897 return SDValue(); 5898 5899 SDValue NewLoad = 5900 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5901 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5902 5903 // Transfer chain users from old loads to the new load. 5904 for (LoadSDNode *L : Loads) 5905 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5906 5907 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5908 } 5909 5910 // If the target has andn, bsl, or a similar bit-select instruction, 5911 // we want to unfold masked merge, with canonical pattern of: 5912 // | A | |B| 5913 // ((x ^ y) & m) ^ y 5914 // | D | 5915 // Into: 5916 // (x & m) | (y & ~m) 5917 // If y is a constant, and the 'andn' does not work with immediates, 5918 // we unfold into a different pattern: 5919 // ~(~x & m) & (m | y) 5920 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 5921 // the very least that breaks andnpd / andnps patterns, and because those 5922 // patterns are simplified in IR and shouldn't be created in the DAG 5923 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 5924 assert(N->getOpcode() == ISD::XOR); 5925 5926 // Don't touch 'not' (i.e. where y = -1). 5927 if (isAllOnesConstantOrAllOnesSplatConstant(N->getOperand(1))) 5928 return SDValue(); 5929 5930 EVT VT = N->getValueType(0); 5931 5932 // There are 3 commutable operators in the pattern, 5933 // so we have to deal with 8 possible variants of the basic pattern. 5934 SDValue X, Y, M; 5935 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 5936 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 5937 return false; 5938 SDValue Xor = And.getOperand(XorIdx); 5939 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 5940 return false; 5941 SDValue Xor0 = Xor.getOperand(0); 5942 SDValue Xor1 = Xor.getOperand(1); 5943 // Don't touch 'not' (i.e. where y = -1). 5944 if (isAllOnesConstantOrAllOnesSplatConstant(Xor1)) 5945 return false; 5946 if (Other == Xor0) 5947 std::swap(Xor0, Xor1); 5948 if (Other != Xor1) 5949 return false; 5950 X = Xor0; 5951 Y = Xor1; 5952 M = And.getOperand(XorIdx ? 0 : 1); 5953 return true; 5954 }; 5955 5956 SDValue N0 = N->getOperand(0); 5957 SDValue N1 = N->getOperand(1); 5958 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 5959 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 5960 return SDValue(); 5961 5962 // Don't do anything if the mask is constant. This should not be reachable. 5963 // InstCombine should have already unfolded this pattern, and DAGCombiner 5964 // probably shouldn't produce it, too. 5965 if (isa<ConstantSDNode>(M.getNode())) 5966 return SDValue(); 5967 5968 // We can transform if the target has AndNot 5969 if (!TLI.hasAndNot(M)) 5970 return SDValue(); 5971 5972 SDLoc DL(N); 5973 5974 // If Y is a constant, check that 'andn' works with immediates. 5975 if (!TLI.hasAndNot(Y)) { 5976 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 5977 // If not, we need to do a bit more work to make sure andn is still used. 5978 SDValue NotX = DAG.getNOT(DL, X, VT); 5979 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 5980 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 5981 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 5982 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 5983 } 5984 5985 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 5986 SDValue NotM = DAG.getNOT(DL, M, VT); 5987 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 5988 5989 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 5990 } 5991 5992 SDValue DAGCombiner::visitXOR(SDNode *N) { 5993 SDValue N0 = N->getOperand(0); 5994 SDValue N1 = N->getOperand(1); 5995 EVT VT = N0.getValueType(); 5996 5997 // fold vector ops 5998 if (VT.isVector()) { 5999 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6000 return FoldedVOp; 6001 6002 // fold (xor x, 0) -> x, vector edition 6003 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6004 return N1; 6005 if (ISD::isBuildVectorAllZeros(N1.getNode())) 6006 return N0; 6007 } 6008 6009 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 6010 if (N0.isUndef() && N1.isUndef()) 6011 return DAG.getConstant(0, SDLoc(N), VT); 6012 // fold (xor x, undef) -> undef 6013 if (N0.isUndef()) 6014 return N0; 6015 if (N1.isUndef()) 6016 return N1; 6017 // fold (xor c1, c2) -> c1^c2 6018 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6019 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 6020 if (N0C && N1C) 6021 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 6022 // canonicalize constant to RHS 6023 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 6024 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 6025 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 6026 // fold (xor x, 0) -> x 6027 if (isNullConstant(N1)) 6028 return N0; 6029 6030 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6031 return NewSel; 6032 6033 // reassociate xor 6034 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1, N->getFlags())) 6035 return RXOR; 6036 6037 // fold !(x cc y) -> (x !cc y) 6038 SDValue LHS, RHS, CC; 6039 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 6040 bool isInt = LHS.getValueType().isInteger(); 6041 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 6042 isInt); 6043 6044 if (!LegalOperations || 6045 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 6046 switch (N0.getOpcode()) { 6047 default: 6048 llvm_unreachable("Unhandled SetCC Equivalent!"); 6049 case ISD::SETCC: 6050 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 6051 case ISD::SELECT_CC: 6052 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 6053 N0.getOperand(3), NotCC); 6054 } 6055 } 6056 } 6057 6058 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 6059 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 6060 N0.getNode()->hasOneUse() && 6061 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 6062 SDValue V = N0.getOperand(0); 6063 SDLoc DL(N0); 6064 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 6065 DAG.getConstant(1, DL, V.getValueType())); 6066 AddToWorklist(V.getNode()); 6067 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 6068 } 6069 6070 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 6071 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 6072 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6073 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6074 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 6075 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6076 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6077 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6078 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6079 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6080 } 6081 } 6082 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 6083 if (isAllOnesConstant(N1) && N0.hasOneUse() && 6084 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6085 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6086 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 6087 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6088 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6089 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6090 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6091 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6092 } 6093 } 6094 // fold (xor (and x, y), y) -> (and (not x), y) 6095 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 6096 N0->getOperand(1) == N1) { 6097 SDValue X = N0->getOperand(0); 6098 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 6099 AddToWorklist(NotX.getNode()); 6100 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 6101 } 6102 6103 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 6104 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 6105 SDValue A = N0.getOpcode() == ISD::ADD ? N0 : N1; 6106 SDValue S = N0.getOpcode() == ISD::SRA ? N0 : N1; 6107 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 6108 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 6109 SDValue S0 = S.getOperand(0); 6110 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) { 6111 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6112 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 6113 if (C->getAPIntValue() == (OpSizeInBits - 1)) 6114 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 6115 } 6116 } 6117 } 6118 6119 // fold (xor x, x) -> 0 6120 if (N0 == N1) 6121 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 6122 6123 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 6124 // Here is a concrete example of this equivalence: 6125 // i16 x == 14 6126 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 6127 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 6128 // 6129 // => 6130 // 6131 // i16 ~1 == 0b1111111111111110 6132 // i16 rol(~1, 14) == 0b1011111111111111 6133 // 6134 // Some additional tips to help conceptualize this transform: 6135 // - Try to see the operation as placing a single zero in a value of all ones. 6136 // - There exists no value for x which would allow the result to contain zero. 6137 // - Values of x larger than the bitwidth are undefined and do not require a 6138 // consistent result. 6139 // - Pushing the zero left requires shifting one bits in from the right. 6140 // A rotate left of ~1 is a nice way of achieving the desired result. 6141 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 6142 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 6143 SDLoc DL(N); 6144 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 6145 N0.getOperand(1)); 6146 } 6147 6148 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 6149 if (N0.getOpcode() == N1.getOpcode()) 6150 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 6151 return Tmp; 6152 6153 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 6154 if (SDValue MM = unfoldMaskedMerge(N)) 6155 return MM; 6156 6157 // Simplify the expression using non-local knowledge. 6158 if (SimplifyDemandedBits(SDValue(N, 0))) 6159 return SDValue(N, 0); 6160 6161 return SDValue(); 6162 } 6163 6164 /// Handle transforms common to the three shifts, when the shift amount is a 6165 /// constant. 6166 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 6167 SDNode *LHS = N->getOperand(0).getNode(); 6168 if (!LHS->hasOneUse()) return SDValue(); 6169 6170 // We want to pull some binops through shifts, so that we have (and (shift)) 6171 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 6172 // thing happens with address calculations, so it's important to canonicalize 6173 // it. 6174 bool HighBitSet = false; // Can we transform this if the high bit is set? 6175 6176 switch (LHS->getOpcode()) { 6177 default: return SDValue(); 6178 case ISD::OR: 6179 case ISD::XOR: 6180 HighBitSet = false; // We can only transform sra if the high bit is clear. 6181 break; 6182 case ISD::AND: 6183 HighBitSet = true; // We can only transform sra if the high bit is set. 6184 break; 6185 case ISD::ADD: 6186 if (N->getOpcode() != ISD::SHL) 6187 return SDValue(); // only shl(add) not sr[al](add). 6188 HighBitSet = false; // We can only transform sra if the high bit is clear. 6189 break; 6190 } 6191 6192 // We require the RHS of the binop to be a constant and not opaque as well. 6193 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 6194 if (!BinOpCst) return SDValue(); 6195 6196 // FIXME: disable this unless the input to the binop is a shift by a constant 6197 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 6198 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 6199 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 6200 BinOpLHSVal->getOpcode() == ISD::SRA || 6201 BinOpLHSVal->getOpcode() == ISD::SRL; 6202 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 6203 BinOpLHSVal->getOpcode() == ISD::SELECT; 6204 6205 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 6206 !isCopyOrSelect) 6207 return SDValue(); 6208 6209 if (isCopyOrSelect && N->hasOneUse()) 6210 return SDValue(); 6211 6212 EVT VT = N->getValueType(0); 6213 6214 // If this is a signed shift right, and the high bit is modified by the 6215 // logical operation, do not perform the transformation. The highBitSet 6216 // boolean indicates the value of the high bit of the constant which would 6217 // cause it to be modified for this operation. 6218 if (N->getOpcode() == ISD::SRA) { 6219 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 6220 if (BinOpRHSSignSet != HighBitSet) 6221 return SDValue(); 6222 } 6223 6224 if (!TLI.isDesirableToCommuteWithShift(N, Level)) 6225 return SDValue(); 6226 6227 // Fold the constants, shifting the binop RHS by the shift amount. 6228 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 6229 N->getValueType(0), 6230 LHS->getOperand(1), N->getOperand(1)); 6231 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 6232 6233 // Create the new shift. 6234 SDValue NewShift = DAG.getNode(N->getOpcode(), 6235 SDLoc(LHS->getOperand(0)), 6236 VT, LHS->getOperand(0), N->getOperand(1)); 6237 6238 // Create the new binop. 6239 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 6240 } 6241 6242 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 6243 assert(N->getOpcode() == ISD::TRUNCATE); 6244 assert(N->getOperand(0).getOpcode() == ISD::AND); 6245 6246 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 6247 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 6248 SDValue N01 = N->getOperand(0).getOperand(1); 6249 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 6250 SDLoc DL(N); 6251 EVT TruncVT = N->getValueType(0); 6252 SDValue N00 = N->getOperand(0).getOperand(0); 6253 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 6254 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 6255 AddToWorklist(Trunc00.getNode()); 6256 AddToWorklist(Trunc01.getNode()); 6257 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 6258 } 6259 } 6260 6261 return SDValue(); 6262 } 6263 6264 SDValue DAGCombiner::visitRotate(SDNode *N) { 6265 SDLoc dl(N); 6266 SDValue N0 = N->getOperand(0); 6267 SDValue N1 = N->getOperand(1); 6268 EVT VT = N->getValueType(0); 6269 unsigned Bitsize = VT.getScalarSizeInBits(); 6270 6271 // fold (rot x, 0) -> x 6272 if (isNullConstantOrNullSplatConstant(N1)) 6273 return N0; 6274 6275 // fold (rot x, c) -> (rot x, c % BitSize) 6276 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 6277 if (Cst->getAPIntValue().uge(Bitsize)) { 6278 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 6279 return DAG.getNode(N->getOpcode(), dl, VT, N0, 6280 DAG.getConstant(RotAmt, dl, N1.getValueType())); 6281 } 6282 } 6283 6284 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 6285 if (N1.getOpcode() == ISD::TRUNCATE && 6286 N1.getOperand(0).getOpcode() == ISD::AND) { 6287 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6288 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 6289 } 6290 6291 unsigned NextOp = N0.getOpcode(); 6292 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 6293 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 6294 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 6295 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 6296 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 6297 EVT ShiftVT = C1->getValueType(0); 6298 bool SameSide = (N->getOpcode() == NextOp); 6299 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 6300 if (SDValue CombinedShift = 6301 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 6302 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 6303 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 6304 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 6305 BitsizeC.getNode()); 6306 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 6307 CombinedShiftNorm); 6308 } 6309 } 6310 } 6311 return SDValue(); 6312 } 6313 6314 SDValue DAGCombiner::visitSHL(SDNode *N) { 6315 SDValue N0 = N->getOperand(0); 6316 SDValue N1 = N->getOperand(1); 6317 EVT VT = N0.getValueType(); 6318 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6319 6320 // fold vector ops 6321 if (VT.isVector()) { 6322 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6323 return FoldedVOp; 6324 6325 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 6326 // If setcc produces all-one true value then: 6327 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 6328 if (N1CV && N1CV->isConstant()) { 6329 if (N0.getOpcode() == ISD::AND) { 6330 SDValue N00 = N0->getOperand(0); 6331 SDValue N01 = N0->getOperand(1); 6332 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 6333 6334 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 6335 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 6336 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6337 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 6338 N01CV, N1CV)) 6339 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 6340 } 6341 } 6342 } 6343 } 6344 6345 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6346 6347 // fold (shl c1, c2) -> c1<<c2 6348 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6349 if (N0C && N1C && !N1C->isOpaque()) 6350 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 6351 // fold (shl 0, x) -> 0 6352 if (isNullConstantOrNullSplatConstant(N0)) 6353 return N0; 6354 // fold (shl x, c >= size(x)) -> undef 6355 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6356 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6357 return Val->getAPIntValue().uge(OpSizeInBits); 6358 }; 6359 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6360 return DAG.getUNDEF(VT); 6361 // fold (shl x, 0) -> x 6362 if (N1C && N1C->isNullValue()) 6363 return N0; 6364 // fold (shl undef, x) -> 0 6365 if (N0.isUndef()) 6366 return DAG.getConstant(0, SDLoc(N), VT); 6367 6368 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6369 return NewSel; 6370 6371 // if (shl x, c) is known to be zero, return 0 6372 if (DAG.MaskedValueIsZero(SDValue(N, 0), 6373 APInt::getAllOnesValue(OpSizeInBits))) 6374 return DAG.getConstant(0, SDLoc(N), VT); 6375 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 6376 if (N1.getOpcode() == ISD::TRUNCATE && 6377 N1.getOperand(0).getOpcode() == ISD::AND) { 6378 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6379 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 6380 } 6381 6382 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6383 return SDValue(N, 0); 6384 6385 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 6386 if (N0.getOpcode() == ISD::SHL) { 6387 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6388 ConstantSDNode *RHS) { 6389 APInt c1 = LHS->getAPIntValue(); 6390 APInt c2 = RHS->getAPIntValue(); 6391 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6392 return (c1 + c2).uge(OpSizeInBits); 6393 }; 6394 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6395 return DAG.getConstant(0, SDLoc(N), VT); 6396 6397 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6398 ConstantSDNode *RHS) { 6399 APInt c1 = LHS->getAPIntValue(); 6400 APInt c2 = RHS->getAPIntValue(); 6401 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6402 return (c1 + c2).ult(OpSizeInBits); 6403 }; 6404 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6405 SDLoc DL(N); 6406 EVT ShiftVT = N1.getValueType(); 6407 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6408 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 6409 } 6410 } 6411 6412 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 6413 // For this to be valid, the second form must not preserve any of the bits 6414 // that are shifted out by the inner shift in the first form. This means 6415 // the outer shift size must be >= the number of bits added by the ext. 6416 // As a corollary, we don't care what kind of ext it is. 6417 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 6418 N0.getOpcode() == ISD::ANY_EXTEND || 6419 N0.getOpcode() == ISD::SIGN_EXTEND) && 6420 N0.getOperand(0).getOpcode() == ISD::SHL) { 6421 SDValue N0Op0 = N0.getOperand(0); 6422 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6423 APInt c1 = N0Op0C1->getAPIntValue(); 6424 APInt c2 = N1C->getAPIntValue(); 6425 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6426 6427 EVT InnerShiftVT = N0Op0.getValueType(); 6428 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6429 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 6430 SDLoc DL(N0); 6431 APInt Sum = c1 + c2; 6432 if (Sum.uge(OpSizeInBits)) 6433 return DAG.getConstant(0, DL, VT); 6434 6435 return DAG.getNode( 6436 ISD::SHL, DL, VT, 6437 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 6438 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 6439 } 6440 } 6441 } 6442 6443 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 6444 // Only fold this if the inner zext has no other uses to avoid increasing 6445 // the total number of instructions. 6446 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 6447 N0.getOperand(0).getOpcode() == ISD::SRL) { 6448 SDValue N0Op0 = N0.getOperand(0); 6449 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6450 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 6451 uint64_t c1 = N0Op0C1->getZExtValue(); 6452 uint64_t c2 = N1C->getZExtValue(); 6453 if (c1 == c2) { 6454 SDValue NewOp0 = N0.getOperand(0); 6455 EVT CountVT = NewOp0.getOperand(1).getValueType(); 6456 SDLoc DL(N); 6457 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 6458 NewOp0, 6459 DAG.getConstant(c2, DL, CountVT)); 6460 AddToWorklist(NewSHL.getNode()); 6461 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 6462 } 6463 } 6464 } 6465 } 6466 6467 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 6468 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 6469 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 6470 N0->getFlags().hasExact()) { 6471 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6472 uint64_t C1 = N0C1->getZExtValue(); 6473 uint64_t C2 = N1C->getZExtValue(); 6474 SDLoc DL(N); 6475 if (C1 <= C2) 6476 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6477 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 6478 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 6479 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 6480 } 6481 } 6482 6483 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 6484 // (and (srl x, (sub c1, c2), MASK) 6485 // Only fold this if the inner shift has no other uses -- if it does, folding 6486 // this will increase the total number of instructions. 6487 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6488 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6489 uint64_t c1 = N0C1->getZExtValue(); 6490 if (c1 < OpSizeInBits) { 6491 uint64_t c2 = N1C->getZExtValue(); 6492 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 6493 SDValue Shift; 6494 if (c2 > c1) { 6495 Mask <<= c2 - c1; 6496 SDLoc DL(N); 6497 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6498 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 6499 } else { 6500 Mask.lshrInPlace(c1 - c2); 6501 SDLoc DL(N); 6502 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 6503 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 6504 } 6505 SDLoc DL(N0); 6506 return DAG.getNode(ISD::AND, DL, VT, Shift, 6507 DAG.getConstant(Mask, DL, VT)); 6508 } 6509 } 6510 } 6511 6512 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 6513 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 6514 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 6515 SDLoc DL(N); 6516 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 6517 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 6518 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 6519 } 6520 6521 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 6522 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 6523 // Variant of version done on multiply, except mul by a power of 2 is turned 6524 // into a shift. 6525 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 6526 N0.getNode()->hasOneUse() && 6527 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6528 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 6529 TLI.isDesirableToCommuteWithShift(N, Level)) { 6530 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 6531 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6532 AddToWorklist(Shl0.getNode()); 6533 AddToWorklist(Shl1.getNode()); 6534 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 6535 } 6536 6537 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 6538 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 6539 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6540 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 6541 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6542 if (isConstantOrConstantVector(Shl)) 6543 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 6544 } 6545 6546 if (N1C && !N1C->isOpaque()) 6547 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 6548 return NewSHL; 6549 6550 return SDValue(); 6551 } 6552 6553 SDValue DAGCombiner::visitSRA(SDNode *N) { 6554 SDValue N0 = N->getOperand(0); 6555 SDValue N1 = N->getOperand(1); 6556 EVT VT = N0.getValueType(); 6557 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6558 6559 // Arithmetic shifting an all-sign-bit value is a no-op. 6560 // fold (sra 0, x) -> 0 6561 // fold (sra -1, x) -> -1 6562 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 6563 return N0; 6564 6565 // fold vector ops 6566 if (VT.isVector()) 6567 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6568 return FoldedVOp; 6569 6570 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6571 6572 // fold (sra c1, c2) -> (sra c1, c2) 6573 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6574 if (N0C && N1C && !N1C->isOpaque()) 6575 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 6576 // fold (sra x, c >= size(x)) -> undef 6577 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6578 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6579 return Val->getAPIntValue().uge(OpSizeInBits); 6580 }; 6581 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6582 return DAG.getUNDEF(VT); 6583 // fold (sra x, 0) -> x 6584 if (N1C && N1C->isNullValue()) 6585 return N0; 6586 6587 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6588 return NewSel; 6589 6590 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 6591 // sext_inreg. 6592 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 6593 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 6594 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 6595 if (VT.isVector()) 6596 ExtVT = EVT::getVectorVT(*DAG.getContext(), 6597 ExtVT, VT.getVectorNumElements()); 6598 if ((!LegalOperations || 6599 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 6600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6601 N0.getOperand(0), DAG.getValueType(ExtVT)); 6602 } 6603 6604 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 6605 // clamp (add c1, c2) to max shift. 6606 if (N0.getOpcode() == ISD::SRA) { 6607 SDLoc DL(N); 6608 EVT ShiftVT = N1.getValueType(); 6609 EVT ShiftSVT = ShiftVT.getScalarType(); 6610 SmallVector<SDValue, 16> ShiftValues; 6611 6612 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { 6613 APInt c1 = LHS->getAPIntValue(); 6614 APInt c2 = RHS->getAPIntValue(); 6615 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6616 APInt Sum = c1 + c2; 6617 unsigned ShiftSum = 6618 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); 6619 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); 6620 return true; 6621 }; 6622 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { 6623 SDValue ShiftValue; 6624 if (VT.isVector()) 6625 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); 6626 else 6627 ShiftValue = ShiftValues[0]; 6628 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); 6629 } 6630 } 6631 6632 // fold (sra (shl X, m), (sub result_size, n)) 6633 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 6634 // result_size - n != m. 6635 // If truncate is free for the target sext(shl) is likely to result in better 6636 // code. 6637 if (N0.getOpcode() == ISD::SHL && N1C) { 6638 // Get the two constanst of the shifts, CN0 = m, CN = n. 6639 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 6640 if (N01C) { 6641 LLVMContext &Ctx = *DAG.getContext(); 6642 // Determine what the truncate's result bitsize and type would be. 6643 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 6644 6645 if (VT.isVector()) 6646 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 6647 6648 // Determine the residual right-shift amount. 6649 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 6650 6651 // If the shift is not a no-op (in which case this should be just a sign 6652 // extend already), the truncated to type is legal, sign_extend is legal 6653 // on that type, and the truncate to that type is both legal and free, 6654 // perform the transform. 6655 if ((ShiftAmt > 0) && 6656 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 6657 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 6658 TLI.isTruncateFree(VT, TruncVT)) { 6659 SDLoc DL(N); 6660 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 6661 getShiftAmountTy(N0.getOperand(0).getValueType())); 6662 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 6663 N0.getOperand(0), Amt); 6664 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 6665 Shift); 6666 return DAG.getNode(ISD::SIGN_EXTEND, DL, 6667 N->getValueType(0), Trunc); 6668 } 6669 } 6670 } 6671 6672 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 6673 if (N1.getOpcode() == ISD::TRUNCATE && 6674 N1.getOperand(0).getOpcode() == ISD::AND) { 6675 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6676 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 6677 } 6678 6679 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 6680 // if c1 is equal to the number of bits the trunc removes 6681 if (N0.getOpcode() == ISD::TRUNCATE && 6682 (N0.getOperand(0).getOpcode() == ISD::SRL || 6683 N0.getOperand(0).getOpcode() == ISD::SRA) && 6684 N0.getOperand(0).hasOneUse() && 6685 N0.getOperand(0).getOperand(1).hasOneUse() && 6686 N1C) { 6687 SDValue N0Op0 = N0.getOperand(0); 6688 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 6689 unsigned LargeShiftVal = LargeShift->getZExtValue(); 6690 EVT LargeVT = N0Op0.getValueType(); 6691 6692 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 6693 SDLoc DL(N); 6694 SDValue Amt = 6695 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 6696 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 6697 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 6698 N0Op0.getOperand(0), Amt); 6699 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 6700 } 6701 } 6702 } 6703 6704 // Simplify, based on bits shifted out of the LHS. 6705 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6706 return SDValue(N, 0); 6707 6708 // If the sign bit is known to be zero, switch this to a SRL. 6709 if (DAG.SignBitIsZero(N0)) 6710 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 6711 6712 if (N1C && !N1C->isOpaque()) 6713 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 6714 return NewSRA; 6715 6716 return SDValue(); 6717 } 6718 6719 SDValue DAGCombiner::visitSRL(SDNode *N) { 6720 SDValue N0 = N->getOperand(0); 6721 SDValue N1 = N->getOperand(1); 6722 EVT VT = N0.getValueType(); 6723 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6724 6725 // fold vector ops 6726 if (VT.isVector()) 6727 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6728 return FoldedVOp; 6729 6730 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6731 6732 // fold (srl c1, c2) -> c1 >>u c2 6733 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6734 if (N0C && N1C && !N1C->isOpaque()) 6735 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6736 // fold (srl 0, x) -> 0 6737 if (isNullConstantOrNullSplatConstant(N0)) 6738 return N0; 6739 // fold (srl x, c >= size(x)) -> undef 6740 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6741 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6742 return Val->getAPIntValue().uge(OpSizeInBits); 6743 }; 6744 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6745 return DAG.getUNDEF(VT); 6746 // fold (srl x, 0) -> x 6747 if (N1C && N1C->isNullValue()) 6748 return N0; 6749 6750 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6751 return NewSel; 6752 6753 // if (srl x, c) is known to be zero, return 0 6754 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6755 APInt::getAllOnesValue(OpSizeInBits))) 6756 return DAG.getConstant(0, SDLoc(N), VT); 6757 6758 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6759 if (N0.getOpcode() == ISD::SRL) { 6760 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6761 ConstantSDNode *RHS) { 6762 APInt c1 = LHS->getAPIntValue(); 6763 APInt c2 = RHS->getAPIntValue(); 6764 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6765 return (c1 + c2).uge(OpSizeInBits); 6766 }; 6767 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6768 return DAG.getConstant(0, SDLoc(N), VT); 6769 6770 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6771 ConstantSDNode *RHS) { 6772 APInt c1 = LHS->getAPIntValue(); 6773 APInt c2 = RHS->getAPIntValue(); 6774 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6775 return (c1 + c2).ult(OpSizeInBits); 6776 }; 6777 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6778 SDLoc DL(N); 6779 EVT ShiftVT = N1.getValueType(); 6780 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6781 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6782 } 6783 } 6784 6785 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6786 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6787 N0.getOperand(0).getOpcode() == ISD::SRL) { 6788 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6789 uint64_t c1 = N001C->getZExtValue(); 6790 uint64_t c2 = N1C->getZExtValue(); 6791 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6792 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6793 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6794 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6795 if (c1 + OpSizeInBits == InnerShiftSize) { 6796 SDLoc DL(N0); 6797 if (c1 + c2 >= InnerShiftSize) 6798 return DAG.getConstant(0, DL, VT); 6799 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6800 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6801 N0.getOperand(0).getOperand(0), 6802 DAG.getConstant(c1 + c2, DL, 6803 ShiftCountVT))); 6804 } 6805 } 6806 } 6807 6808 // fold (srl (shl x, c), c) -> (and x, cst2) 6809 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6810 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6811 SDLoc DL(N); 6812 SDValue Mask = 6813 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6814 AddToWorklist(Mask.getNode()); 6815 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6816 } 6817 6818 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6819 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6820 // Shifting in all undef bits? 6821 EVT SmallVT = N0.getOperand(0).getValueType(); 6822 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6823 if (N1C->getZExtValue() >= BitSize) 6824 return DAG.getUNDEF(VT); 6825 6826 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6827 uint64_t ShiftAmt = N1C->getZExtValue(); 6828 SDLoc DL0(N0); 6829 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6830 N0.getOperand(0), 6831 DAG.getConstant(ShiftAmt, DL0, 6832 getShiftAmountTy(SmallVT))); 6833 AddToWorklist(SmallShift.getNode()); 6834 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6835 SDLoc DL(N); 6836 return DAG.getNode(ISD::AND, DL, VT, 6837 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6838 DAG.getConstant(Mask, DL, VT)); 6839 } 6840 } 6841 6842 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6843 // bit, which is unmodified by sra. 6844 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6845 if (N0.getOpcode() == ISD::SRA) 6846 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6847 } 6848 6849 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6850 if (N1C && N0.getOpcode() == ISD::CTLZ && 6851 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6852 KnownBits Known; 6853 DAG.computeKnownBits(N0.getOperand(0), Known); 6854 6855 // If any of the input bits are KnownOne, then the input couldn't be all 6856 // zeros, thus the result of the srl will always be zero. 6857 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6858 6859 // If all of the bits input the to ctlz node are known to be zero, then 6860 // the result of the ctlz is "32" and the result of the shift is one. 6861 APInt UnknownBits = ~Known.Zero; 6862 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6863 6864 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6865 if (UnknownBits.isPowerOf2()) { 6866 // Okay, we know that only that the single bit specified by UnknownBits 6867 // could be set on input to the CTLZ node. If this bit is set, the SRL 6868 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6869 // to an SRL/XOR pair, which is likely to simplify more. 6870 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6871 SDValue Op = N0.getOperand(0); 6872 6873 if (ShAmt) { 6874 SDLoc DL(N0); 6875 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6876 DAG.getConstant(ShAmt, DL, 6877 getShiftAmountTy(Op.getValueType()))); 6878 AddToWorklist(Op.getNode()); 6879 } 6880 6881 SDLoc DL(N); 6882 return DAG.getNode(ISD::XOR, DL, VT, 6883 Op, DAG.getConstant(1, DL, VT)); 6884 } 6885 } 6886 6887 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6888 if (N1.getOpcode() == ISD::TRUNCATE && 6889 N1.getOperand(0).getOpcode() == ISD::AND) { 6890 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6891 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6892 } 6893 6894 // fold operands of srl based on knowledge that the low bits are not 6895 // demanded. 6896 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6897 return SDValue(N, 0); 6898 6899 if (N1C && !N1C->isOpaque()) 6900 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6901 return NewSRL; 6902 6903 // Attempt to convert a srl of a load into a narrower zero-extending load. 6904 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6905 return NarrowLoad; 6906 6907 // Here is a common situation. We want to optimize: 6908 // 6909 // %a = ... 6910 // %b = and i32 %a, 2 6911 // %c = srl i32 %b, 1 6912 // brcond i32 %c ... 6913 // 6914 // into 6915 // 6916 // %a = ... 6917 // %b = and %a, 2 6918 // %c = setcc eq %b, 0 6919 // brcond %c ... 6920 // 6921 // However when after the source operand of SRL is optimized into AND, the SRL 6922 // itself may not be optimized further. Look for it and add the BRCOND into 6923 // the worklist. 6924 if (N->hasOneUse()) { 6925 SDNode *Use = *N->use_begin(); 6926 if (Use->getOpcode() == ISD::BRCOND) 6927 AddToWorklist(Use); 6928 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6929 // Also look pass the truncate. 6930 Use = *Use->use_begin(); 6931 if (Use->getOpcode() == ISD::BRCOND) 6932 AddToWorklist(Use); 6933 } 6934 } 6935 6936 return SDValue(); 6937 } 6938 6939 SDValue DAGCombiner::visitABS(SDNode *N) { 6940 SDValue N0 = N->getOperand(0); 6941 EVT VT = N->getValueType(0); 6942 6943 // fold (abs c1) -> c2 6944 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6945 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6946 // fold (abs (abs x)) -> (abs x) 6947 if (N0.getOpcode() == ISD::ABS) 6948 return N0; 6949 // fold (abs x) -> x iff not-negative 6950 if (DAG.SignBitIsZero(N0)) 6951 return N0; 6952 return SDValue(); 6953 } 6954 6955 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6956 SDValue N0 = N->getOperand(0); 6957 EVT VT = N->getValueType(0); 6958 6959 // fold (bswap c1) -> c2 6960 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6961 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6962 // fold (bswap (bswap x)) -> x 6963 if (N0.getOpcode() == ISD::BSWAP) 6964 return N0->getOperand(0); 6965 return SDValue(); 6966 } 6967 6968 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6969 SDValue N0 = N->getOperand(0); 6970 EVT VT = N->getValueType(0); 6971 6972 // fold (bitreverse c1) -> c2 6973 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6974 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6975 // fold (bitreverse (bitreverse x)) -> x 6976 if (N0.getOpcode() == ISD::BITREVERSE) 6977 return N0.getOperand(0); 6978 return SDValue(); 6979 } 6980 6981 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6982 SDValue N0 = N->getOperand(0); 6983 EVT VT = N->getValueType(0); 6984 6985 // fold (ctlz c1) -> c2 6986 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6987 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6988 6989 // If the value is known never to be zero, switch to the undef version. 6990 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 6991 if (DAG.isKnownNeverZero(N0)) 6992 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6993 } 6994 6995 return SDValue(); 6996 } 6997 6998 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6999 SDValue N0 = N->getOperand(0); 7000 EVT VT = N->getValueType(0); 7001 7002 // fold (ctlz_zero_undef c1) -> c2 7003 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7004 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7005 return SDValue(); 7006 } 7007 7008 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 7009 SDValue N0 = N->getOperand(0); 7010 EVT VT = N->getValueType(0); 7011 7012 // fold (cttz c1) -> c2 7013 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7014 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 7015 7016 // If the value is known never to be zero, switch to the undef version. 7017 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 7018 if (DAG.isKnownNeverZero(N0)) 7019 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7020 } 7021 7022 return SDValue(); 7023 } 7024 7025 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 7026 SDValue N0 = N->getOperand(0); 7027 EVT VT = N->getValueType(0); 7028 7029 // fold (cttz_zero_undef c1) -> c2 7030 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7031 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7032 return SDValue(); 7033 } 7034 7035 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 7036 SDValue N0 = N->getOperand(0); 7037 EVT VT = N->getValueType(0); 7038 7039 // fold (ctpop c1) -> c2 7040 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7041 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 7042 return SDValue(); 7043 } 7044 7045 // FIXME: This should be checking for no signed zeros on individual operands, as 7046 // well as no nans. 7047 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, SDValue RHS) { 7048 const TargetOptions &Options = DAG.getTarget().Options; 7049 EVT VT = LHS.getValueType(); 7050 7051 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && 7052 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); 7053 } 7054 7055 /// Generate Min/Max node 7056 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 7057 SDValue RHS, SDValue True, SDValue False, 7058 ISD::CondCode CC, const TargetLowering &TLI, 7059 SelectionDAG &DAG) { 7060 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 7061 return SDValue(); 7062 7063 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 7064 switch (CC) { 7065 case ISD::SETOLT: 7066 case ISD::SETOLE: 7067 case ISD::SETLT: 7068 case ISD::SETLE: 7069 case ISD::SETULT: 7070 case ISD::SETULE: { 7071 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 7072 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7073 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7074 return SDValue(); 7075 } 7076 case ISD::SETOGT: 7077 case ISD::SETOGE: 7078 case ISD::SETGT: 7079 case ISD::SETGE: 7080 case ISD::SETUGT: 7081 case ISD::SETUGE: { 7082 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 7083 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7084 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7085 return SDValue(); 7086 } 7087 default: 7088 return SDValue(); 7089 } 7090 } 7091 7092 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 7093 SDValue Cond = N->getOperand(0); 7094 SDValue N1 = N->getOperand(1); 7095 SDValue N2 = N->getOperand(2); 7096 EVT VT = N->getValueType(0); 7097 EVT CondVT = Cond.getValueType(); 7098 SDLoc DL(N); 7099 7100 if (!VT.isInteger()) 7101 return SDValue(); 7102 7103 auto *C1 = dyn_cast<ConstantSDNode>(N1); 7104 auto *C2 = dyn_cast<ConstantSDNode>(N2); 7105 if (!C1 || !C2) 7106 return SDValue(); 7107 7108 // Only do this before legalization to avoid conflicting with target-specific 7109 // transforms in the other direction (create a select from a zext/sext). There 7110 // is also a target-independent combine here in DAGCombiner in the other 7111 // direction for (select Cond, -1, 0) when the condition is not i1. 7112 if (CondVT == MVT::i1 && !LegalOperations) { 7113 if (C1->isNullValue() && C2->isOne()) { 7114 // select Cond, 0, 1 --> zext (!Cond) 7115 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7116 if (VT != MVT::i1) 7117 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 7118 return NotCond; 7119 } 7120 if (C1->isNullValue() && C2->isAllOnesValue()) { 7121 // select Cond, 0, -1 --> sext (!Cond) 7122 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7123 if (VT != MVT::i1) 7124 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 7125 return NotCond; 7126 } 7127 if (C1->isOne() && C2->isNullValue()) { 7128 // select Cond, 1, 0 --> zext (Cond) 7129 if (VT != MVT::i1) 7130 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7131 return Cond; 7132 } 7133 if (C1->isAllOnesValue() && C2->isNullValue()) { 7134 // select Cond, -1, 0 --> sext (Cond) 7135 if (VT != MVT::i1) 7136 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7137 return Cond; 7138 } 7139 7140 // For any constants that differ by 1, we can transform the select into an 7141 // extend and add. Use a target hook because some targets may prefer to 7142 // transform in the other direction. 7143 if (TLI.convertSelectOfConstantsToMath(VT)) { 7144 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 7145 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 7146 if (VT != MVT::i1) 7147 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7148 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7149 } 7150 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 7151 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 7152 if (VT != MVT::i1) 7153 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7154 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7155 } 7156 } 7157 7158 return SDValue(); 7159 } 7160 7161 // fold (select Cond, 0, 1) -> (xor Cond, 1) 7162 // We can't do this reliably if integer based booleans have different contents 7163 // to floating point based booleans. This is because we can't tell whether we 7164 // have an integer-based boolean or a floating-point-based boolean unless we 7165 // can find the SETCC that produced it and inspect its operands. This is 7166 // fairly easy if C is the SETCC node, but it can potentially be 7167 // undiscoverable (or not reasonably discoverable). For example, it could be 7168 // in another basic block or it could require searching a complicated 7169 // expression. 7170 if (CondVT.isInteger() && 7171 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 7172 TargetLowering::ZeroOrOneBooleanContent && 7173 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 7174 TargetLowering::ZeroOrOneBooleanContent && 7175 C1->isNullValue() && C2->isOne()) { 7176 SDValue NotCond = 7177 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 7178 if (VT.bitsEq(CondVT)) 7179 return NotCond; 7180 return DAG.getZExtOrTrunc(NotCond, DL, VT); 7181 } 7182 7183 return SDValue(); 7184 } 7185 7186 SDValue DAGCombiner::visitSELECT(SDNode *N) { 7187 SDValue N0 = N->getOperand(0); 7188 SDValue N1 = N->getOperand(1); 7189 SDValue N2 = N->getOperand(2); 7190 EVT VT = N->getValueType(0); 7191 EVT VT0 = N0.getValueType(); 7192 SDLoc DL(N); 7193 7194 // fold (select C, X, X) -> X 7195 if (N1 == N2) 7196 return N1; 7197 7198 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 7199 // fold (select true, X, Y) -> X 7200 // fold (select false, X, Y) -> Y 7201 return !N0C->isNullValue() ? N1 : N2; 7202 } 7203 7204 // fold (select X, X, Y) -> (or X, Y) 7205 // fold (select X, 1, Y) -> (or C, Y) 7206 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 7207 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 7208 7209 if (SDValue V = foldSelectOfConstants(N)) 7210 return V; 7211 7212 // fold (select C, 0, X) -> (and (not C), X) 7213 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 7214 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7215 AddToWorklist(NOTNode.getNode()); 7216 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 7217 } 7218 // fold (select C, X, 1) -> (or (not C), X) 7219 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 7220 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7221 AddToWorklist(NOTNode.getNode()); 7222 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 7223 } 7224 // fold (select X, Y, X) -> (and X, Y) 7225 // fold (select X, Y, 0) -> (and X, Y) 7226 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 7227 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 7228 7229 // If we can fold this based on the true/false value, do so. 7230 if (SimplifySelectOps(N, N1, N2)) 7231 return SDValue(N, 0); // Don't revisit N. 7232 7233 if (VT0 == MVT::i1) { 7234 // The code in this block deals with the following 2 equivalences: 7235 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 7236 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 7237 // The target can specify its preferred form with the 7238 // shouldNormalizeToSelectSequence() callback. However we always transform 7239 // to the right anyway if we find the inner select exists in the DAG anyway 7240 // and we always transform to the left side if we know that we can further 7241 // optimize the combination of the conditions. 7242 bool normalizeToSequence = 7243 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 7244 // select (and Cond0, Cond1), X, Y 7245 // -> select Cond0, (select Cond1, X, Y), Y 7246 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 7247 SDValue Cond0 = N0->getOperand(0); 7248 SDValue Cond1 = N0->getOperand(1); 7249 SDValue InnerSelect = 7250 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7251 if (normalizeToSequence || !InnerSelect.use_empty()) 7252 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 7253 InnerSelect, N2); 7254 } 7255 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 7256 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 7257 SDValue Cond0 = N0->getOperand(0); 7258 SDValue Cond1 = N0->getOperand(1); 7259 SDValue InnerSelect = 7260 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7261 if (normalizeToSequence || !InnerSelect.use_empty()) 7262 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 7263 InnerSelect); 7264 } 7265 7266 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 7267 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 7268 SDValue N1_0 = N1->getOperand(0); 7269 SDValue N1_1 = N1->getOperand(1); 7270 SDValue N1_2 = N1->getOperand(2); 7271 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 7272 // Create the actual and node if we can generate good code for it. 7273 if (!normalizeToSequence) { 7274 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 7275 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 7276 } 7277 // Otherwise see if we can optimize the "and" to a better pattern. 7278 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 7279 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 7280 N2); 7281 } 7282 } 7283 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 7284 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 7285 SDValue N2_0 = N2->getOperand(0); 7286 SDValue N2_1 = N2->getOperand(1); 7287 SDValue N2_2 = N2->getOperand(2); 7288 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 7289 // Create the actual or node if we can generate good code for it. 7290 if (!normalizeToSequence) { 7291 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 7292 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 7293 } 7294 // Otherwise see if we can optimize to a better pattern. 7295 if (SDValue Combined = visitORLike(N0, N2_0, N)) 7296 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 7297 N2_2); 7298 } 7299 } 7300 } 7301 7302 if (VT0 == MVT::i1) { 7303 // select (not Cond), N1, N2 -> select Cond, N2, N1 7304 if (isBitwiseNot(N0)) 7305 return DAG.getNode(ISD::SELECT, DL, VT, N0->getOperand(0), N2, N1); 7306 } 7307 7308 // fold selects based on a setcc into other things, such as min/max/abs 7309 if (N0.getOpcode() == ISD::SETCC) { 7310 // select x, y (fcmp lt x, y) -> fminnum x, y 7311 // select x, y (fcmp gt x, y) -> fmaxnum x, y 7312 // 7313 // This is OK if we don't care about what happens if either operand is a 7314 // NaN. 7315 // 7316 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2)) { 7317 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7318 7319 if (SDValue FMinMax = combineMinNumMaxNum( 7320 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 7321 return FMinMax; 7322 } 7323 7324 if ((!LegalOperations && 7325 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 7326 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 7327 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 7328 N0.getOperand(1), N1, N2, N0.getOperand(2)); 7329 return SimplifySelect(DL, N0, N1, N2); 7330 } 7331 7332 return SDValue(); 7333 } 7334 7335 static 7336 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 7337 SDLoc DL(N); 7338 EVT LoVT, HiVT; 7339 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 7340 7341 // Split the inputs. 7342 SDValue Lo, Hi, LL, LH, RL, RH; 7343 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 7344 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 7345 7346 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 7347 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 7348 7349 return std::make_pair(Lo, Hi); 7350 } 7351 7352 // This function assumes all the vselect's arguments are CONCAT_VECTOR 7353 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 7354 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 7355 SDLoc DL(N); 7356 SDValue Cond = N->getOperand(0); 7357 SDValue LHS = N->getOperand(1); 7358 SDValue RHS = N->getOperand(2); 7359 EVT VT = N->getValueType(0); 7360 int NumElems = VT.getVectorNumElements(); 7361 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 7362 RHS.getOpcode() == ISD::CONCAT_VECTORS && 7363 Cond.getOpcode() == ISD::BUILD_VECTOR); 7364 7365 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 7366 // binary ones here. 7367 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 7368 return SDValue(); 7369 7370 // We're sure we have an even number of elements due to the 7371 // concat_vectors we have as arguments to vselect. 7372 // Skip BV elements until we find one that's not an UNDEF 7373 // After we find an UNDEF element, keep looping until we get to half the 7374 // length of the BV and see if all the non-undef nodes are the same. 7375 ConstantSDNode *BottomHalf = nullptr; 7376 for (int i = 0; i < NumElems / 2; ++i) { 7377 if (Cond->getOperand(i)->isUndef()) 7378 continue; 7379 7380 if (BottomHalf == nullptr) 7381 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7382 else if (Cond->getOperand(i).getNode() != BottomHalf) 7383 return SDValue(); 7384 } 7385 7386 // Do the same for the second half of the BuildVector 7387 ConstantSDNode *TopHalf = nullptr; 7388 for (int i = NumElems / 2; i < NumElems; ++i) { 7389 if (Cond->getOperand(i)->isUndef()) 7390 continue; 7391 7392 if (TopHalf == nullptr) 7393 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7394 else if (Cond->getOperand(i).getNode() != TopHalf) 7395 return SDValue(); 7396 } 7397 7398 assert(TopHalf && BottomHalf && 7399 "One half of the selector was all UNDEFs and the other was all the " 7400 "same value. This should have been addressed before this function."); 7401 return DAG.getNode( 7402 ISD::CONCAT_VECTORS, DL, VT, 7403 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 7404 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 7405 } 7406 7407 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 7408 if (Level >= AfterLegalizeTypes) 7409 return SDValue(); 7410 7411 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 7412 SDValue Mask = MSC->getMask(); 7413 SDValue Data = MSC->getValue(); 7414 SDLoc DL(N); 7415 7416 // If the MSCATTER data type requires splitting and the mask is provided by a 7417 // SETCC, then split both nodes and its operands before legalization. This 7418 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7419 // and enables future optimizations (e.g. min/max pattern matching on X86). 7420 if (Mask.getOpcode() != ISD::SETCC) 7421 return SDValue(); 7422 7423 // Check if any splitting is required. 7424 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 7425 TargetLowering::TypeSplitVector) 7426 return SDValue(); 7427 SDValue MaskLo, MaskHi; 7428 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7429 7430 EVT LoVT, HiVT; 7431 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 7432 7433 SDValue Chain = MSC->getChain(); 7434 7435 EVT MemoryVT = MSC->getMemoryVT(); 7436 unsigned Alignment = MSC->getOriginalAlignment(); 7437 7438 EVT LoMemVT, HiMemVT; 7439 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7440 7441 SDValue DataLo, DataHi; 7442 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7443 7444 SDValue Scale = MSC->getScale(); 7445 SDValue BasePtr = MSC->getBasePtr(); 7446 SDValue IndexLo, IndexHi; 7447 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 7448 7449 MachineMemOperand *MMO = DAG.getMachineFunction(). 7450 getMachineMemOperand(MSC->getPointerInfo(), 7451 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7452 Alignment, MSC->getAAInfo(), MSC->getRanges()); 7453 7454 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale }; 7455 SDValue Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), 7456 DataLo.getValueType(), DL, OpsLo, MMO); 7457 7458 // The order of the Scatter operation after split is well defined. The "Hi" 7459 // part comes after the "Lo". So these two operations should be chained one 7460 // after another. 7461 SDValue OpsHi[] = { Lo, DataHi, MaskHi, BasePtr, IndexHi, Scale }; 7462 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 7463 DL, OpsHi, MMO); 7464 } 7465 7466 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 7467 if (Level >= AfterLegalizeTypes) 7468 return SDValue(); 7469 7470 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 7471 SDValue Mask = MST->getMask(); 7472 SDValue Data = MST->getValue(); 7473 EVT VT = Data.getValueType(); 7474 SDLoc DL(N); 7475 7476 // If the MSTORE data type requires splitting and the mask is provided by a 7477 // SETCC, then split both nodes and its operands before legalization. This 7478 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7479 // and enables future optimizations (e.g. min/max pattern matching on X86). 7480 if (Mask.getOpcode() == ISD::SETCC) { 7481 // Check if any splitting is required. 7482 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7483 TargetLowering::TypeSplitVector) 7484 return SDValue(); 7485 7486 SDValue MaskLo, MaskHi, Lo, Hi; 7487 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7488 7489 SDValue Chain = MST->getChain(); 7490 SDValue Ptr = MST->getBasePtr(); 7491 7492 EVT MemoryVT = MST->getMemoryVT(); 7493 unsigned Alignment = MST->getOriginalAlignment(); 7494 7495 // if Alignment is equal to the vector size, 7496 // take the half of it for the second part 7497 unsigned SecondHalfAlignment = 7498 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 7499 7500 EVT LoMemVT, HiMemVT; 7501 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7502 7503 SDValue DataLo, DataHi; 7504 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7505 7506 MachineMemOperand *MMO = DAG.getMachineFunction(). 7507 getMachineMemOperand(MST->getPointerInfo(), 7508 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7509 Alignment, MST->getAAInfo(), MST->getRanges()); 7510 7511 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 7512 MST->isTruncatingStore(), 7513 MST->isCompressingStore()); 7514 7515 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7516 MST->isCompressingStore()); 7517 unsigned HiOffset = LoMemVT.getStoreSize(); 7518 7519 MMO = DAG.getMachineFunction().getMachineMemOperand( 7520 MST->getPointerInfo().getWithOffset(HiOffset), 7521 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment, 7522 MST->getAAInfo(), MST->getRanges()); 7523 7524 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 7525 MST->isTruncatingStore(), 7526 MST->isCompressingStore()); 7527 7528 AddToWorklist(Lo.getNode()); 7529 AddToWorklist(Hi.getNode()); 7530 7531 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 7532 } 7533 return SDValue(); 7534 } 7535 7536 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 7537 if (Level >= AfterLegalizeTypes) 7538 return SDValue(); 7539 7540 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 7541 SDValue Mask = MGT->getMask(); 7542 SDLoc DL(N); 7543 7544 // If the MGATHER result requires splitting and the mask is provided by a 7545 // SETCC, then split both nodes and its operands before legalization. This 7546 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7547 // and enables future optimizations (e.g. min/max pattern matching on X86). 7548 7549 if (Mask.getOpcode() != ISD::SETCC) 7550 return SDValue(); 7551 7552 EVT VT = N->getValueType(0); 7553 7554 // Check if any splitting is required. 7555 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7556 TargetLowering::TypeSplitVector) 7557 return SDValue(); 7558 7559 SDValue MaskLo, MaskHi, Lo, Hi; 7560 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7561 7562 SDValue PassThru = MGT->getPassThru(); 7563 SDValue PassThruLo, PassThruHi; 7564 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 7565 7566 EVT LoVT, HiVT; 7567 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 7568 7569 SDValue Chain = MGT->getChain(); 7570 EVT MemoryVT = MGT->getMemoryVT(); 7571 unsigned Alignment = MGT->getOriginalAlignment(); 7572 7573 EVT LoMemVT, HiMemVT; 7574 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7575 7576 SDValue Scale = MGT->getScale(); 7577 SDValue BasePtr = MGT->getBasePtr(); 7578 SDValue Index = MGT->getIndex(); 7579 SDValue IndexLo, IndexHi; 7580 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 7581 7582 MachineMemOperand *MMO = DAG.getMachineFunction(). 7583 getMachineMemOperand(MGT->getPointerInfo(), 7584 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7585 Alignment, MGT->getAAInfo(), MGT->getRanges()); 7586 7587 SDValue OpsLo[] = { Chain, PassThruLo, MaskLo, BasePtr, IndexLo, Scale }; 7588 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 7589 MMO); 7590 7591 SDValue OpsHi[] = { Chain, PassThruHi, MaskHi, BasePtr, IndexHi, Scale }; 7592 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 7593 MMO); 7594 7595 AddToWorklist(Lo.getNode()); 7596 AddToWorklist(Hi.getNode()); 7597 7598 // Build a factor node to remember that this load is independent of the 7599 // other one. 7600 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7601 Hi.getValue(1)); 7602 7603 // Legalized the chain result - switch anything that used the old chain to 7604 // use the new one. 7605 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 7606 7607 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7608 7609 SDValue RetOps[] = { GatherRes, Chain }; 7610 return DAG.getMergeValues(RetOps, DL); 7611 } 7612 7613 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 7614 if (Level >= AfterLegalizeTypes) 7615 return SDValue(); 7616 7617 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 7618 SDValue Mask = MLD->getMask(); 7619 SDLoc DL(N); 7620 7621 // If the MLOAD result requires splitting and the mask is provided by a 7622 // SETCC, then split both nodes and its operands before legalization. This 7623 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7624 // and enables future optimizations (e.g. min/max pattern matching on X86). 7625 if (Mask.getOpcode() == ISD::SETCC) { 7626 EVT VT = N->getValueType(0); 7627 7628 // Check if any splitting is required. 7629 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7630 TargetLowering::TypeSplitVector) 7631 return SDValue(); 7632 7633 SDValue MaskLo, MaskHi, Lo, Hi; 7634 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7635 7636 SDValue PassThru = MLD->getPassThru(); 7637 SDValue PassThruLo, PassThruHi; 7638 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 7639 7640 EVT LoVT, HiVT; 7641 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 7642 7643 SDValue Chain = MLD->getChain(); 7644 SDValue Ptr = MLD->getBasePtr(); 7645 EVT MemoryVT = MLD->getMemoryVT(); 7646 unsigned Alignment = MLD->getOriginalAlignment(); 7647 7648 // if Alignment is equal to the vector size, 7649 // take the half of it for the second part 7650 unsigned SecondHalfAlignment = 7651 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 7652 Alignment/2 : Alignment; 7653 7654 EVT LoMemVT, HiMemVT; 7655 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7656 7657 MachineMemOperand *MMO = DAG.getMachineFunction(). 7658 getMachineMemOperand(MLD->getPointerInfo(), 7659 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7660 Alignment, MLD->getAAInfo(), MLD->getRanges()); 7661 7662 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, PassThruLo, LoMemVT, 7663 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7664 7665 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7666 MLD->isExpandingLoad()); 7667 unsigned HiOffset = LoMemVT.getStoreSize(); 7668 7669 MMO = DAG.getMachineFunction().getMachineMemOperand( 7670 MLD->getPointerInfo().getWithOffset(HiOffset), 7671 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment, 7672 MLD->getAAInfo(), MLD->getRanges()); 7673 7674 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, PassThruHi, HiMemVT, 7675 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7676 7677 AddToWorklist(Lo.getNode()); 7678 AddToWorklist(Hi.getNode()); 7679 7680 // Build a factor node to remember that this load is independent of the 7681 // other one. 7682 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7683 Hi.getValue(1)); 7684 7685 // Legalized the chain result - switch anything that used the old chain to 7686 // use the new one. 7687 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 7688 7689 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7690 7691 SDValue RetOps[] = { LoadRes, Chain }; 7692 return DAG.getMergeValues(RetOps, DL); 7693 } 7694 return SDValue(); 7695 } 7696 7697 /// A vector select of 2 constant vectors can be simplified to math/logic to 7698 /// avoid a variable select instruction and possibly avoid constant loads. 7699 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 7700 SDValue Cond = N->getOperand(0); 7701 SDValue N1 = N->getOperand(1); 7702 SDValue N2 = N->getOperand(2); 7703 EVT VT = N->getValueType(0); 7704 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 7705 !TLI.convertSelectOfConstantsToMath(VT) || 7706 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 7707 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 7708 return SDValue(); 7709 7710 // Check if we can use the condition value to increment/decrement a single 7711 // constant value. This simplifies a select to an add and removes a constant 7712 // load/materialization from the general case. 7713 bool AllAddOne = true; 7714 bool AllSubOne = true; 7715 unsigned Elts = VT.getVectorNumElements(); 7716 for (unsigned i = 0; i != Elts; ++i) { 7717 SDValue N1Elt = N1.getOperand(i); 7718 SDValue N2Elt = N2.getOperand(i); 7719 if (N1Elt.isUndef() || N2Elt.isUndef()) 7720 continue; 7721 7722 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 7723 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 7724 if (C1 != C2 + 1) 7725 AllAddOne = false; 7726 if (C1 != C2 - 1) 7727 AllSubOne = false; 7728 } 7729 7730 // Further simplifications for the extra-special cases where the constants are 7731 // all 0 or all -1 should be implemented as folds of these patterns. 7732 SDLoc DL(N); 7733 if (AllAddOne || AllSubOne) { 7734 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7735 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7736 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7737 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7738 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7739 } 7740 7741 // The general case for select-of-constants: 7742 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7743 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7744 // leave that to a machine-specific pass. 7745 return SDValue(); 7746 } 7747 7748 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7749 SDValue N0 = N->getOperand(0); 7750 SDValue N1 = N->getOperand(1); 7751 SDValue N2 = N->getOperand(2); 7752 SDLoc DL(N); 7753 7754 // fold (vselect C, X, X) -> X 7755 if (N1 == N2) 7756 return N1; 7757 7758 // Canonicalize integer abs. 7759 // vselect (setg[te] X, 0), X, -X -> 7760 // vselect (setgt X, -1), X, -X -> 7761 // vselect (setl[te] X, 0), -X, X -> 7762 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7763 if (N0.getOpcode() == ISD::SETCC) { 7764 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7765 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7766 bool isAbs = false; 7767 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7768 7769 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7770 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7771 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7772 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7773 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7774 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7775 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7776 7777 if (isAbs) { 7778 EVT VT = LHS.getValueType(); 7779 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7780 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7781 7782 SDValue Shift = DAG.getNode( 7783 ISD::SRA, DL, VT, LHS, 7784 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7785 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7786 AddToWorklist(Shift.getNode()); 7787 AddToWorklist(Add.getNode()); 7788 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7789 } 7790 7791 // vselect x, y (fcmp lt x, y) -> fminnum x, y 7792 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y 7793 // 7794 // This is OK if we don't care about what happens if either operand is a 7795 // NaN. 7796 // 7797 EVT VT = N->getValueType(0); 7798 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N0.getOperand(0), N0.getOperand(1))) { 7799 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7800 if (SDValue FMinMax = combineMinNumMaxNum( 7801 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 7802 return FMinMax; 7803 } 7804 7805 // If this select has a condition (setcc) with narrower operands than the 7806 // select, try to widen the compare to match the select width. 7807 // TODO: This should be extended to handle any constant. 7808 // TODO: This could be extended to handle non-loading patterns, but that 7809 // requires thorough testing to avoid regressions. 7810 if (isNullConstantOrNullSplatConstant(RHS)) { 7811 EVT NarrowVT = LHS.getValueType(); 7812 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 7813 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 7814 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 7815 unsigned WideWidth = WideVT.getScalarSizeInBits(); 7816 bool IsSigned = isSignedIntSetCC(CC); 7817 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7818 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 7819 SetCCWidth != 1 && SetCCWidth < WideWidth && 7820 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 7821 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 7822 // Both compare operands can be widened for free. The LHS can use an 7823 // extended load, and the RHS is a constant: 7824 // vselect (ext (setcc load(X), C)), N1, N2 --> 7825 // vselect (setcc extload(X), C'), N1, N2 7826 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7827 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 7828 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 7829 EVT WideSetCCVT = getSetCCResultType(WideVT); 7830 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 7831 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 7832 } 7833 } 7834 } 7835 7836 if (SimplifySelectOps(N, N1, N2)) 7837 return SDValue(N, 0); // Don't revisit N. 7838 7839 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7840 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7841 return N1; 7842 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7843 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7844 return N2; 7845 7846 // The ConvertSelectToConcatVector function is assuming both the above 7847 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7848 // and addressed. 7849 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7850 N2.getOpcode() == ISD::CONCAT_VECTORS && 7851 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7852 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7853 return CV; 7854 } 7855 7856 if (SDValue V = foldVSelectOfConstants(N)) 7857 return V; 7858 7859 return SDValue(); 7860 } 7861 7862 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7863 SDValue N0 = N->getOperand(0); 7864 SDValue N1 = N->getOperand(1); 7865 SDValue N2 = N->getOperand(2); 7866 SDValue N3 = N->getOperand(3); 7867 SDValue N4 = N->getOperand(4); 7868 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7869 7870 // fold select_cc lhs, rhs, x, x, cc -> x 7871 if (N2 == N3) 7872 return N2; 7873 7874 // Determine if the condition we're dealing with is constant 7875 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7876 CC, SDLoc(N), false)) { 7877 AddToWorklist(SCC.getNode()); 7878 7879 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7880 if (!SCCC->isNullValue()) 7881 return N2; // cond always true -> true val 7882 else 7883 return N3; // cond always false -> false val 7884 } else if (SCC->isUndef()) { 7885 // When the condition is UNDEF, just return the first operand. This is 7886 // coherent the DAG creation, no setcc node is created in this case 7887 return N2; 7888 } else if (SCC.getOpcode() == ISD::SETCC) { 7889 // Fold to a simpler select_cc 7890 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7891 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7892 SCC.getOperand(2)); 7893 } 7894 } 7895 7896 // If we can fold this based on the true/false value, do so. 7897 if (SimplifySelectOps(N, N2, N3)) 7898 return SDValue(N, 0); // Don't revisit N. 7899 7900 // fold select_cc into other things, such as min/max/abs 7901 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7902 } 7903 7904 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7905 // setcc is very commonly used as an argument to brcond. This pattern 7906 // also lend itself to numerous combines and, as a result, it is desired 7907 // we keep the argument to a brcond as a setcc as much as possible. 7908 bool PreferSetCC = 7909 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 7910 7911 SDValue Combined = SimplifySetCC( 7912 N->getValueType(0), N->getOperand(0), N->getOperand(1), 7913 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 7914 7915 if (!Combined) 7916 return SDValue(); 7917 7918 // If we prefer to have a setcc, and we don't, we'll try our best to 7919 // recreate one using rebuildSetCC. 7920 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 7921 SDValue NewSetCC = rebuildSetCC(Combined); 7922 7923 // We don't have anything interesting to combine to. 7924 if (NewSetCC.getNode() == N) 7925 return SDValue(); 7926 7927 if (NewSetCC) 7928 return NewSetCC; 7929 } 7930 7931 return Combined; 7932 } 7933 7934 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 7935 SDValue LHS = N->getOperand(0); 7936 SDValue RHS = N->getOperand(1); 7937 SDValue Carry = N->getOperand(2); 7938 SDValue Cond = N->getOperand(3); 7939 7940 // If Carry is false, fold to a regular SETCC. 7941 if (isNullConstant(Carry)) 7942 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7943 7944 return SDValue(); 7945 } 7946 7947 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 7948 /// a build_vector of constants. 7949 /// This function is called by the DAGCombiner when visiting sext/zext/aext 7950 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 7951 /// Vector extends are not folded if operations are legal; this is to 7952 /// avoid introducing illegal build_vector dag nodes. 7953 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 7954 SelectionDAG &DAG, bool LegalTypes, 7955 bool LegalOperations) { 7956 unsigned Opcode = N->getOpcode(); 7957 SDValue N0 = N->getOperand(0); 7958 EVT VT = N->getValueType(0); 7959 7960 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 7961 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 7962 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 7963 && "Expected EXTEND dag node in input!"); 7964 7965 // fold (sext c1) -> c1 7966 // fold (zext c1) -> c1 7967 // fold (aext c1) -> c1 7968 if (isa<ConstantSDNode>(N0)) 7969 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 7970 7971 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 7972 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 7973 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 7974 EVT SVT = VT.getScalarType(); 7975 if (!(VT.isVector() && 7976 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 7977 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 7978 return nullptr; 7979 7980 // We can fold this node into a build_vector. 7981 unsigned VTBits = SVT.getSizeInBits(); 7982 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 7983 SmallVector<SDValue, 8> Elts; 7984 unsigned NumElts = VT.getVectorNumElements(); 7985 SDLoc DL(N); 7986 7987 for (unsigned i=0; i != NumElts; ++i) { 7988 SDValue Op = N0->getOperand(i); 7989 if (Op->isUndef()) { 7990 Elts.push_back(DAG.getUNDEF(SVT)); 7991 continue; 7992 } 7993 7994 SDLoc DL(Op); 7995 // Get the constant value and if needed trunc it to the size of the type. 7996 // Nodes like build_vector might have constants wider than the scalar type. 7997 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 7998 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 7999 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 8000 else 8001 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 8002 } 8003 8004 return DAG.getBuildVector(VT, DL, Elts).getNode(); 8005 } 8006 8007 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 8008 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 8009 // transformation. Returns true if extension are possible and the above 8010 // mentioned transformation is profitable. 8011 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 8012 unsigned ExtOpc, 8013 SmallVectorImpl<SDNode *> &ExtendNodes, 8014 const TargetLowering &TLI) { 8015 bool HasCopyToRegUses = false; 8016 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 8017 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 8018 UE = N0.getNode()->use_end(); 8019 UI != UE; ++UI) { 8020 SDNode *User = *UI; 8021 if (User == N) 8022 continue; 8023 if (UI.getUse().getResNo() != N0.getResNo()) 8024 continue; 8025 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 8026 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 8027 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 8028 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 8029 // Sign bits will be lost after a zext. 8030 return false; 8031 bool Add = false; 8032 for (unsigned i = 0; i != 2; ++i) { 8033 SDValue UseOp = User->getOperand(i); 8034 if (UseOp == N0) 8035 continue; 8036 if (!isa<ConstantSDNode>(UseOp)) 8037 return false; 8038 Add = true; 8039 } 8040 if (Add) 8041 ExtendNodes.push_back(User); 8042 continue; 8043 } 8044 // If truncates aren't free and there are users we can't 8045 // extend, it isn't worthwhile. 8046 if (!isTruncFree) 8047 return false; 8048 // Remember if this value is live-out. 8049 if (User->getOpcode() == ISD::CopyToReg) 8050 HasCopyToRegUses = true; 8051 } 8052 8053 if (HasCopyToRegUses) { 8054 bool BothLiveOut = false; 8055 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8056 UI != UE; ++UI) { 8057 SDUse &Use = UI.getUse(); 8058 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 8059 BothLiveOut = true; 8060 break; 8061 } 8062 } 8063 if (BothLiveOut) 8064 // Both unextended and extended values are live out. There had better be 8065 // a good reason for the transformation. 8066 return ExtendNodes.size(); 8067 } 8068 return true; 8069 } 8070 8071 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 8072 SDValue OrigLoad, SDValue ExtLoad, 8073 ISD::NodeType ExtType) { 8074 // Extend SetCC uses if necessary. 8075 SDLoc DL(ExtLoad); 8076 for (SDNode *SetCC : SetCCs) { 8077 SmallVector<SDValue, 4> Ops; 8078 8079 for (unsigned j = 0; j != 2; ++j) { 8080 SDValue SOp = SetCC->getOperand(j); 8081 if (SOp == OrigLoad) 8082 Ops.push_back(ExtLoad); 8083 else 8084 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 8085 } 8086 8087 Ops.push_back(SetCC->getOperand(2)); 8088 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 8089 } 8090 } 8091 8092 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 8093 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 8094 SDValue N0 = N->getOperand(0); 8095 EVT DstVT = N->getValueType(0); 8096 EVT SrcVT = N0.getValueType(); 8097 8098 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8099 N->getOpcode() == ISD::ZERO_EXTEND) && 8100 "Unexpected node type (not an extend)!"); 8101 8102 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 8103 // For example, on a target with legal v4i32, but illegal v8i32, turn: 8104 // (v8i32 (sext (v8i16 (load x)))) 8105 // into: 8106 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8107 // (v4i32 (sextload (x + 16))))) 8108 // Where uses of the original load, i.e.: 8109 // (v8i16 (load x)) 8110 // are replaced with: 8111 // (v8i16 (truncate 8112 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8113 // (v4i32 (sextload (x + 16))))))) 8114 // 8115 // This combine is only applicable to illegal, but splittable, vectors. 8116 // All legal types, and illegal non-vector types, are handled elsewhere. 8117 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 8118 // 8119 if (N0->getOpcode() != ISD::LOAD) 8120 return SDValue(); 8121 8122 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8123 8124 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 8125 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 8126 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 8127 return SDValue(); 8128 8129 SmallVector<SDNode *, 4> SetCCs; 8130 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 8131 return SDValue(); 8132 8133 ISD::LoadExtType ExtType = 8134 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 8135 8136 // Try to split the vector types to get down to legal types. 8137 EVT SplitSrcVT = SrcVT; 8138 EVT SplitDstVT = DstVT; 8139 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 8140 SplitSrcVT.getVectorNumElements() > 1) { 8141 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 8142 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 8143 } 8144 8145 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 8146 return SDValue(); 8147 8148 SDLoc DL(N); 8149 const unsigned NumSplits = 8150 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 8151 const unsigned Stride = SplitSrcVT.getStoreSize(); 8152 SmallVector<SDValue, 4> Loads; 8153 SmallVector<SDValue, 4> Chains; 8154 8155 SDValue BasePtr = LN0->getBasePtr(); 8156 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 8157 const unsigned Offset = Idx * Stride; 8158 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 8159 8160 SDValue SplitLoad = DAG.getExtLoad( 8161 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 8162 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 8163 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8164 8165 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 8166 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 8167 8168 Loads.push_back(SplitLoad.getValue(0)); 8169 Chains.push_back(SplitLoad.getValue(1)); 8170 } 8171 8172 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 8173 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 8174 8175 // Simplify TF. 8176 AddToWorklist(NewChain.getNode()); 8177 8178 CombineTo(N, NewValue); 8179 8180 // Replace uses of the original load (before extension) 8181 // with a truncate of the concatenated sextloaded vectors. 8182 SDValue Trunc = 8183 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 8184 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 8185 CombineTo(N0.getNode(), Trunc, NewChain); 8186 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8187 } 8188 8189 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8190 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8191 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 8192 assert(N->getOpcode() == ISD::ZERO_EXTEND); 8193 EVT VT = N->getValueType(0); 8194 8195 // and/or/xor 8196 SDValue N0 = N->getOperand(0); 8197 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8198 N0.getOpcode() == ISD::XOR) || 8199 N0.getOperand(1).getOpcode() != ISD::Constant || 8200 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 8201 return SDValue(); 8202 8203 // shl/shr 8204 SDValue N1 = N0->getOperand(0); 8205 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 8206 N1.getOperand(1).getOpcode() != ISD::Constant || 8207 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 8208 return SDValue(); 8209 8210 // load 8211 if (!isa<LoadSDNode>(N1.getOperand(0))) 8212 return SDValue(); 8213 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 8214 EVT MemVT = Load->getMemoryVT(); 8215 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 8216 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 8217 return SDValue(); 8218 8219 8220 // If the shift op is SHL, the logic op must be AND, otherwise the result 8221 // will be wrong. 8222 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 8223 return SDValue(); 8224 8225 if (!N0.hasOneUse() || !N1.hasOneUse()) 8226 return SDValue(); 8227 8228 SmallVector<SDNode*, 4> SetCCs; 8229 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 8230 ISD::ZERO_EXTEND, SetCCs, TLI)) 8231 return SDValue(); 8232 8233 // Actually do the transformation. 8234 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 8235 Load->getChain(), Load->getBasePtr(), 8236 Load->getMemoryVT(), Load->getMemOperand()); 8237 8238 SDLoc DL1(N1); 8239 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 8240 N1.getOperand(1)); 8241 8242 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8243 Mask = Mask.zext(VT.getSizeInBits()); 8244 SDLoc DL0(N0); 8245 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 8246 DAG.getConstant(Mask, DL0, VT)); 8247 8248 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8249 CombineTo(N, And); 8250 if (SDValue(Load, 0).hasOneUse()) { 8251 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 8252 } else { 8253 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 8254 Load->getValueType(0), ExtLoad); 8255 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 8256 } 8257 return SDValue(N,0); // Return N so it doesn't get rechecked! 8258 } 8259 8260 /// If we're narrowing or widening the result of a vector select and the final 8261 /// size is the same size as a setcc (compare) feeding the select, then try to 8262 /// apply the cast operation to the select's operands because matching vector 8263 /// sizes for a select condition and other operands should be more efficient. 8264 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 8265 unsigned CastOpcode = Cast->getOpcode(); 8266 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 8267 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 8268 CastOpcode == ISD::FP_ROUND) && 8269 "Unexpected opcode for vector select narrowing/widening"); 8270 8271 // We only do this transform before legal ops because the pattern may be 8272 // obfuscated by target-specific operations after legalization. Do not create 8273 // an illegal select op, however, because that may be difficult to lower. 8274 EVT VT = Cast->getValueType(0); 8275 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 8276 return SDValue(); 8277 8278 SDValue VSel = Cast->getOperand(0); 8279 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 8280 VSel.getOperand(0).getOpcode() != ISD::SETCC) 8281 return SDValue(); 8282 8283 // Does the setcc have the same vector size as the casted select? 8284 SDValue SetCC = VSel.getOperand(0); 8285 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 8286 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 8287 return SDValue(); 8288 8289 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 8290 SDValue A = VSel.getOperand(1); 8291 SDValue B = VSel.getOperand(2); 8292 SDValue CastA, CastB; 8293 SDLoc DL(Cast); 8294 if (CastOpcode == ISD::FP_ROUND) { 8295 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 8296 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 8297 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 8298 } else { 8299 CastA = DAG.getNode(CastOpcode, DL, VT, A); 8300 CastB = DAG.getNode(CastOpcode, DL, VT, B); 8301 } 8302 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 8303 } 8304 8305 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8306 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8307 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 8308 const TargetLowering &TLI, EVT VT, 8309 bool LegalOperations, SDNode *N, 8310 SDValue N0, ISD::LoadExtType ExtLoadType) { 8311 SDNode *N0Node = N0.getNode(); 8312 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 8313 : ISD::isZEXTLoad(N0Node); 8314 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 8315 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 8316 return {}; 8317 8318 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8319 EVT MemVT = LN0->getMemoryVT(); 8320 if ((LegalOperations || LN0->isVolatile()) && 8321 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 8322 return {}; 8323 8324 SDValue ExtLoad = 8325 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8326 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 8327 Combiner.CombineTo(N, ExtLoad); 8328 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8329 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8330 } 8331 8332 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8333 // Only generate vector extloads when 1) they're legal, and 2) they are 8334 // deemed desirable by the target. 8335 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 8336 const TargetLowering &TLI, EVT VT, 8337 bool LegalOperations, SDNode *N, SDValue N0, 8338 ISD::LoadExtType ExtLoadType, 8339 ISD::NodeType ExtOpc) { 8340 if (!ISD::isNON_EXTLoad(N0.getNode()) || 8341 !ISD::isUNINDEXEDLoad(N0.getNode()) || 8342 ((LegalOperations || VT.isVector() || 8343 cast<LoadSDNode>(N0)->isVolatile()) && 8344 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 8345 return {}; 8346 8347 bool DoXform = true; 8348 SmallVector<SDNode *, 4> SetCCs; 8349 if (!N0.hasOneUse()) 8350 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 8351 if (VT.isVector()) 8352 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 8353 if (!DoXform) 8354 return {}; 8355 8356 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8357 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8358 LN0->getBasePtr(), N0.getValueType(), 8359 LN0->getMemOperand()); 8360 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 8361 // If the load value is used only by N, replace it via CombineTo N. 8362 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 8363 Combiner.CombineTo(N, ExtLoad); 8364 if (NoReplaceTrunc) { 8365 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8366 } else { 8367 SDValue Trunc = 8368 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 8369 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8370 } 8371 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8372 } 8373 8374 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 8375 bool LegalOperations) { 8376 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8377 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 8378 8379 SDValue SetCC = N->getOperand(0); 8380 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 8381 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 8382 return SDValue(); 8383 8384 SDValue X = SetCC.getOperand(0); 8385 SDValue Ones = SetCC.getOperand(1); 8386 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 8387 EVT VT = N->getValueType(0); 8388 EVT XVT = X.getValueType(); 8389 // setge X, C is canonicalized to setgt, so we do not need to match that 8390 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 8391 // not require the 'not' op. 8392 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 8393 // Invert and smear/shift the sign bit: 8394 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 8395 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 8396 SDLoc DL(N); 8397 SDValue NotX = DAG.getNOT(DL, X, VT); 8398 SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT); 8399 auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 8400 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 8401 } 8402 return SDValue(); 8403 } 8404 8405 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 8406 SDValue N0 = N->getOperand(0); 8407 EVT VT = N->getValueType(0); 8408 SDLoc DL(N); 8409 8410 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8411 LegalOperations)) 8412 return SDValue(Res, 0); 8413 8414 // fold (sext (sext x)) -> (sext x) 8415 // fold (sext (aext x)) -> (sext x) 8416 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8417 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 8418 8419 if (N0.getOpcode() == ISD::TRUNCATE) { 8420 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 8421 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 8422 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8423 SDNode *oye = N0.getOperand(0).getNode(); 8424 if (NarrowLoad.getNode() != N0.getNode()) { 8425 CombineTo(N0.getNode(), NarrowLoad); 8426 // CombineTo deleted the truncate, if needed, but not what's under it. 8427 AddToWorklist(oye); 8428 } 8429 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8430 } 8431 8432 // See if the value being truncated is already sign extended. If so, just 8433 // eliminate the trunc/sext pair. 8434 SDValue Op = N0.getOperand(0); 8435 unsigned OpBits = Op.getScalarValueSizeInBits(); 8436 unsigned MidBits = N0.getScalarValueSizeInBits(); 8437 unsigned DestBits = VT.getScalarSizeInBits(); 8438 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 8439 8440 if (OpBits == DestBits) { 8441 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 8442 // bits, it is already ready. 8443 if (NumSignBits > DestBits-MidBits) 8444 return Op; 8445 } else if (OpBits < DestBits) { 8446 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 8447 // bits, just sext from i32. 8448 if (NumSignBits > OpBits-MidBits) 8449 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 8450 } else { 8451 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 8452 // bits, just truncate to i32. 8453 if (NumSignBits > OpBits-MidBits) 8454 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 8455 } 8456 8457 // fold (sext (truncate x)) -> (sextinreg x). 8458 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 8459 N0.getValueType())) { 8460 if (OpBits < DestBits) 8461 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 8462 else if (OpBits > DestBits) 8463 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 8464 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 8465 DAG.getValueType(N0.getValueType())); 8466 } 8467 } 8468 8469 // Try to simplify (sext (load x)). 8470 if (SDValue foldedExt = 8471 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8472 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 8473 return foldedExt; 8474 8475 // fold (sext (load x)) to multiple smaller sextloads. 8476 // Only on illegal but splittable vectors. 8477 if (SDValue ExtLoad = CombineExtLoad(N)) 8478 return ExtLoad; 8479 8480 // Try to simplify (sext (sextload x)). 8481 if (SDValue foldedExt = tryToFoldExtOfExtload( 8482 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 8483 return foldedExt; 8484 8485 // fold (sext (and/or/xor (load x), cst)) -> 8486 // (and/or/xor (sextload x), (sext cst)) 8487 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8488 N0.getOpcode() == ISD::XOR) && 8489 isa<LoadSDNode>(N0.getOperand(0)) && 8490 N0.getOperand(1).getOpcode() == ISD::Constant && 8491 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8492 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8493 EVT MemVT = LN00->getMemoryVT(); 8494 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 8495 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 8496 SmallVector<SDNode*, 4> SetCCs; 8497 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8498 ISD::SIGN_EXTEND, SetCCs, TLI); 8499 if (DoXform) { 8500 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 8501 LN00->getChain(), LN00->getBasePtr(), 8502 LN00->getMemoryVT(), 8503 LN00->getMemOperand()); 8504 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8505 Mask = Mask.sext(VT.getSizeInBits()); 8506 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8507 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8508 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 8509 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8510 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8511 CombineTo(N, And); 8512 // If N0 has multiple uses, change other uses as well. 8513 if (NoReplaceTruncAnd) { 8514 SDValue TruncAnd = 8515 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8516 CombineTo(N0.getNode(), TruncAnd); 8517 } 8518 if (NoReplaceTrunc) { 8519 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8520 } else { 8521 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8522 LN00->getValueType(0), ExtLoad); 8523 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8524 } 8525 return SDValue(N,0); // Return N so it doesn't get rechecked! 8526 } 8527 } 8528 } 8529 8530 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8531 return V; 8532 8533 if (N0.getOpcode() == ISD::SETCC) { 8534 SDValue N00 = N0.getOperand(0); 8535 SDValue N01 = N0.getOperand(1); 8536 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 8537 EVT N00VT = N0.getOperand(0).getValueType(); 8538 8539 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 8540 // Only do this before legalize for now. 8541 if (VT.isVector() && !LegalOperations && 8542 TLI.getBooleanContents(N00VT) == 8543 TargetLowering::ZeroOrNegativeOneBooleanContent) { 8544 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 8545 // of the same size as the compared operands. Only optimize sext(setcc()) 8546 // if this is the case. 8547 EVT SVT = getSetCCResultType(N00VT); 8548 8549 // We know that the # elements of the results is the same as the 8550 // # elements of the compare (and the # elements of the compare result 8551 // for that matter). Check to see that they are the same size. If so, 8552 // we know that the element size of the sext'd result matches the 8553 // element size of the compare operands. 8554 if (VT.getSizeInBits() == SVT.getSizeInBits()) 8555 return DAG.getSetCC(DL, VT, N00, N01, CC); 8556 8557 // If the desired elements are smaller or larger than the source 8558 // elements, we can use a matching integer vector type and then 8559 // truncate/sign extend. 8560 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 8561 if (SVT == MatchingVecType) { 8562 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 8563 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 8564 } 8565 } 8566 8567 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 8568 // Here, T can be 1 or -1, depending on the type of the setcc and 8569 // getBooleanContents(). 8570 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 8571 8572 // To determine the "true" side of the select, we need to know the high bit 8573 // of the value returned by the setcc if it evaluates to true. 8574 // If the type of the setcc is i1, then the true case of the select is just 8575 // sext(i1 1), that is, -1. 8576 // If the type of the setcc is larger (say, i8) then the value of the high 8577 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 8578 // of the appropriate width. 8579 SDValue ExtTrueVal = (SetCCWidth == 1) 8580 ? DAG.getAllOnesConstant(DL, VT) 8581 : DAG.getBoolConstant(true, DL, VT, N00VT); 8582 SDValue Zero = DAG.getConstant(0, DL, VT); 8583 if (SDValue SCC = 8584 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 8585 return SCC; 8586 8587 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 8588 EVT SetCCVT = getSetCCResultType(N00VT); 8589 // Don't do this transform for i1 because there's a select transform 8590 // that would reverse it. 8591 // TODO: We should not do this transform at all without a target hook 8592 // because a sext is likely cheaper than a select? 8593 if (SetCCVT.getScalarSizeInBits() != 1 && 8594 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 8595 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 8596 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 8597 } 8598 } 8599 } 8600 8601 // fold (sext x) -> (zext x) if the sign bit is known zero. 8602 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 8603 DAG.SignBitIsZero(N0)) 8604 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 8605 8606 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8607 return NewVSel; 8608 8609 return SDValue(); 8610 } 8611 8612 // isTruncateOf - If N is a truncate of some other value, return true, record 8613 // the value being truncated in Op and which of Op's bits are zero/one in Known. 8614 // This function computes KnownBits to avoid a duplicated call to 8615 // computeKnownBits in the caller. 8616 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 8617 KnownBits &Known) { 8618 if (N->getOpcode() == ISD::TRUNCATE) { 8619 Op = N->getOperand(0); 8620 DAG.computeKnownBits(Op, Known); 8621 return true; 8622 } 8623 8624 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 8625 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 8626 return false; 8627 8628 SDValue Op0 = N->getOperand(0); 8629 SDValue Op1 = N->getOperand(1); 8630 assert(Op0.getValueType() == Op1.getValueType()); 8631 8632 if (isNullConstant(Op0)) 8633 Op = Op1; 8634 else if (isNullConstant(Op1)) 8635 Op = Op0; 8636 else 8637 return false; 8638 8639 DAG.computeKnownBits(Op, Known); 8640 8641 if (!(Known.Zero | 1).isAllOnesValue()) 8642 return false; 8643 8644 return true; 8645 } 8646 8647 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 8648 SDValue N0 = N->getOperand(0); 8649 EVT VT = N->getValueType(0); 8650 8651 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8652 LegalOperations)) 8653 return SDValue(Res, 0); 8654 8655 // fold (zext (zext x)) -> (zext x) 8656 // fold (zext (aext x)) -> (zext x) 8657 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8658 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 8659 N0.getOperand(0)); 8660 8661 // fold (zext (truncate x)) -> (zext x) or 8662 // (zext (truncate x)) -> (truncate x) 8663 // This is valid when the truncated bits of x are already zero. 8664 // FIXME: We should extend this to work for vectors too. 8665 SDValue Op; 8666 KnownBits Known; 8667 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 8668 APInt TruncatedBits = 8669 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 8670 APInt(Op.getValueSizeInBits(), 0) : 8671 APInt::getBitsSet(Op.getValueSizeInBits(), 8672 N0.getValueSizeInBits(), 8673 std::min(Op.getValueSizeInBits(), 8674 VT.getSizeInBits())); 8675 if (TruncatedBits.isSubsetOf(Known.Zero)) 8676 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8677 } 8678 8679 // fold (zext (truncate x)) -> (and x, mask) 8680 if (N0.getOpcode() == ISD::TRUNCATE) { 8681 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 8682 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 8683 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8684 SDNode *oye = N0.getOperand(0).getNode(); 8685 if (NarrowLoad.getNode() != N0.getNode()) { 8686 CombineTo(N0.getNode(), NarrowLoad); 8687 // CombineTo deleted the truncate, if needed, but not what's under it. 8688 AddToWorklist(oye); 8689 } 8690 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8691 } 8692 8693 EVT SrcVT = N0.getOperand(0).getValueType(); 8694 EVT MinVT = N0.getValueType(); 8695 8696 // Try to mask before the extension to avoid having to generate a larger mask, 8697 // possibly over several sub-vectors. 8698 if (SrcVT.bitsLT(VT) && VT.isVector()) { 8699 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 8700 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 8701 SDValue Op = N0.getOperand(0); 8702 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8703 AddToWorklist(Op.getNode()); 8704 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8705 // Transfer the debug info; the new node is equivalent to N0. 8706 DAG.transferDbgValues(N0, ZExtOrTrunc); 8707 return ZExtOrTrunc; 8708 } 8709 } 8710 8711 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 8712 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8713 AddToWorklist(Op.getNode()); 8714 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8715 // We may safely transfer the debug info describing the truncate node over 8716 // to the equivalent and operation. 8717 DAG.transferDbgValues(N0, And); 8718 return And; 8719 } 8720 } 8721 8722 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 8723 // if either of the casts is not free. 8724 if (N0.getOpcode() == ISD::AND && 8725 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8726 N0.getOperand(1).getOpcode() == ISD::Constant && 8727 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8728 N0.getValueType()) || 8729 !TLI.isZExtFree(N0.getValueType(), VT))) { 8730 SDValue X = N0.getOperand(0).getOperand(0); 8731 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 8732 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8733 Mask = Mask.zext(VT.getSizeInBits()); 8734 SDLoc DL(N); 8735 return DAG.getNode(ISD::AND, DL, VT, 8736 X, DAG.getConstant(Mask, DL, VT)); 8737 } 8738 8739 // Try to simplify (zext (load x)). 8740 if (SDValue foldedExt = 8741 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8742 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 8743 return foldedExt; 8744 8745 // fold (zext (load x)) to multiple smaller zextloads. 8746 // Only on illegal but splittable vectors. 8747 if (SDValue ExtLoad = CombineExtLoad(N)) 8748 return ExtLoad; 8749 8750 // fold (zext (and/or/xor (load x), cst)) -> 8751 // (and/or/xor (zextload x), (zext cst)) 8752 // Unless (and (load x) cst) will match as a zextload already and has 8753 // additional users. 8754 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8755 N0.getOpcode() == ISD::XOR) && 8756 isa<LoadSDNode>(N0.getOperand(0)) && 8757 N0.getOperand(1).getOpcode() == ISD::Constant && 8758 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8759 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8760 EVT MemVT = LN00->getMemoryVT(); 8761 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 8762 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 8763 bool DoXform = true; 8764 SmallVector<SDNode*, 4> SetCCs; 8765 if (!N0.hasOneUse()) { 8766 if (N0.getOpcode() == ISD::AND) { 8767 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 8768 EVT LoadResultTy = AndC->getValueType(0); 8769 EVT ExtVT; 8770 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 8771 DoXform = false; 8772 } 8773 } 8774 if (DoXform) 8775 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8776 ISD::ZERO_EXTEND, SetCCs, TLI); 8777 if (DoXform) { 8778 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 8779 LN00->getChain(), LN00->getBasePtr(), 8780 LN00->getMemoryVT(), 8781 LN00->getMemOperand()); 8782 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8783 Mask = Mask.zext(VT.getSizeInBits()); 8784 SDLoc DL(N); 8785 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8786 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8787 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8788 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8789 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8790 CombineTo(N, And); 8791 // If N0 has multiple uses, change other uses as well. 8792 if (NoReplaceTruncAnd) { 8793 SDValue TruncAnd = 8794 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8795 CombineTo(N0.getNode(), TruncAnd); 8796 } 8797 if (NoReplaceTrunc) { 8798 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8799 } else { 8800 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8801 LN00->getValueType(0), ExtLoad); 8802 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8803 } 8804 return SDValue(N,0); // Return N so it doesn't get rechecked! 8805 } 8806 } 8807 } 8808 8809 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8810 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8811 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 8812 return ZExtLoad; 8813 8814 // Try to simplify (zext (zextload x)). 8815 if (SDValue foldedExt = tryToFoldExtOfExtload( 8816 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 8817 return foldedExt; 8818 8819 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8820 return V; 8821 8822 if (N0.getOpcode() == ISD::SETCC) { 8823 // Only do this before legalize for now. 8824 if (!LegalOperations && VT.isVector() && 8825 N0.getValueType().getVectorElementType() == MVT::i1) { 8826 EVT N00VT = N0.getOperand(0).getValueType(); 8827 if (getSetCCResultType(N00VT) == N0.getValueType()) 8828 return SDValue(); 8829 8830 // We know that the # elements of the results is the same as the # 8831 // elements of the compare (and the # elements of the compare result for 8832 // that matter). Check to see that they are the same size. If so, we know 8833 // that the element size of the sext'd result matches the element size of 8834 // the compare operands. 8835 SDLoc DL(N); 8836 SDValue VecOnes = DAG.getConstant(1, DL, VT); 8837 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 8838 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 8839 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 8840 N0.getOperand(1), N0.getOperand(2)); 8841 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 8842 } 8843 8844 // If the desired elements are smaller or larger than the source 8845 // elements we can use a matching integer vector type and then 8846 // truncate/sign extend. 8847 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8848 SDValue VsetCC = 8849 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 8850 N0.getOperand(1), N0.getOperand(2)); 8851 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 8852 VecOnes); 8853 } 8854 8855 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8856 SDLoc DL(N); 8857 if (SDValue SCC = SimplifySelectCC( 8858 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8859 DAG.getConstant(0, DL, VT), 8860 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8861 return SCC; 8862 } 8863 8864 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 8865 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 8866 isa<ConstantSDNode>(N0.getOperand(1)) && 8867 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 8868 N0.hasOneUse()) { 8869 SDValue ShAmt = N0.getOperand(1); 8870 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8871 if (N0.getOpcode() == ISD::SHL) { 8872 SDValue InnerZExt = N0.getOperand(0); 8873 // If the original shl may be shifting out bits, do not perform this 8874 // transformation. 8875 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 8876 InnerZExt.getOperand(0).getValueSizeInBits(); 8877 if (ShAmtVal > KnownZeroBits) 8878 return SDValue(); 8879 } 8880 8881 SDLoc DL(N); 8882 8883 // Ensure that the shift amount is wide enough for the shifted value. 8884 if (VT.getSizeInBits() >= 256) 8885 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 8886 8887 return DAG.getNode(N0.getOpcode(), DL, VT, 8888 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8889 ShAmt); 8890 } 8891 8892 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8893 return NewVSel; 8894 8895 return SDValue(); 8896 } 8897 8898 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8899 SDValue N0 = N->getOperand(0); 8900 EVT VT = N->getValueType(0); 8901 8902 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8903 LegalOperations)) 8904 return SDValue(Res, 0); 8905 8906 // fold (aext (aext x)) -> (aext x) 8907 // fold (aext (zext x)) -> (zext x) 8908 // fold (aext (sext x)) -> (sext x) 8909 if (N0.getOpcode() == ISD::ANY_EXTEND || 8910 N0.getOpcode() == ISD::ZERO_EXTEND || 8911 N0.getOpcode() == ISD::SIGN_EXTEND) 8912 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8913 8914 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8915 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8916 if (N0.getOpcode() == ISD::TRUNCATE) { 8917 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8918 SDNode *oye = N0.getOperand(0).getNode(); 8919 if (NarrowLoad.getNode() != N0.getNode()) { 8920 CombineTo(N0.getNode(), NarrowLoad); 8921 // CombineTo deleted the truncate, if needed, but not what's under it. 8922 AddToWorklist(oye); 8923 } 8924 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8925 } 8926 } 8927 8928 // fold (aext (truncate x)) 8929 if (N0.getOpcode() == ISD::TRUNCATE) 8930 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8931 8932 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 8933 // if the trunc is not free. 8934 if (N0.getOpcode() == ISD::AND && 8935 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8936 N0.getOperand(1).getOpcode() == ISD::Constant && 8937 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8938 N0.getValueType())) { 8939 SDLoc DL(N); 8940 SDValue X = N0.getOperand(0).getOperand(0); 8941 X = DAG.getAnyExtOrTrunc(X, DL, VT); 8942 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8943 Mask = Mask.zext(VT.getSizeInBits()); 8944 return DAG.getNode(ISD::AND, DL, VT, 8945 X, DAG.getConstant(Mask, DL, VT)); 8946 } 8947 8948 // fold (aext (load x)) -> (aext (truncate (extload x))) 8949 // None of the supported targets knows how to perform load and any_ext 8950 // on vectors in one instruction. We only perform this transformation on 8951 // scalars. 8952 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 8953 ISD::isUNINDEXEDLoad(N0.getNode()) && 8954 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8955 bool DoXform = true; 8956 SmallVector<SDNode*, 4> SetCCs; 8957 if (!N0.hasOneUse()) 8958 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, 8959 TLI); 8960 if (DoXform) { 8961 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8962 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8963 LN0->getChain(), 8964 LN0->getBasePtr(), N0.getValueType(), 8965 LN0->getMemOperand()); 8966 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 8967 // If the load value is used only by N, replace it via CombineTo N. 8968 bool NoReplaceTrunc = N0.hasOneUse(); 8969 CombineTo(N, ExtLoad); 8970 if (NoReplaceTrunc) { 8971 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8972 } else { 8973 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8974 N0.getValueType(), ExtLoad); 8975 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8976 } 8977 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8978 } 8979 } 8980 8981 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 8982 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 8983 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 8984 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 8985 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 8986 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8987 ISD::LoadExtType ExtType = LN0->getExtensionType(); 8988 EVT MemVT = LN0->getMemoryVT(); 8989 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 8990 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 8991 VT, LN0->getChain(), LN0->getBasePtr(), 8992 MemVT, LN0->getMemOperand()); 8993 CombineTo(N, ExtLoad); 8994 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8995 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8996 } 8997 } 8998 8999 if (N0.getOpcode() == ISD::SETCC) { 9000 // For vectors: 9001 // aext(setcc) -> vsetcc 9002 // aext(setcc) -> truncate(vsetcc) 9003 // aext(setcc) -> aext(vsetcc) 9004 // Only do this before legalize for now. 9005 if (VT.isVector() && !LegalOperations) { 9006 EVT N00VT = N0.getOperand(0).getValueType(); 9007 if (getSetCCResultType(N00VT) == N0.getValueType()) 9008 return SDValue(); 9009 9010 // We know that the # elements of the results is the same as the 9011 // # elements of the compare (and the # elements of the compare result 9012 // for that matter). Check to see that they are the same size. If so, 9013 // we know that the element size of the sext'd result matches the 9014 // element size of the compare operands. 9015 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 9016 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 9017 N0.getOperand(1), 9018 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9019 // If the desired elements are smaller or larger than the source 9020 // elements we can use a matching integer vector type and then 9021 // truncate/any extend 9022 else { 9023 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 9024 SDValue VsetCC = 9025 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 9026 N0.getOperand(1), 9027 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9028 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 9029 } 9030 } 9031 9032 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 9033 SDLoc DL(N); 9034 if (SDValue SCC = SimplifySelectCC( 9035 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 9036 DAG.getConstant(0, DL, VT), 9037 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 9038 return SCC; 9039 } 9040 9041 return SDValue(); 9042 } 9043 9044 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 9045 unsigned Opcode = N->getOpcode(); 9046 SDValue N0 = N->getOperand(0); 9047 SDValue N1 = N->getOperand(1); 9048 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 9049 9050 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 9051 if (N0.getOpcode() == Opcode && 9052 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 9053 return N0; 9054 9055 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 9056 N0.getOperand(0).getOpcode() == Opcode) { 9057 // We have an assert, truncate, assert sandwich. Make one stronger assert 9058 // by asserting on the smallest asserted type to the larger source type. 9059 // This eliminates the later assert: 9060 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 9061 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 9062 SDValue BigA = N0.getOperand(0); 9063 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 9064 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 9065 "Asserting zero/sign-extended bits to a type larger than the " 9066 "truncated destination does not provide information"); 9067 9068 SDLoc DL(N); 9069 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 9070 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 9071 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 9072 BigA.getOperand(0), MinAssertVTVal); 9073 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 9074 } 9075 9076 return SDValue(); 9077 } 9078 9079 /// If the result of a wider load is shifted to right of N bits and then 9080 /// truncated to a narrower type and where N is a multiple of number of bits of 9081 /// the narrower type, transform it to a narrower load from address + N / num of 9082 /// bits of new type. Also narrow the load if the result is masked with an AND 9083 /// to effectively produce a smaller type. If the result is to be extended, also 9084 /// fold the extension to form a extending load. 9085 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 9086 unsigned Opc = N->getOpcode(); 9087 9088 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 9089 SDValue N0 = N->getOperand(0); 9090 EVT VT = N->getValueType(0); 9091 EVT ExtVT = VT; 9092 9093 // This transformation isn't valid for vector loads. 9094 if (VT.isVector()) 9095 return SDValue(); 9096 9097 unsigned ShAmt = 0; 9098 bool HasShiftedOffset = false; 9099 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 9100 // extended to VT. 9101 if (Opc == ISD::SIGN_EXTEND_INREG) { 9102 ExtType = ISD::SEXTLOAD; 9103 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9104 } else if (Opc == ISD::SRL) { 9105 // Another special-case: SRL is basically zero-extending a narrower value, 9106 // or it maybe shifting a higher subword, half or byte into the lowest 9107 // bits. 9108 ExtType = ISD::ZEXTLOAD; 9109 N0 = SDValue(N, 0); 9110 9111 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 9112 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9113 if (!N01 || !LN0) 9114 return SDValue(); 9115 9116 uint64_t ShiftAmt = N01->getZExtValue(); 9117 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 9118 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 9119 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 9120 else 9121 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 9122 VT.getSizeInBits() - ShiftAmt); 9123 } else if (Opc == ISD::AND) { 9124 // An AND with a constant mask is the same as a truncate + zero-extend. 9125 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9126 if (!AndC) 9127 return SDValue(); 9128 9129 const APInt &Mask = AndC->getAPIntValue(); 9130 unsigned ActiveBits = 0; 9131 if (Mask.isMask()) { 9132 ActiveBits = Mask.countTrailingOnes(); 9133 } else if (Mask.isShiftedMask()) { 9134 ShAmt = Mask.countTrailingZeros(); 9135 APInt ShiftedMask = Mask.lshr(ShAmt); 9136 ActiveBits = ShiftedMask.countTrailingOnes(); 9137 HasShiftedOffset = true; 9138 } else 9139 return SDValue(); 9140 9141 ExtType = ISD::ZEXTLOAD; 9142 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 9143 } 9144 9145 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 9146 SDValue SRL = N0; 9147 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 9148 ShAmt = ConstShift->getZExtValue(); 9149 unsigned EVTBits = ExtVT.getSizeInBits(); 9150 // Is the shift amount a multiple of size of VT? 9151 if ((ShAmt & (EVTBits-1)) == 0) { 9152 N0 = N0.getOperand(0); 9153 // Is the load width a multiple of size of VT? 9154 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 9155 return SDValue(); 9156 } 9157 9158 // At this point, we must have a load or else we can't do the transform. 9159 if (!isa<LoadSDNode>(N0)) return SDValue(); 9160 9161 auto *LN0 = cast<LoadSDNode>(N0); 9162 9163 // Because a SRL must be assumed to *need* to zero-extend the high bits 9164 // (as opposed to anyext the high bits), we can't combine the zextload 9165 // lowering of SRL and an sextload. 9166 if (LN0->getExtensionType() == ISD::SEXTLOAD) 9167 return SDValue(); 9168 9169 // If the shift amount is larger than the input type then we're not 9170 // accessing any of the loaded bytes. If the load was a zextload/extload 9171 // then the result of the shift+trunc is zero/undef (handled elsewhere). 9172 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 9173 return SDValue(); 9174 9175 // If the SRL is only used by a masking AND, we may be able to adjust 9176 // the ExtVT to make the AND redundant. 9177 SDNode *Mask = *(SRL->use_begin()); 9178 if (Mask->getOpcode() == ISD::AND && 9179 isa<ConstantSDNode>(Mask->getOperand(1))) { 9180 const APInt &ShiftMask = 9181 cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue(); 9182 if (ShiftMask.isMask()) { 9183 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 9184 ShiftMask.countTrailingOnes()); 9185 // If the mask is smaller, recompute the type. 9186 if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) && 9187 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 9188 ExtVT = MaskedVT; 9189 } 9190 } 9191 } 9192 } 9193 9194 // If the load is shifted left (and the result isn't shifted back right), 9195 // we can fold the truncate through the shift. 9196 unsigned ShLeftAmt = 0; 9197 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9198 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 9199 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 9200 ShLeftAmt = N01->getZExtValue(); 9201 N0 = N0.getOperand(0); 9202 } 9203 } 9204 9205 // If we haven't found a load, we can't narrow it. 9206 if (!isa<LoadSDNode>(N0)) 9207 return SDValue(); 9208 9209 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9210 if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 9211 return SDValue(); 9212 9213 auto AdjustBigEndianShift = [&](unsigned ShAmt) { 9214 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 9215 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 9216 return LVTStoreBits - EVTStoreBits - ShAmt; 9217 }; 9218 9219 // For big endian targets, we need to adjust the offset to the pointer to 9220 // load the correct bytes. 9221 if (DAG.getDataLayout().isBigEndian()) 9222 ShAmt = AdjustBigEndianShift(ShAmt); 9223 9224 EVT PtrType = N0.getOperand(1).getValueType(); 9225 uint64_t PtrOff = ShAmt / 8; 9226 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 9227 SDLoc DL(LN0); 9228 // The original load itself didn't wrap, so an offset within it doesn't. 9229 SDNodeFlags Flags; 9230 Flags.setNoUnsignedWrap(true); 9231 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 9232 PtrType, LN0->getBasePtr(), 9233 DAG.getConstant(PtrOff, DL, PtrType), 9234 Flags); 9235 AddToWorklist(NewPtr.getNode()); 9236 9237 SDValue Load; 9238 if (ExtType == ISD::NON_EXTLOAD) 9239 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 9240 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9241 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9242 else 9243 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 9244 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 9245 NewAlign, LN0->getMemOperand()->getFlags(), 9246 LN0->getAAInfo()); 9247 9248 // Replace the old load's chain with the new load's chain. 9249 WorklistRemover DeadNodes(*this); 9250 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9251 9252 // Shift the result left, if we've swallowed a left shift. 9253 SDValue Result = Load; 9254 if (ShLeftAmt != 0) { 9255 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 9256 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 9257 ShImmTy = VT; 9258 // If the shift amount is as large as the result size (but, presumably, 9259 // no larger than the source) then the useful bits of the result are 9260 // zero; we can't simply return the shortened shift, because the result 9261 // of that operation is undefined. 9262 SDLoc DL(N0); 9263 if (ShLeftAmt >= VT.getSizeInBits()) 9264 Result = DAG.getConstant(0, DL, VT); 9265 else 9266 Result = DAG.getNode(ISD::SHL, DL, VT, 9267 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 9268 } 9269 9270 if (HasShiftedOffset) { 9271 // Recalculate the shift amount after it has been altered to calculate 9272 // the offset. 9273 if (DAG.getDataLayout().isBigEndian()) 9274 ShAmt = AdjustBigEndianShift(ShAmt); 9275 9276 // We're using a shifted mask, so the load now has an offset. This means we 9277 // now need to shift right the mask to match the new load and then shift 9278 // right the result of the AND. 9279 const APInt &Mask = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue(); 9280 APInt ShiftedMask = Mask.lshr(ShAmt); 9281 DAG.UpdateNodeOperands(N, Result, DAG.getConstant(ShiftedMask, DL, VT)); 9282 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); 9283 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, SDValue(N, 0), 9284 ShiftC); 9285 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shifted); 9286 DAG.UpdateNodeOperands(Shifted.getNode(), SDValue(N, 0), ShiftC); 9287 } 9288 // Return the new loaded value. 9289 return Result; 9290 } 9291 9292 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 9293 SDValue N0 = N->getOperand(0); 9294 SDValue N1 = N->getOperand(1); 9295 EVT VT = N->getValueType(0); 9296 EVT EVT = cast<VTSDNode>(N1)->getVT(); 9297 unsigned VTBits = VT.getScalarSizeInBits(); 9298 unsigned EVTBits = EVT.getScalarSizeInBits(); 9299 9300 if (N0.isUndef()) 9301 return DAG.getUNDEF(VT); 9302 9303 // fold (sext_in_reg c1) -> c1 9304 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9305 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 9306 9307 // If the input is already sign extended, just drop the extension. 9308 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 9309 return N0; 9310 9311 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 9312 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 9313 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 9314 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9315 N0.getOperand(0), N1); 9316 9317 // fold (sext_in_reg (sext x)) -> (sext x) 9318 // fold (sext_in_reg (aext x)) -> (sext x) 9319 // if x is small enough. 9320 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 9321 SDValue N00 = N0.getOperand(0); 9322 if (N00.getScalarValueSizeInBits() <= EVTBits && 9323 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9324 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9325 } 9326 9327 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 9328 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 9329 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 9330 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 9331 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 9332 if (!LegalOperations || 9333 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 9334 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 9335 } 9336 9337 // fold (sext_in_reg (zext x)) -> (sext x) 9338 // iff we are extending the source sign bit. 9339 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 9340 SDValue N00 = N0.getOperand(0); 9341 if (N00.getScalarValueSizeInBits() == EVTBits && 9342 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9343 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9344 } 9345 9346 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 9347 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 9348 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 9349 9350 // fold operands of sext_in_reg based on knowledge that the top bits are not 9351 // demanded. 9352 if (SimplifyDemandedBits(SDValue(N, 0))) 9353 return SDValue(N, 0); 9354 9355 // fold (sext_in_reg (load x)) -> (smaller sextload x) 9356 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 9357 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 9358 return NarrowLoad; 9359 9360 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 9361 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 9362 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 9363 if (N0.getOpcode() == ISD::SRL) { 9364 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 9365 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 9366 // We can turn this into an SRA iff the input to the SRL is already sign 9367 // extended enough. 9368 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 9369 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 9370 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 9371 N0.getOperand(0), N0.getOperand(1)); 9372 } 9373 } 9374 9375 // fold (sext_inreg (extload x)) -> (sextload x) 9376 // If sextload is not supported by target, we can only do the combine when 9377 // load has one use. Doing otherwise can block folding the extload with other 9378 // extends that the target does support. 9379 if (ISD::isEXTLoad(N0.getNode()) && 9380 ISD::isUNINDEXEDLoad(N0.getNode()) && 9381 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9382 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 9383 N0.hasOneUse()) || 9384 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9385 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9386 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9387 LN0->getChain(), 9388 LN0->getBasePtr(), EVT, 9389 LN0->getMemOperand()); 9390 CombineTo(N, ExtLoad); 9391 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9392 AddToWorklist(ExtLoad.getNode()); 9393 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9394 } 9395 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 9396 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 9397 N0.hasOneUse() && 9398 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9399 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9400 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9401 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9402 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9403 LN0->getChain(), 9404 LN0->getBasePtr(), EVT, 9405 LN0->getMemOperand()); 9406 CombineTo(N, ExtLoad); 9407 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9408 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9409 } 9410 9411 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 9412 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 9413 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 9414 N0.getOperand(1), false)) 9415 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9416 BSwap, N1); 9417 } 9418 9419 return SDValue(); 9420 } 9421 9422 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 9423 SDValue N0 = N->getOperand(0); 9424 EVT VT = N->getValueType(0); 9425 9426 if (N0.isUndef()) 9427 return DAG.getUNDEF(VT); 9428 9429 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9430 LegalOperations)) 9431 return SDValue(Res, 0); 9432 9433 return SDValue(); 9434 } 9435 9436 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 9437 SDValue N0 = N->getOperand(0); 9438 EVT VT = N->getValueType(0); 9439 9440 if (N0.isUndef()) 9441 return DAG.getUNDEF(VT); 9442 9443 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9444 LegalOperations)) 9445 return SDValue(Res, 0); 9446 9447 return SDValue(); 9448 } 9449 9450 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 9451 SDValue N0 = N->getOperand(0); 9452 EVT VT = N->getValueType(0); 9453 bool isLE = DAG.getDataLayout().isLittleEndian(); 9454 9455 // noop truncate 9456 if (N0.getValueType() == N->getValueType(0)) 9457 return N0; 9458 9459 // fold (truncate (truncate x)) -> (truncate x) 9460 if (N0.getOpcode() == ISD::TRUNCATE) 9461 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9462 9463 // fold (truncate c1) -> c1 9464 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 9465 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 9466 if (C.getNode() != N) 9467 return C; 9468 } 9469 9470 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 9471 if (N0.getOpcode() == ISD::ZERO_EXTEND || 9472 N0.getOpcode() == ISD::SIGN_EXTEND || 9473 N0.getOpcode() == ISD::ANY_EXTEND) { 9474 // if the source is smaller than the dest, we still need an extend. 9475 if (N0.getOperand(0).getValueType().bitsLT(VT)) 9476 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 9477 // if the source is larger than the dest, than we just need the truncate. 9478 if (N0.getOperand(0).getValueType().bitsGT(VT)) 9479 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9480 // if the source and dest are the same type, we can drop both the extend 9481 // and the truncate. 9482 return N0.getOperand(0); 9483 } 9484 9485 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 9486 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 9487 return SDValue(); 9488 9489 // Fold extract-and-trunc into a narrow extract. For example: 9490 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 9491 // i32 y = TRUNCATE(i64 x) 9492 // -- becomes -- 9493 // v16i8 b = BITCAST (v2i64 val) 9494 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 9495 // 9496 // Note: We only run this optimization after type legalization (which often 9497 // creates this pattern) and before operation legalization after which 9498 // we need to be more careful about the vector instructions that we generate. 9499 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 9500 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 9501 EVT VecTy = N0.getOperand(0).getValueType(); 9502 EVT ExTy = N0.getValueType(); 9503 EVT TrTy = N->getValueType(0); 9504 9505 unsigned NumElem = VecTy.getVectorNumElements(); 9506 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 9507 9508 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 9509 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 9510 9511 SDValue EltNo = N0->getOperand(1); 9512 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 9513 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9514 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 9515 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 9516 9517 SDLoc DL(N); 9518 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 9519 DAG.getBitcast(NVT, N0.getOperand(0)), 9520 DAG.getConstant(Index, DL, IndexTy)); 9521 } 9522 } 9523 9524 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 9525 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 9526 EVT SrcVT = N0.getValueType(); 9527 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 9528 TLI.isTruncateFree(SrcVT, VT)) { 9529 SDLoc SL(N0); 9530 SDValue Cond = N0.getOperand(0); 9531 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9532 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 9533 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 9534 } 9535 } 9536 9537 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 9538 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9539 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 9540 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 9541 SDValue Amt = N0.getOperand(1); 9542 KnownBits Known; 9543 DAG.computeKnownBits(Amt, Known); 9544 unsigned Size = VT.getScalarSizeInBits(); 9545 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 9546 SDLoc SL(N); 9547 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 9548 9549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9550 if (AmtVT != Amt.getValueType()) { 9551 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 9552 AddToWorklist(Amt.getNode()); 9553 } 9554 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 9555 } 9556 } 9557 9558 // Fold a series of buildvector, bitcast, and truncate if possible. 9559 // For example fold 9560 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 9561 // (2xi32 (buildvector x, y)). 9562 if (Level == AfterLegalizeVectorOps && VT.isVector() && 9563 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 9564 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 9565 N0.getOperand(0).hasOneUse()) { 9566 SDValue BuildVect = N0.getOperand(0); 9567 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 9568 EVT TruncVecEltTy = VT.getVectorElementType(); 9569 9570 // Check that the element types match. 9571 if (BuildVectEltTy == TruncVecEltTy) { 9572 // Now we only need to compute the offset of the truncated elements. 9573 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 9574 unsigned TruncVecNumElts = VT.getVectorNumElements(); 9575 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 9576 9577 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 9578 "Invalid number of elements"); 9579 9580 SmallVector<SDValue, 8> Opnds; 9581 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 9582 Opnds.push_back(BuildVect.getOperand(i)); 9583 9584 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 9585 } 9586 } 9587 9588 // See if we can simplify the input to this truncate through knowledge that 9589 // only the low bits are being used. 9590 // For example "trunc (or (shl x, 8), y)" // -> trunc y 9591 // Currently we only perform this optimization on scalars because vectors 9592 // may have different active low bits. 9593 if (!VT.isVector()) { 9594 APInt Mask = 9595 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 9596 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 9597 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 9598 } 9599 9600 // fold (truncate (load x)) -> (smaller load x) 9601 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 9602 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 9603 if (SDValue Reduced = ReduceLoadWidth(N)) 9604 return Reduced; 9605 9606 // Handle the case where the load remains an extending load even 9607 // after truncation. 9608 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 9609 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9610 if (!LN0->isVolatile() && 9611 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 9612 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 9613 VT, LN0->getChain(), LN0->getBasePtr(), 9614 LN0->getMemoryVT(), 9615 LN0->getMemOperand()); 9616 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 9617 return NewLoad; 9618 } 9619 } 9620 } 9621 9622 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 9623 // where ... are all 'undef'. 9624 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 9625 SmallVector<EVT, 8> VTs; 9626 SDValue V; 9627 unsigned Idx = 0; 9628 unsigned NumDefs = 0; 9629 9630 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 9631 SDValue X = N0.getOperand(i); 9632 if (!X.isUndef()) { 9633 V = X; 9634 Idx = i; 9635 NumDefs++; 9636 } 9637 // Stop if more than one members are non-undef. 9638 if (NumDefs > 1) 9639 break; 9640 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 9641 VT.getVectorElementType(), 9642 X.getValueType().getVectorNumElements())); 9643 } 9644 9645 if (NumDefs == 0) 9646 return DAG.getUNDEF(VT); 9647 9648 if (NumDefs == 1) { 9649 assert(V.getNode() && "The single defined operand is empty!"); 9650 SmallVector<SDValue, 8> Opnds; 9651 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 9652 if (i != Idx) { 9653 Opnds.push_back(DAG.getUNDEF(VTs[i])); 9654 continue; 9655 } 9656 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 9657 AddToWorklist(NV.getNode()); 9658 Opnds.push_back(NV); 9659 } 9660 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 9661 } 9662 } 9663 9664 // Fold truncate of a bitcast of a vector to an extract of the low vector 9665 // element. 9666 // 9667 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 9668 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 9669 SDValue VecSrc = N0.getOperand(0); 9670 EVT SrcVT = VecSrc.getValueType(); 9671 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 9672 (!LegalOperations || 9673 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 9674 SDLoc SL(N); 9675 9676 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 9677 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 9678 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 9679 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 9680 } 9681 } 9682 9683 // Simplify the operands using demanded-bits information. 9684 if (!VT.isVector() && 9685 SimplifyDemandedBits(SDValue(N, 0))) 9686 return SDValue(N, 0); 9687 9688 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 9689 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 9690 // When the adde's carry is not used. 9691 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 9692 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 9693 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 9694 SDLoc SL(N); 9695 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9696 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9697 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 9698 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 9699 } 9700 9701 // fold (truncate (extract_subvector(ext x))) -> 9702 // (extract_subvector x) 9703 // TODO: This can be generalized to cover cases where the truncate and extract 9704 // do not fully cancel each other out. 9705 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 9706 SDValue N00 = N0.getOperand(0); 9707 if (N00.getOpcode() == ISD::SIGN_EXTEND || 9708 N00.getOpcode() == ISD::ZERO_EXTEND || 9709 N00.getOpcode() == ISD::ANY_EXTEND) { 9710 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 9711 VT.getVectorElementType()) 9712 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 9713 N00.getOperand(0), N0.getOperand(1)); 9714 } 9715 } 9716 9717 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 9718 return NewVSel; 9719 9720 return SDValue(); 9721 } 9722 9723 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 9724 SDValue Elt = N->getOperand(i); 9725 if (Elt.getOpcode() != ISD::MERGE_VALUES) 9726 return Elt.getNode(); 9727 return Elt.getOperand(Elt.getResNo()).getNode(); 9728 } 9729 9730 /// build_pair (load, load) -> load 9731 /// if load locations are consecutive. 9732 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 9733 assert(N->getOpcode() == ISD::BUILD_PAIR); 9734 9735 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 9736 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 9737 9738 // A BUILD_PAIR is always having the least significant part in elt 0 and the 9739 // most significant part in elt 1. So when combining into one large load, we 9740 // need to consider the endianness. 9741 if (DAG.getDataLayout().isBigEndian()) 9742 std::swap(LD1, LD2); 9743 9744 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 9745 LD1->getAddressSpace() != LD2->getAddressSpace()) 9746 return SDValue(); 9747 EVT LD1VT = LD1->getValueType(0); 9748 unsigned LD1Bytes = LD1VT.getStoreSize(); 9749 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 9750 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 9751 unsigned Align = LD1->getAlignment(); 9752 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 9753 VT.getTypeForEVT(*DAG.getContext())); 9754 9755 if (NewAlign <= Align && 9756 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 9757 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 9758 LD1->getPointerInfo(), Align); 9759 } 9760 9761 return SDValue(); 9762 } 9763 9764 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 9765 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 9766 // and Lo parts; on big-endian machines it doesn't. 9767 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 9768 } 9769 9770 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 9771 const TargetLowering &TLI) { 9772 // If this is not a bitcast to an FP type or if the target doesn't have 9773 // IEEE754-compliant FP logic, we're done. 9774 EVT VT = N->getValueType(0); 9775 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 9776 return SDValue(); 9777 9778 // TODO: Use splat values for the constant-checking below and remove this 9779 // restriction. 9780 SDValue N0 = N->getOperand(0); 9781 EVT SourceVT = N0.getValueType(); 9782 if (SourceVT.isVector()) 9783 return SDValue(); 9784 9785 unsigned FPOpcode; 9786 APInt SignMask; 9787 switch (N0.getOpcode()) { 9788 case ISD::AND: 9789 FPOpcode = ISD::FABS; 9790 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 9791 break; 9792 case ISD::XOR: 9793 FPOpcode = ISD::FNEG; 9794 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 9795 break; 9796 // TODO: ISD::OR --> ISD::FNABS? 9797 default: 9798 return SDValue(); 9799 } 9800 9801 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 9802 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 9803 SDValue LogicOp0 = N0.getOperand(0); 9804 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9805 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 9806 LogicOp0.getOpcode() == ISD::BITCAST && 9807 LogicOp0->getOperand(0).getValueType() == VT) 9808 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 9809 9810 return SDValue(); 9811 } 9812 9813 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 9814 SDValue N0 = N->getOperand(0); 9815 EVT VT = N->getValueType(0); 9816 9817 if (N0.isUndef()) 9818 return DAG.getUNDEF(VT); 9819 9820 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 9821 // Only do this before legalize, since afterward the target may be depending 9822 // on the bitconvert. 9823 // First check to see if this is all constant. 9824 if (!LegalTypes && 9825 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 9826 VT.isVector()) { 9827 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 9828 9829 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 9830 assert(!DestEltVT.isVector() && 9831 "Element type of vector ValueType must not be vector!"); 9832 if (isSimple) 9833 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 9834 } 9835 9836 // If the input is a constant, let getNode fold it. 9837 // We always need to check that this is just a fp -> int or int -> conversion 9838 // otherwise we will get back N which will confuse the caller into thinking 9839 // we used CombineTo. This can block target combines from running. If we can't 9840 // allowed legal operations, we need to ensure the resulting operation will be 9841 // legal. 9842 // TODO: Maybe we should check that the return value isn't N explicitly? 9843 if ((isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 9844 (!LegalOperations || TLI.isOperationLegal(ISD::ConstantFP, VT))) || 9845 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 9846 (!LegalOperations || TLI.isOperationLegal(ISD::Constant, VT)))) 9847 return DAG.getBitcast(VT, N0); 9848 9849 // (conv (conv x, t1), t2) -> (conv x, t2) 9850 if (N0.getOpcode() == ISD::BITCAST) 9851 return DAG.getBitcast(VT, N0.getOperand(0)); 9852 9853 // fold (conv (load x)) -> (load (conv*)x) 9854 // If the resultant load doesn't need a higher alignment than the original! 9855 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9856 // Do not remove the cast if the types differ in endian layout. 9857 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 9858 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 9859 // If the load is volatile, we only want to change the load type if the 9860 // resulting load is legal. Otherwise we might increase the number of 9861 // memory accesses. We don't care if the original type was legal or not 9862 // as we assume software couldn't rely on the number of accesses of an 9863 // illegal type. 9864 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9865 TLI.isOperationLegal(ISD::LOAD, VT)) && 9866 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 9867 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9868 unsigned OrigAlign = LN0->getAlignment(); 9869 9870 bool Fast = false; 9871 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9872 LN0->getAddressSpace(), OrigAlign, &Fast) && 9873 Fast) { 9874 SDValue Load = 9875 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9876 LN0->getPointerInfo(), OrigAlign, 9877 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9878 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9879 return Load; 9880 } 9881 } 9882 9883 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 9884 return V; 9885 9886 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 9887 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 9888 // 9889 // For ppc_fp128: 9890 // fold (bitcast (fneg x)) -> 9891 // flipbit = signbit 9892 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9893 // 9894 // fold (bitcast (fabs x)) -> 9895 // flipbit = (and (extract_element (bitcast x), 0), signbit) 9896 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9897 // This often reduces constant pool loads. 9898 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 9899 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 9900 N0.getNode()->hasOneUse() && VT.isInteger() && 9901 !VT.isVector() && !N0.getValueType().isVector()) { 9902 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 9903 AddToWorklist(NewConv.getNode()); 9904 9905 SDLoc DL(N); 9906 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9907 assert(VT.getSizeInBits() == 128); 9908 SDValue SignBit = DAG.getConstant( 9909 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 9910 SDValue FlipBit; 9911 if (N0.getOpcode() == ISD::FNEG) { 9912 FlipBit = SignBit; 9913 AddToWorklist(FlipBit.getNode()); 9914 } else { 9915 assert(N0.getOpcode() == ISD::FABS); 9916 SDValue Hi = 9917 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 9918 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9919 SDLoc(NewConv))); 9920 AddToWorklist(Hi.getNode()); 9921 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 9922 AddToWorklist(FlipBit.getNode()); 9923 } 9924 SDValue FlipBits = 9925 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9926 AddToWorklist(FlipBits.getNode()); 9927 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 9928 } 9929 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9930 if (N0.getOpcode() == ISD::FNEG) 9931 return DAG.getNode(ISD::XOR, DL, VT, 9932 NewConv, DAG.getConstant(SignBit, DL, VT)); 9933 assert(N0.getOpcode() == ISD::FABS); 9934 return DAG.getNode(ISD::AND, DL, VT, 9935 NewConv, DAG.getConstant(~SignBit, DL, VT)); 9936 } 9937 9938 // fold (bitconvert (fcopysign cst, x)) -> 9939 // (or (and (bitconvert x), sign), (and cst, (not sign))) 9940 // Note that we don't handle (copysign x, cst) because this can always be 9941 // folded to an fneg or fabs. 9942 // 9943 // For ppc_fp128: 9944 // fold (bitcast (fcopysign cst, x)) -> 9945 // flipbit = (and (extract_element 9946 // (xor (bitcast cst), (bitcast x)), 0), 9947 // signbit) 9948 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 9949 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 9950 isa<ConstantFPSDNode>(N0.getOperand(0)) && 9951 VT.isInteger() && !VT.isVector()) { 9952 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 9953 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 9954 if (isTypeLegal(IntXVT)) { 9955 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 9956 AddToWorklist(X.getNode()); 9957 9958 // If X has a different width than the result/lhs, sext it or truncate it. 9959 unsigned VTWidth = VT.getSizeInBits(); 9960 if (OrigXWidth < VTWidth) { 9961 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 9962 AddToWorklist(X.getNode()); 9963 } else if (OrigXWidth > VTWidth) { 9964 // To get the sign bit in the right place, we have to shift it right 9965 // before truncating. 9966 SDLoc DL(X); 9967 X = DAG.getNode(ISD::SRL, DL, 9968 X.getValueType(), X, 9969 DAG.getConstant(OrigXWidth-VTWidth, DL, 9970 X.getValueType())); 9971 AddToWorklist(X.getNode()); 9972 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 9973 AddToWorklist(X.getNode()); 9974 } 9975 9976 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9977 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 9978 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9979 AddToWorklist(Cst.getNode()); 9980 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 9981 AddToWorklist(X.getNode()); 9982 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 9983 AddToWorklist(XorResult.getNode()); 9984 SDValue XorResult64 = DAG.getNode( 9985 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 9986 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9987 SDLoc(XorResult))); 9988 AddToWorklist(XorResult64.getNode()); 9989 SDValue FlipBit = 9990 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 9991 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 9992 AddToWorklist(FlipBit.getNode()); 9993 SDValue FlipBits = 9994 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9995 AddToWorklist(FlipBits.getNode()); 9996 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 9997 } 9998 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9999 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 10000 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 10001 AddToWorklist(X.getNode()); 10002 10003 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 10004 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 10005 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 10006 AddToWorklist(Cst.getNode()); 10007 10008 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 10009 } 10010 } 10011 10012 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 10013 if (N0.getOpcode() == ISD::BUILD_PAIR) 10014 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 10015 return CombineLD; 10016 10017 // Remove double bitcasts from shuffles - this is often a legacy of 10018 // XformToShuffleWithZero being used to combine bitmaskings (of 10019 // float vectors bitcast to integer vectors) into shuffles. 10020 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 10021 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 10022 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 10023 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 10024 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 10025 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 10026 10027 // If operands are a bitcast, peek through if it casts the original VT. 10028 // If operands are a constant, just bitcast back to original VT. 10029 auto PeekThroughBitcast = [&](SDValue Op) { 10030 if (Op.getOpcode() == ISD::BITCAST && 10031 Op.getOperand(0).getValueType() == VT) 10032 return SDValue(Op.getOperand(0)); 10033 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 10034 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 10035 return DAG.getBitcast(VT, Op); 10036 return SDValue(); 10037 }; 10038 10039 // FIXME: If either input vector is bitcast, try to convert the shuffle to 10040 // the result type of this bitcast. This would eliminate at least one 10041 // bitcast. See the transform in InstCombine. 10042 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 10043 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 10044 if (!(SV0 && SV1)) 10045 return SDValue(); 10046 10047 int MaskScale = 10048 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 10049 SmallVector<int, 8> NewMask; 10050 for (int M : SVN->getMask()) 10051 for (int i = 0; i != MaskScale; ++i) 10052 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 10053 10054 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10055 if (!LegalMask) { 10056 std::swap(SV0, SV1); 10057 ShuffleVectorSDNode::commuteMask(NewMask); 10058 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10059 } 10060 10061 if (LegalMask) 10062 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 10063 } 10064 10065 return SDValue(); 10066 } 10067 10068 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 10069 EVT VT = N->getValueType(0); 10070 return CombineConsecutiveLoads(N, VT); 10071 } 10072 10073 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 10074 /// operands. DstEltVT indicates the destination element value type. 10075 SDValue DAGCombiner:: 10076 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 10077 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 10078 10079 // If this is already the right type, we're done. 10080 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 10081 10082 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 10083 unsigned DstBitSize = DstEltVT.getSizeInBits(); 10084 10085 // If this is a conversion of N elements of one type to N elements of another 10086 // type, convert each element. This handles FP<->INT cases. 10087 if (SrcBitSize == DstBitSize) { 10088 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10089 BV->getValueType(0).getVectorNumElements()); 10090 10091 // Due to the FP element handling below calling this routine recursively, 10092 // we can end up with a scalar-to-vector node here. 10093 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 10094 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 10095 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 10096 10097 SmallVector<SDValue, 8> Ops; 10098 for (SDValue Op : BV->op_values()) { 10099 // If the vector element type is not legal, the BUILD_VECTOR operands 10100 // are promoted and implicitly truncated. Make that explicit here. 10101 if (Op.getValueType() != SrcEltVT) 10102 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 10103 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 10104 AddToWorklist(Ops.back().getNode()); 10105 } 10106 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 10107 } 10108 10109 // Otherwise, we're growing or shrinking the elements. To avoid having to 10110 // handle annoying details of growing/shrinking FP values, we convert them to 10111 // int first. 10112 if (SrcEltVT.isFloatingPoint()) { 10113 // Convert the input float vector to a int vector where the elements are the 10114 // same sizes. 10115 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 10116 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 10117 SrcEltVT = IntVT; 10118 } 10119 10120 // Now we know the input is an integer vector. If the output is a FP type, 10121 // convert to integer first, then to FP of the right size. 10122 if (DstEltVT.isFloatingPoint()) { 10123 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 10124 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 10125 10126 // Next, convert to FP elements of the same size. 10127 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 10128 } 10129 10130 SDLoc DL(BV); 10131 10132 // Okay, we know the src/dst types are both integers of differing types. 10133 // Handling growing first. 10134 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 10135 if (SrcBitSize < DstBitSize) { 10136 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 10137 10138 SmallVector<SDValue, 8> Ops; 10139 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 10140 i += NumInputsPerOutput) { 10141 bool isLE = DAG.getDataLayout().isLittleEndian(); 10142 APInt NewBits = APInt(DstBitSize, 0); 10143 bool EltIsUndef = true; 10144 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 10145 // Shift the previously computed bits over. 10146 NewBits <<= SrcBitSize; 10147 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 10148 if (Op.isUndef()) continue; 10149 EltIsUndef = false; 10150 10151 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 10152 zextOrTrunc(SrcBitSize).zext(DstBitSize); 10153 } 10154 10155 if (EltIsUndef) 10156 Ops.push_back(DAG.getUNDEF(DstEltVT)); 10157 else 10158 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 10159 } 10160 10161 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 10162 return DAG.getBuildVector(VT, DL, Ops); 10163 } 10164 10165 // Finally, this must be the case where we are shrinking elements: each input 10166 // turns into multiple outputs. 10167 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 10168 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10169 NumOutputsPerInput*BV->getNumOperands()); 10170 SmallVector<SDValue, 8> Ops; 10171 10172 for (const SDValue &Op : BV->op_values()) { 10173 if (Op.isUndef()) { 10174 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 10175 continue; 10176 } 10177 10178 APInt OpVal = cast<ConstantSDNode>(Op)-> 10179 getAPIntValue().zextOrTrunc(SrcBitSize); 10180 10181 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 10182 APInt ThisVal = OpVal.trunc(DstBitSize); 10183 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 10184 OpVal.lshrInPlace(DstBitSize); 10185 } 10186 10187 // For big endian targets, swap the order of the pieces of each element. 10188 if (DAG.getDataLayout().isBigEndian()) 10189 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 10190 } 10191 10192 return DAG.getBuildVector(VT, DL, Ops); 10193 } 10194 10195 static bool isContractable(SDNode *N) { 10196 SDNodeFlags F = N->getFlags(); 10197 return F.hasAllowContract() || F.hasAllowReassociation(); 10198 } 10199 10200 /// Try to perform FMA combining on a given FADD node. 10201 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 10202 SDValue N0 = N->getOperand(0); 10203 SDValue N1 = N->getOperand(1); 10204 EVT VT = N->getValueType(0); 10205 SDLoc SL(N); 10206 10207 const TargetOptions &Options = DAG.getTarget().Options; 10208 10209 // Floating-point multiply-add with intermediate rounding. 10210 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10211 10212 // Floating-point multiply-add without intermediate rounding. 10213 bool HasFMA = 10214 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10215 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10216 10217 // No valid opcode, do not combine. 10218 if (!HasFMAD && !HasFMA) 10219 return SDValue(); 10220 10221 SDNodeFlags Flags = N->getFlags(); 10222 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10223 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10224 CanFuse || HasFMAD); 10225 // If the addition is not contractable, do not combine. 10226 if (!AllowFusionGlobally && !isContractable(N)) 10227 return SDValue(); 10228 10229 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10230 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10231 return SDValue(); 10232 10233 // Always prefer FMAD to FMA for precision. 10234 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10235 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10236 10237 // Is the node an FMUL and contractable either due to global flags or 10238 // SDNodeFlags. 10239 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10240 if (N.getOpcode() != ISD::FMUL) 10241 return false; 10242 return AllowFusionGlobally || isContractable(N.getNode()); 10243 }; 10244 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 10245 // prefer to fold the multiply with fewer uses. 10246 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 10247 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 10248 std::swap(N0, N1); 10249 } 10250 10251 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 10252 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10253 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10254 N0.getOperand(0), N0.getOperand(1), N1, Flags); 10255 } 10256 10257 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 10258 // Note: Commutes FADD operands. 10259 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10260 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10261 N1.getOperand(0), N1.getOperand(1), N0, Flags); 10262 } 10263 10264 // Look through FP_EXTEND nodes to do more combining. 10265 10266 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 10267 if (N0.getOpcode() == ISD::FP_EXTEND) { 10268 SDValue N00 = N0.getOperand(0); 10269 if (isContractableFMUL(N00) && 10270 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10271 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10272 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10273 N00.getOperand(0)), 10274 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10275 N00.getOperand(1)), N1, Flags); 10276 } 10277 } 10278 10279 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 10280 // Note: Commutes FADD operands. 10281 if (N1.getOpcode() == ISD::FP_EXTEND) { 10282 SDValue N10 = N1.getOperand(0); 10283 if (isContractableFMUL(N10) && 10284 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10285 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10286 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10287 N10.getOperand(0)), 10288 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10289 N10.getOperand(1)), N0, Flags); 10290 } 10291 } 10292 10293 // More folding opportunities when target permits. 10294 if (Aggressive) { 10295 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 10296 if (CanFuse && 10297 N0.getOpcode() == PreferredFusedOpcode && 10298 N0.getOperand(2).getOpcode() == ISD::FMUL && 10299 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 10300 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10301 N0.getOperand(0), N0.getOperand(1), 10302 DAG.getNode(PreferredFusedOpcode, SL, VT, 10303 N0.getOperand(2).getOperand(0), 10304 N0.getOperand(2).getOperand(1), 10305 N1, Flags), Flags); 10306 } 10307 10308 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 10309 if (CanFuse && 10310 N1->getOpcode() == PreferredFusedOpcode && 10311 N1.getOperand(2).getOpcode() == ISD::FMUL && 10312 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 10313 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10314 N1.getOperand(0), N1.getOperand(1), 10315 DAG.getNode(PreferredFusedOpcode, SL, VT, 10316 N1.getOperand(2).getOperand(0), 10317 N1.getOperand(2).getOperand(1), 10318 N0, Flags), Flags); 10319 } 10320 10321 10322 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 10323 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 10324 auto FoldFAddFMAFPExtFMul = [&] ( 10325 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10326 SDNodeFlags Flags) { 10327 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 10328 DAG.getNode(PreferredFusedOpcode, SL, VT, 10329 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10330 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10331 Z, Flags), Flags); 10332 }; 10333 if (N0.getOpcode() == PreferredFusedOpcode) { 10334 SDValue N02 = N0.getOperand(2); 10335 if (N02.getOpcode() == ISD::FP_EXTEND) { 10336 SDValue N020 = N02.getOperand(0); 10337 if (isContractableFMUL(N020) && 10338 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10339 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 10340 N020.getOperand(0), N020.getOperand(1), 10341 N1, Flags); 10342 } 10343 } 10344 } 10345 10346 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 10347 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 10348 // FIXME: This turns two single-precision and one double-precision 10349 // operation into two double-precision operations, which might not be 10350 // interesting for all targets, especially GPUs. 10351 auto FoldFAddFPExtFMAFMul = [&] ( 10352 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10353 SDNodeFlags Flags) { 10354 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10355 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 10356 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 10357 DAG.getNode(PreferredFusedOpcode, SL, VT, 10358 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10359 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10360 Z, Flags), Flags); 10361 }; 10362 if (N0.getOpcode() == ISD::FP_EXTEND) { 10363 SDValue N00 = N0.getOperand(0); 10364 if (N00.getOpcode() == PreferredFusedOpcode) { 10365 SDValue N002 = N00.getOperand(2); 10366 if (isContractableFMUL(N002) && 10367 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10368 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 10369 N002.getOperand(0), N002.getOperand(1), 10370 N1, Flags); 10371 } 10372 } 10373 } 10374 10375 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 10376 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 10377 if (N1.getOpcode() == PreferredFusedOpcode) { 10378 SDValue N12 = N1.getOperand(2); 10379 if (N12.getOpcode() == ISD::FP_EXTEND) { 10380 SDValue N120 = N12.getOperand(0); 10381 if (isContractableFMUL(N120) && 10382 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10383 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 10384 N120.getOperand(0), N120.getOperand(1), 10385 N0, Flags); 10386 } 10387 } 10388 } 10389 10390 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 10391 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 10392 // FIXME: This turns two single-precision and one double-precision 10393 // operation into two double-precision operations, which might not be 10394 // interesting for all targets, especially GPUs. 10395 if (N1.getOpcode() == ISD::FP_EXTEND) { 10396 SDValue N10 = N1.getOperand(0); 10397 if (N10.getOpcode() == PreferredFusedOpcode) { 10398 SDValue N102 = N10.getOperand(2); 10399 if (isContractableFMUL(N102) && 10400 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10401 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 10402 N102.getOperand(0), N102.getOperand(1), 10403 N0, Flags); 10404 } 10405 } 10406 } 10407 } 10408 10409 return SDValue(); 10410 } 10411 10412 /// Try to perform FMA combining on a given FSUB node. 10413 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 10414 SDValue N0 = N->getOperand(0); 10415 SDValue N1 = N->getOperand(1); 10416 EVT VT = N->getValueType(0); 10417 SDLoc SL(N); 10418 10419 const TargetOptions &Options = DAG.getTarget().Options; 10420 // Floating-point multiply-add with intermediate rounding. 10421 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10422 10423 // Floating-point multiply-add without intermediate rounding. 10424 bool HasFMA = 10425 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10426 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10427 10428 // No valid opcode, do not combine. 10429 if (!HasFMAD && !HasFMA) 10430 return SDValue(); 10431 10432 const SDNodeFlags Flags = N->getFlags(); 10433 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10434 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10435 CanFuse || HasFMAD); 10436 10437 // If the subtraction is not contractable, do not combine. 10438 if (!AllowFusionGlobally && !isContractable(N)) 10439 return SDValue(); 10440 10441 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10442 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10443 return SDValue(); 10444 10445 // Always prefer FMAD to FMA for precision. 10446 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10447 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10448 10449 // Is the node an FMUL and contractable either due to global flags or 10450 // SDNodeFlags. 10451 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10452 if (N.getOpcode() != ISD::FMUL) 10453 return false; 10454 return AllowFusionGlobally || isContractable(N.getNode()); 10455 }; 10456 10457 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 10458 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10459 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10460 N0.getOperand(0), N0.getOperand(1), 10461 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10462 } 10463 10464 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 10465 // Note: Commutes FSUB operands. 10466 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10467 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10468 DAG.getNode(ISD::FNEG, SL, VT, 10469 N1.getOperand(0)), 10470 N1.getOperand(1), N0, Flags); 10471 } 10472 10473 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 10474 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 10475 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 10476 SDValue N00 = N0.getOperand(0).getOperand(0); 10477 SDValue N01 = N0.getOperand(0).getOperand(1); 10478 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10479 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 10480 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10481 } 10482 10483 // Look through FP_EXTEND nodes to do more combining. 10484 10485 // fold (fsub (fpext (fmul x, y)), z) 10486 // -> (fma (fpext x), (fpext y), (fneg z)) 10487 if (N0.getOpcode() == ISD::FP_EXTEND) { 10488 SDValue N00 = N0.getOperand(0); 10489 if (isContractableFMUL(N00) && 10490 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10491 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10492 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10493 N00.getOperand(0)), 10494 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10495 N00.getOperand(1)), 10496 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10497 } 10498 } 10499 10500 // fold (fsub x, (fpext (fmul y, z))) 10501 // -> (fma (fneg (fpext y)), (fpext z), x) 10502 // Note: Commutes FSUB operands. 10503 if (N1.getOpcode() == ISD::FP_EXTEND) { 10504 SDValue N10 = N1.getOperand(0); 10505 if (isContractableFMUL(N10) && 10506 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10507 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10508 DAG.getNode(ISD::FNEG, SL, VT, 10509 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10510 N10.getOperand(0))), 10511 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10512 N10.getOperand(1)), 10513 N0, Flags); 10514 } 10515 } 10516 10517 // fold (fsub (fpext (fneg (fmul, x, y))), z) 10518 // -> (fneg (fma (fpext x), (fpext y), z)) 10519 // Note: This could be removed with appropriate canonicalization of the 10520 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10521 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10522 // from implementing the canonicalization in visitFSUB. 10523 if (N0.getOpcode() == ISD::FP_EXTEND) { 10524 SDValue N00 = N0.getOperand(0); 10525 if (N00.getOpcode() == ISD::FNEG) { 10526 SDValue N000 = N00.getOperand(0); 10527 if (isContractableFMUL(N000) && 10528 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10529 return DAG.getNode(ISD::FNEG, SL, VT, 10530 DAG.getNode(PreferredFusedOpcode, SL, VT, 10531 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10532 N000.getOperand(0)), 10533 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10534 N000.getOperand(1)), 10535 N1, Flags)); 10536 } 10537 } 10538 } 10539 10540 // fold (fsub (fneg (fpext (fmul, x, y))), z) 10541 // -> (fneg (fma (fpext x)), (fpext y), z) 10542 // Note: This could be removed with appropriate canonicalization of the 10543 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10544 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10545 // from implementing the canonicalization in visitFSUB. 10546 if (N0.getOpcode() == ISD::FNEG) { 10547 SDValue N00 = N0.getOperand(0); 10548 if (N00.getOpcode() == ISD::FP_EXTEND) { 10549 SDValue N000 = N00.getOperand(0); 10550 if (isContractableFMUL(N000) && 10551 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 10552 return DAG.getNode(ISD::FNEG, SL, VT, 10553 DAG.getNode(PreferredFusedOpcode, SL, VT, 10554 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10555 N000.getOperand(0)), 10556 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10557 N000.getOperand(1)), 10558 N1, Flags)); 10559 } 10560 } 10561 } 10562 10563 // More folding opportunities when target permits. 10564 if (Aggressive) { 10565 // fold (fsub (fma x, y, (fmul u, v)), z) 10566 // -> (fma x, y (fma u, v, (fneg z))) 10567 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && 10568 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 10569 N0.getOperand(2)->hasOneUse()) { 10570 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10571 N0.getOperand(0), N0.getOperand(1), 10572 DAG.getNode(PreferredFusedOpcode, SL, VT, 10573 N0.getOperand(2).getOperand(0), 10574 N0.getOperand(2).getOperand(1), 10575 DAG.getNode(ISD::FNEG, SL, VT, 10576 N1), Flags), Flags); 10577 } 10578 10579 // fold (fsub x, (fma y, z, (fmul u, v))) 10580 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 10581 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && 10582 isContractableFMUL(N1.getOperand(2))) { 10583 SDValue N20 = N1.getOperand(2).getOperand(0); 10584 SDValue N21 = N1.getOperand(2).getOperand(1); 10585 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10586 DAG.getNode(ISD::FNEG, SL, VT, 10587 N1.getOperand(0)), 10588 N1.getOperand(1), 10589 DAG.getNode(PreferredFusedOpcode, SL, VT, 10590 DAG.getNode(ISD::FNEG, SL, VT, N20), 10591 N21, N0, Flags), Flags); 10592 } 10593 10594 10595 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 10596 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 10597 if (N0.getOpcode() == PreferredFusedOpcode) { 10598 SDValue N02 = N0.getOperand(2); 10599 if (N02.getOpcode() == ISD::FP_EXTEND) { 10600 SDValue N020 = N02.getOperand(0); 10601 if (isContractableFMUL(N020) && 10602 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10603 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10604 N0.getOperand(0), N0.getOperand(1), 10605 DAG.getNode(PreferredFusedOpcode, SL, VT, 10606 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10607 N020.getOperand(0)), 10608 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10609 N020.getOperand(1)), 10610 DAG.getNode(ISD::FNEG, SL, VT, 10611 N1), Flags), Flags); 10612 } 10613 } 10614 } 10615 10616 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 10617 // -> (fma (fpext x), (fpext y), 10618 // (fma (fpext u), (fpext v), (fneg z))) 10619 // FIXME: This turns two single-precision and one double-precision 10620 // operation into two double-precision operations, which might not be 10621 // interesting for all targets, especially GPUs. 10622 if (N0.getOpcode() == ISD::FP_EXTEND) { 10623 SDValue N00 = N0.getOperand(0); 10624 if (N00.getOpcode() == PreferredFusedOpcode) { 10625 SDValue N002 = N00.getOperand(2); 10626 if (isContractableFMUL(N002) && 10627 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10628 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10629 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10630 N00.getOperand(0)), 10631 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10632 N00.getOperand(1)), 10633 DAG.getNode(PreferredFusedOpcode, SL, VT, 10634 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10635 N002.getOperand(0)), 10636 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10637 N002.getOperand(1)), 10638 DAG.getNode(ISD::FNEG, SL, VT, 10639 N1), Flags), Flags); 10640 } 10641 } 10642 } 10643 10644 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 10645 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 10646 if (N1.getOpcode() == PreferredFusedOpcode && 10647 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 10648 SDValue N120 = N1.getOperand(2).getOperand(0); 10649 if (isContractableFMUL(N120) && 10650 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10651 SDValue N1200 = N120.getOperand(0); 10652 SDValue N1201 = N120.getOperand(1); 10653 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10654 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 10655 N1.getOperand(1), 10656 DAG.getNode(PreferredFusedOpcode, SL, VT, 10657 DAG.getNode(ISD::FNEG, SL, VT, 10658 DAG.getNode(ISD::FP_EXTEND, SL, 10659 VT, N1200)), 10660 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10661 N1201), 10662 N0, Flags), Flags); 10663 } 10664 } 10665 10666 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 10667 // -> (fma (fneg (fpext y)), (fpext z), 10668 // (fma (fneg (fpext u)), (fpext v), x)) 10669 // FIXME: This turns two single-precision and one double-precision 10670 // operation into two double-precision operations, which might not be 10671 // interesting for all targets, especially GPUs. 10672 if (N1.getOpcode() == ISD::FP_EXTEND && 10673 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 10674 SDValue CvtSrc = N1.getOperand(0); 10675 SDValue N100 = CvtSrc.getOperand(0); 10676 SDValue N101 = CvtSrc.getOperand(1); 10677 SDValue N102 = CvtSrc.getOperand(2); 10678 if (isContractableFMUL(N102) && 10679 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 10680 SDValue N1020 = N102.getOperand(0); 10681 SDValue N1021 = N102.getOperand(1); 10682 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10683 DAG.getNode(ISD::FNEG, SL, VT, 10684 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10685 N100)), 10686 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 10687 DAG.getNode(PreferredFusedOpcode, SL, VT, 10688 DAG.getNode(ISD::FNEG, SL, VT, 10689 DAG.getNode(ISD::FP_EXTEND, SL, 10690 VT, N1020)), 10691 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10692 N1021), 10693 N0, Flags), Flags); 10694 } 10695 } 10696 } 10697 10698 return SDValue(); 10699 } 10700 10701 /// Try to perform FMA combining on a given FMUL node based on the distributive 10702 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 10703 /// subtraction instead of addition). 10704 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 10705 SDValue N0 = N->getOperand(0); 10706 SDValue N1 = N->getOperand(1); 10707 EVT VT = N->getValueType(0); 10708 SDLoc SL(N); 10709 const SDNodeFlags Flags = N->getFlags(); 10710 10711 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 10712 10713 const TargetOptions &Options = DAG.getTarget().Options; 10714 10715 // The transforms below are incorrect when x == 0 and y == inf, because the 10716 // intermediate multiplication produces a nan. 10717 if (!Options.NoInfsFPMath) 10718 return SDValue(); 10719 10720 // Floating-point multiply-add without intermediate rounding. 10721 bool HasFMA = 10722 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 10723 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10724 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10725 10726 // Floating-point multiply-add with intermediate rounding. This can result 10727 // in a less precise result due to the changed rounding order. 10728 bool HasFMAD = Options.UnsafeFPMath && 10729 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10730 10731 // No valid opcode, do not combine. 10732 if (!HasFMAD && !HasFMA) 10733 return SDValue(); 10734 10735 // Always prefer FMAD to FMA for precision. 10736 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10737 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10738 10739 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 10740 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 10741 auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10742 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 10743 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 10744 if (XC1 && XC1->isExactlyValue(+1.0)) 10745 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10746 Y, Flags); 10747 if (XC1 && XC1->isExactlyValue(-1.0)) 10748 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10749 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10750 } 10751 return SDValue(); 10752 }; 10753 10754 if (SDValue FMA = FuseFADD(N0, N1, Flags)) 10755 return FMA; 10756 if (SDValue FMA = FuseFADD(N1, N0, Flags)) 10757 return FMA; 10758 10759 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 10760 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 10761 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 10762 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 10763 auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10764 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 10765 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 10766 if (XC0 && XC0->isExactlyValue(+1.0)) 10767 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10768 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10769 Y, Flags); 10770 if (XC0 && XC0->isExactlyValue(-1.0)) 10771 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10772 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10773 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10774 10775 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 10776 if (XC1 && XC1->isExactlyValue(+1.0)) 10777 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10778 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10779 if (XC1 && XC1->isExactlyValue(-1.0)) 10780 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10781 Y, Flags); 10782 } 10783 return SDValue(); 10784 }; 10785 10786 if (SDValue FMA = FuseFSUB(N0, N1, Flags)) 10787 return FMA; 10788 if (SDValue FMA = FuseFSUB(N1, N0, Flags)) 10789 return FMA; 10790 10791 return SDValue(); 10792 } 10793 10794 static bool isFMulNegTwo(SDValue &N) { 10795 if (N.getOpcode() != ISD::FMUL) 10796 return false; 10797 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 10798 return CFP->isExactlyValue(-2.0); 10799 return false; 10800 } 10801 10802 SDValue DAGCombiner::visitFADD(SDNode *N) { 10803 SDValue N0 = N->getOperand(0); 10804 SDValue N1 = N->getOperand(1); 10805 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 10806 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 10807 EVT VT = N->getValueType(0); 10808 SDLoc DL(N); 10809 const TargetOptions &Options = DAG.getTarget().Options; 10810 const SDNodeFlags Flags = N->getFlags(); 10811 10812 // fold vector ops 10813 if (VT.isVector()) 10814 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10815 return FoldedVOp; 10816 10817 // fold (fadd c1, c2) -> c1 + c2 10818 if (N0CFP && N1CFP) 10819 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 10820 10821 // canonicalize constant to RHS 10822 if (N0CFP && !N1CFP) 10823 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 10824 10825 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) 10826 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1); 10827 if (N1C && N1C->isZero()) 10828 if (N1C->isNegative() || Options.UnsafeFPMath || Flags.hasNoSignedZeros()) 10829 return N0; 10830 10831 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10832 return NewSel; 10833 10834 // fold (fadd A, (fneg B)) -> (fsub A, B) 10835 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10836 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 10837 return DAG.getNode(ISD::FSUB, DL, VT, N0, 10838 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10839 10840 // fold (fadd (fneg A), B) -> (fsub B, A) 10841 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10842 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 10843 return DAG.getNode(ISD::FSUB, DL, VT, N1, 10844 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 10845 10846 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 10847 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 10848 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 10849 (isFMulNegTwo(N1) && N1.hasOneUse())) { 10850 bool N1IsFMul = isFMulNegTwo(N1); 10851 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 10852 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 10853 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 10854 } 10855 10856 // No FP constant should be created after legalization as Instruction 10857 // Selection pass has a hard time dealing with FP constants. 10858 bool AllowNewConst = (Level < AfterLegalizeDAG); 10859 10860 // If 'unsafe math' or nnan is enabled, fold lots of things. 10861 if ((Options.UnsafeFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 10862 // If allowed, fold (fadd (fneg x), x) -> 0.0 10863 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 10864 return DAG.getConstantFP(0.0, DL, VT); 10865 10866 // If allowed, fold (fadd x, (fneg x)) -> 0.0 10867 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 10868 return DAG.getConstantFP(0.0, DL, VT); 10869 } 10870 10871 // If 'unsafe math' or reassoc and nsz, fold lots of things. 10872 // TODO: break out portions of the transformations below for which Unsafe is 10873 // considered and which do not require both nsz and reassoc 10874 if ((Options.UnsafeFPMath || 10875 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 10876 AllowNewConst) { 10877 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 10878 if (N1CFP && N0.getOpcode() == ISD::FADD && 10879 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10880 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags); 10881 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags); 10882 } 10883 10884 // We can fold chains of FADD's of the same value into multiplications. 10885 // This transform is not safe in general because we are reducing the number 10886 // of rounding steps. 10887 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 10888 if (N0.getOpcode() == ISD::FMUL) { 10889 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10890 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 10891 10892 // (fadd (fmul x, c), x) -> (fmul x, c+1) 10893 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 10894 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10895 DAG.getConstantFP(1.0, DL, VT), Flags); 10896 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 10897 } 10898 10899 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 10900 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 10901 N1.getOperand(0) == N1.getOperand(1) && 10902 N0.getOperand(0) == N1.getOperand(0)) { 10903 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10904 DAG.getConstantFP(2.0, DL, VT), Flags); 10905 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 10906 } 10907 } 10908 10909 if (N1.getOpcode() == ISD::FMUL) { 10910 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10911 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 10912 10913 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 10914 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 10915 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10916 DAG.getConstantFP(1.0, DL, VT), Flags); 10917 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 10918 } 10919 10920 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 10921 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 10922 N0.getOperand(0) == N0.getOperand(1) && 10923 N1.getOperand(0) == N0.getOperand(0)) { 10924 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10925 DAG.getConstantFP(2.0, DL, VT), Flags); 10926 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 10927 } 10928 } 10929 10930 if (N0.getOpcode() == ISD::FADD) { 10931 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10932 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 10933 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 10934 (N0.getOperand(0) == N1)) { 10935 return DAG.getNode(ISD::FMUL, DL, VT, 10936 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 10937 } 10938 } 10939 10940 if (N1.getOpcode() == ISD::FADD) { 10941 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10942 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 10943 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 10944 N1.getOperand(0) == N0) { 10945 return DAG.getNode(ISD::FMUL, DL, VT, 10946 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 10947 } 10948 } 10949 10950 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 10951 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 10952 N0.getOperand(0) == N0.getOperand(1) && 10953 N1.getOperand(0) == N1.getOperand(1) && 10954 N0.getOperand(0) == N1.getOperand(0)) { 10955 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 10956 DAG.getConstantFP(4.0, DL, VT), Flags); 10957 } 10958 } 10959 } // enable-unsafe-fp-math 10960 10961 // FADD -> FMA combines: 10962 if (SDValue Fused = visitFADDForFMACombine(N)) { 10963 AddToWorklist(Fused.getNode()); 10964 return Fused; 10965 } 10966 return SDValue(); 10967 } 10968 10969 SDValue DAGCombiner::visitFSUB(SDNode *N) { 10970 SDValue N0 = N->getOperand(0); 10971 SDValue N1 = N->getOperand(1); 10972 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10973 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10974 EVT VT = N->getValueType(0); 10975 SDLoc DL(N); 10976 const TargetOptions &Options = DAG.getTarget().Options; 10977 const SDNodeFlags Flags = N->getFlags(); 10978 10979 // fold vector ops 10980 if (VT.isVector()) 10981 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10982 return FoldedVOp; 10983 10984 // fold (fsub c1, c2) -> c1-c2 10985 if (N0CFP && N1CFP) 10986 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 10987 10988 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10989 return NewSel; 10990 10991 // (fsub A, 0) -> A 10992 if (N1CFP && N1CFP->isZero()) { 10993 if (!N1CFP->isNegative() || Options.UnsafeFPMath || 10994 Flags.hasNoSignedZeros()) { 10995 return N0; 10996 } 10997 } 10998 10999 if (N0 == N1) { 11000 // (fsub x, x) -> 0.0 11001 if (Options.UnsafeFPMath || Flags.hasNoNaNs()) 11002 return DAG.getConstantFP(0.0f, DL, VT); 11003 } 11004 11005 // (fsub 0, B) -> -B 11006 if (N0CFP && N0CFP->isZero()) { 11007 if (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) { 11008 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 11009 return GetNegatedExpression(N1, DAG, LegalOperations); 11010 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11011 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 11012 } 11013 } 11014 11015 if ((Options.UnsafeFPMath || 11016 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) 11017 && N1.getOpcode() == ISD::FADD) { 11018 // X - (X + Y) -> -Y 11019 if (N0 == N1->getOperand(0)) 11020 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1), Flags); 11021 // X - (Y + X) -> -Y 11022 if (N0 == N1->getOperand(1)) 11023 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0), Flags); 11024 } 11025 11026 // fold (fsub A, (fneg B)) -> (fadd A, B) 11027 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 11028 return DAG.getNode(ISD::FADD, DL, VT, N0, 11029 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 11030 11031 // FSUB -> FMA combines: 11032 if (SDValue Fused = visitFSUBForFMACombine(N)) { 11033 AddToWorklist(Fused.getNode()); 11034 return Fused; 11035 } 11036 11037 return SDValue(); 11038 } 11039 11040 SDValue DAGCombiner::visitFMUL(SDNode *N) { 11041 SDValue N0 = N->getOperand(0); 11042 SDValue N1 = N->getOperand(1); 11043 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11044 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11045 EVT VT = N->getValueType(0); 11046 SDLoc DL(N); 11047 const TargetOptions &Options = DAG.getTarget().Options; 11048 const SDNodeFlags Flags = N->getFlags(); 11049 11050 // fold vector ops 11051 if (VT.isVector()) { 11052 // This just handles C1 * C2 for vectors. Other vector folds are below. 11053 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11054 return FoldedVOp; 11055 } 11056 11057 // fold (fmul c1, c2) -> c1*c2 11058 if (N0CFP && N1CFP) 11059 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 11060 11061 // canonicalize constant to RHS 11062 if (isConstantFPBuildVectorOrConstantFP(N0) && 11063 !isConstantFPBuildVectorOrConstantFP(N1)) 11064 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 11065 11066 // fold (fmul A, 1.0) -> A 11067 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11068 return N0; 11069 11070 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11071 return NewSel; 11072 11073 if (Options.UnsafeFPMath || 11074 (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) { 11075 // fold (fmul A, 0) -> 0 11076 if (N1CFP && N1CFP->isZero()) 11077 return N1; 11078 } 11079 11080 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 11081 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 11082 if (N0.getOpcode() == ISD::FMUL) { 11083 // Fold scalars or any vector constants (not just splats). 11084 // This fold is done in general by InstCombine, but extra fmul insts 11085 // may have been generated during lowering. 11086 SDValue N00 = N0.getOperand(0); 11087 SDValue N01 = N0.getOperand(1); 11088 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 11089 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 11090 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 11091 11092 // Check 1: Make sure that the first operand of the inner multiply is NOT 11093 // a constant. Otherwise, we may induce infinite looping. 11094 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 11095 // Check 2: Make sure that the second operand of the inner multiply and 11096 // the second operand of the outer multiply are constants. 11097 if ((N1CFP && isConstOrConstSplatFP(N01)) || 11098 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 11099 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 11100 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 11101 } 11102 } 11103 } 11104 11105 // Match a special-case: we convert X * 2.0 into fadd. 11106 // fmul (fadd X, X), C -> fmul X, 2.0 * C 11107 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 11108 N0.getOperand(0) == N0.getOperand(1)) { 11109 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 11110 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 11111 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 11112 } 11113 } 11114 11115 // fold (fmul X, 2.0) -> (fadd X, X) 11116 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 11117 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 11118 11119 // fold (fmul X, -1.0) -> (fneg X) 11120 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 11121 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11122 return DAG.getNode(ISD::FNEG, DL, VT, N0); 11123 11124 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 11125 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11126 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11127 // Both can be negated for free, check to see if at least one is cheaper 11128 // negated. 11129 if (LHSNeg == 2 || RHSNeg == 2) 11130 return DAG.getNode(ISD::FMUL, DL, VT, 11131 GetNegatedExpression(N0, DAG, LegalOperations), 11132 GetNegatedExpression(N1, DAG, LegalOperations), 11133 Flags); 11134 } 11135 } 11136 11137 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 11138 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 11139 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 11140 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 11141 TLI.isOperationLegal(ISD::FABS, VT)) { 11142 SDValue Select = N0, X = N1; 11143 if (Select.getOpcode() != ISD::SELECT) 11144 std::swap(Select, X); 11145 11146 SDValue Cond = Select.getOperand(0); 11147 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 11148 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 11149 11150 if (TrueOpnd && FalseOpnd && 11151 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 11152 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 11153 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 11154 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 11155 switch (CC) { 11156 default: break; 11157 case ISD::SETOLT: 11158 case ISD::SETULT: 11159 case ISD::SETOLE: 11160 case ISD::SETULE: 11161 case ISD::SETLT: 11162 case ISD::SETLE: 11163 std::swap(TrueOpnd, FalseOpnd); 11164 LLVM_FALLTHROUGH; 11165 case ISD::SETOGT: 11166 case ISD::SETUGT: 11167 case ISD::SETOGE: 11168 case ISD::SETUGE: 11169 case ISD::SETGT: 11170 case ISD::SETGE: 11171 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 11172 TLI.isOperationLegal(ISD::FNEG, VT)) 11173 return DAG.getNode(ISD::FNEG, DL, VT, 11174 DAG.getNode(ISD::FABS, DL, VT, X)); 11175 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 11176 return DAG.getNode(ISD::FABS, DL, VT, X); 11177 11178 break; 11179 } 11180 } 11181 } 11182 11183 // FMUL -> FMA combines: 11184 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 11185 AddToWorklist(Fused.getNode()); 11186 return Fused; 11187 } 11188 11189 return SDValue(); 11190 } 11191 11192 SDValue DAGCombiner::visitFMA(SDNode *N) { 11193 SDValue N0 = N->getOperand(0); 11194 SDValue N1 = N->getOperand(1); 11195 SDValue N2 = N->getOperand(2); 11196 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11197 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11198 EVT VT = N->getValueType(0); 11199 SDLoc DL(N); 11200 const TargetOptions &Options = DAG.getTarget().Options; 11201 11202 // FMA nodes have flags that propagate to the created nodes. 11203 const SDNodeFlags Flags = N->getFlags(); 11204 bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N); 11205 11206 // Constant fold FMA. 11207 if (isa<ConstantFPSDNode>(N0) && 11208 isa<ConstantFPSDNode>(N1) && 11209 isa<ConstantFPSDNode>(N2)) { 11210 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 11211 } 11212 11213 if (UnsafeFPMath) { 11214 if (N0CFP && N0CFP->isZero()) 11215 return N2; 11216 if (N1CFP && N1CFP->isZero()) 11217 return N2; 11218 } 11219 // TODO: The FMA node should have flags that propagate to these nodes. 11220 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11221 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 11222 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11223 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 11224 11225 // Canonicalize (fma c, x, y) -> (fma x, c, y) 11226 if (isConstantFPBuildVectorOrConstantFP(N0) && 11227 !isConstantFPBuildVectorOrConstantFP(N1)) 11228 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 11229 11230 if (UnsafeFPMath) { 11231 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 11232 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 11233 isConstantFPBuildVectorOrConstantFP(N1) && 11234 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 11235 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11236 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 11237 Flags), Flags); 11238 } 11239 11240 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 11241 if (N0.getOpcode() == ISD::FMUL && 11242 isConstantFPBuildVectorOrConstantFP(N1) && 11243 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 11244 return DAG.getNode(ISD::FMA, DL, VT, 11245 N0.getOperand(0), 11246 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 11247 Flags), 11248 N2); 11249 } 11250 } 11251 11252 // (fma x, 1, y) -> (fadd x, y) 11253 // (fma x, -1, y) -> (fadd (fneg x), y) 11254 if (N1CFP) { 11255 if (N1CFP->isExactlyValue(1.0)) 11256 // TODO: The FMA node should have flags that propagate to this node. 11257 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 11258 11259 if (N1CFP->isExactlyValue(-1.0) && 11260 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 11261 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 11262 AddToWorklist(RHSNeg.getNode()); 11263 // TODO: The FMA node should have flags that propagate to this node. 11264 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 11265 } 11266 11267 // fma (fneg x), K, y -> fma x -K, y 11268 if (N0.getOpcode() == ISD::FNEG && 11269 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 11270 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 11271 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 11272 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 11273 } 11274 } 11275 11276 if (UnsafeFPMath) { 11277 // (fma x, c, x) -> (fmul x, (c+1)) 11278 if (N1CFP && N0 == N2) { 11279 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11280 DAG.getNode(ISD::FADD, DL, VT, N1, 11281 DAG.getConstantFP(1.0, DL, VT), Flags), 11282 Flags); 11283 } 11284 11285 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 11286 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 11287 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11288 DAG.getNode(ISD::FADD, DL, VT, N1, 11289 DAG.getConstantFP(-1.0, DL, VT), Flags), 11290 Flags); 11291 } 11292 } 11293 11294 return SDValue(); 11295 } 11296 11297 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11298 // reciprocal. 11299 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 11300 // Notice that this is not always beneficial. One reason is different targets 11301 // may have different costs for FDIV and FMUL, so sometimes the cost of two 11302 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 11303 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 11304 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 11305 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 11306 const SDNodeFlags Flags = N->getFlags(); 11307 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 11308 return SDValue(); 11309 11310 // Skip if current node is a reciprocal. 11311 SDValue N0 = N->getOperand(0); 11312 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11313 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11314 return SDValue(); 11315 11316 // Exit early if the target does not want this transform or if there can't 11317 // possibly be enough uses of the divisor to make the transform worthwhile. 11318 SDValue N1 = N->getOperand(1); 11319 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 11320 if (!MinUses || N1->use_size() < MinUses) 11321 return SDValue(); 11322 11323 // Find all FDIV users of the same divisor. 11324 // Use a set because duplicates may be present in the user list. 11325 SetVector<SDNode *> Users; 11326 for (auto *U : N1->uses()) { 11327 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 11328 // This division is eligible for optimization only if global unsafe math 11329 // is enabled or if this division allows reciprocal formation. 11330 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 11331 Users.insert(U); 11332 } 11333 } 11334 11335 // Now that we have the actual number of divisor uses, make sure it meets 11336 // the minimum threshold specified by the target. 11337 if (Users.size() < MinUses) 11338 return SDValue(); 11339 11340 EVT VT = N->getValueType(0); 11341 SDLoc DL(N); 11342 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 11343 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 11344 11345 // Dividend / Divisor -> Dividend * Reciprocal 11346 for (auto *U : Users) { 11347 SDValue Dividend = U->getOperand(0); 11348 if (Dividend != FPOne) { 11349 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 11350 Reciprocal, Flags); 11351 CombineTo(U, NewNode); 11352 } else if (U != Reciprocal.getNode()) { 11353 // In the absence of fast-math-flags, this user node is always the 11354 // same node as Reciprocal, but with FMF they may be different nodes. 11355 CombineTo(U, Reciprocal); 11356 } 11357 } 11358 return SDValue(N, 0); // N was replaced. 11359 } 11360 11361 SDValue DAGCombiner::visitFDIV(SDNode *N) { 11362 SDValue N0 = N->getOperand(0); 11363 SDValue N1 = N->getOperand(1); 11364 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11365 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11366 EVT VT = N->getValueType(0); 11367 SDLoc DL(N); 11368 const TargetOptions &Options = DAG.getTarget().Options; 11369 SDNodeFlags Flags = N->getFlags(); 11370 11371 // fold vector ops 11372 if (VT.isVector()) 11373 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11374 return FoldedVOp; 11375 11376 // fold (fdiv c1, c2) -> c1/c2 11377 if (N0CFP && N1CFP) 11378 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 11379 11380 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11381 return NewSel; 11382 11383 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 11384 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 11385 if (N1CFP) { 11386 // Compute the reciprocal 1.0 / c2. 11387 const APFloat &N1APF = N1CFP->getValueAPF(); 11388 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 11389 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 11390 // Only do the transform if the reciprocal is a legal fp immediate that 11391 // isn't too nasty (eg NaN, denormal, ...). 11392 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 11393 (!LegalOperations || 11394 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 11395 // backend)... we should handle this gracefully after Legalize. 11396 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 11397 TLI.isOperationLegal(ISD::ConstantFP, VT) || 11398 TLI.isFPImmLegal(Recip, VT))) 11399 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11400 DAG.getConstantFP(Recip, DL, VT), Flags); 11401 } 11402 11403 // If this FDIV is part of a reciprocal square root, it may be folded 11404 // into a target-specific square root estimate instruction. 11405 if (N1.getOpcode() == ISD::FSQRT) { 11406 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 11407 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11408 } 11409 } else if (N1.getOpcode() == ISD::FP_EXTEND && 11410 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11411 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11412 Flags)) { 11413 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 11414 AddToWorklist(RV.getNode()); 11415 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11416 } 11417 } else if (N1.getOpcode() == ISD::FP_ROUND && 11418 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11419 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11420 Flags)) { 11421 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 11422 AddToWorklist(RV.getNode()); 11423 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11424 } 11425 } else if (N1.getOpcode() == ISD::FMUL) { 11426 // Look through an FMUL. Even though this won't remove the FDIV directly, 11427 // it's still worthwhile to get rid of the FSQRT if possible. 11428 SDValue SqrtOp; 11429 SDValue OtherOp; 11430 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11431 SqrtOp = N1.getOperand(0); 11432 OtherOp = N1.getOperand(1); 11433 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 11434 SqrtOp = N1.getOperand(1); 11435 OtherOp = N1.getOperand(0); 11436 } 11437 if (SqrtOp.getNode()) { 11438 // We found a FSQRT, so try to make this fold: 11439 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 11440 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 11441 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 11442 AddToWorklist(RV.getNode()); 11443 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11444 } 11445 } 11446 } 11447 11448 // Fold into a reciprocal estimate and multiply instead of a real divide. 11449 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 11450 AddToWorklist(RV.getNode()); 11451 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11452 } 11453 } 11454 11455 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 11456 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11457 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11458 // Both can be negated for free, check to see if at least one is cheaper 11459 // negated. 11460 if (LHSNeg == 2 || RHSNeg == 2) 11461 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 11462 GetNegatedExpression(N0, DAG, LegalOperations), 11463 GetNegatedExpression(N1, DAG, LegalOperations), 11464 Flags); 11465 } 11466 } 11467 11468 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 11469 return CombineRepeatedDivisors; 11470 11471 return SDValue(); 11472 } 11473 11474 SDValue DAGCombiner::visitFREM(SDNode *N) { 11475 SDValue N0 = N->getOperand(0); 11476 SDValue N1 = N->getOperand(1); 11477 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11478 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11479 EVT VT = N->getValueType(0); 11480 11481 // fold (frem c1, c2) -> fmod(c1,c2) 11482 if (N0CFP && N1CFP) 11483 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 11484 11485 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11486 return NewSel; 11487 11488 return SDValue(); 11489 } 11490 11491 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 11492 SDNodeFlags Flags = N->getFlags(); 11493 if (!DAG.getTarget().Options.UnsafeFPMath && 11494 !Flags.hasApproximateFuncs()) 11495 return SDValue(); 11496 11497 SDValue N0 = N->getOperand(0); 11498 if (TLI.isFsqrtCheap(N0, DAG)) 11499 return SDValue(); 11500 11501 // FSQRT nodes have flags that propagate to the created nodes. 11502 return buildSqrtEstimate(N0, Flags); 11503 } 11504 11505 /// copysign(x, fp_extend(y)) -> copysign(x, y) 11506 /// copysign(x, fp_round(y)) -> copysign(x, y) 11507 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 11508 SDValue N1 = N->getOperand(1); 11509 if ((N1.getOpcode() == ISD::FP_EXTEND || 11510 N1.getOpcode() == ISD::FP_ROUND)) { 11511 // Do not optimize out type conversion of f128 type yet. 11512 // For some targets like x86_64, configuration is changed to keep one f128 11513 // value in one SSE register, but instruction selection cannot handle 11514 // FCOPYSIGN on SSE registers yet. 11515 EVT N1VT = N1->getValueType(0); 11516 EVT N1Op0VT = N1->getOperand(0).getValueType(); 11517 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 11518 } 11519 return false; 11520 } 11521 11522 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 11523 SDValue N0 = N->getOperand(0); 11524 SDValue N1 = N->getOperand(1); 11525 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11526 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11527 EVT VT = N->getValueType(0); 11528 11529 if (N0CFP && N1CFP) // Constant fold 11530 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 11531 11532 if (N1CFP) { 11533 const APFloat &V = N1CFP->getValueAPF(); 11534 // copysign(x, c1) -> fabs(x) iff ispos(c1) 11535 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 11536 if (!V.isNegative()) { 11537 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 11538 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11539 } else { 11540 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11541 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 11542 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 11543 } 11544 } 11545 11546 // copysign(fabs(x), y) -> copysign(x, y) 11547 // copysign(fneg(x), y) -> copysign(x, y) 11548 // copysign(copysign(x,z), y) -> copysign(x, y) 11549 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 11550 N0.getOpcode() == ISD::FCOPYSIGN) 11551 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 11552 11553 // copysign(x, abs(y)) -> abs(x) 11554 if (N1.getOpcode() == ISD::FABS) 11555 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11556 11557 // copysign(x, copysign(y,z)) -> copysign(x, z) 11558 if (N1.getOpcode() == ISD::FCOPYSIGN) 11559 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 11560 11561 // copysign(x, fp_extend(y)) -> copysign(x, y) 11562 // copysign(x, fp_round(y)) -> copysign(x, y) 11563 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 11564 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 11565 11566 return SDValue(); 11567 } 11568 11569 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 11570 const TargetLowering &TLI) { 11571 // This optimization is guarded by a function attribute because it may produce 11572 // unexpected results. Ie, programs may be relying on the platform-specific 11573 // undefined behavior when the float-to-int conversion overflows. 11574 const Function &F = DAG.getMachineFunction().getFunction(); 11575 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 11576 if (StrictOverflow.getValueAsString().equals("false")) 11577 return SDValue(); 11578 11579 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 11580 // replacing casts with a libcall. We also must be allowed to ignore -0.0 11581 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 11582 // conversions would return +0.0. 11583 // FIXME: We should be able to use node-level FMF here. 11584 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 11585 EVT VT = N->getValueType(0); 11586 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 11587 !DAG.getTarget().Options.NoSignedZerosFPMath) 11588 return SDValue(); 11589 11590 // fptosi/fptoui round towards zero, so converting from FP to integer and 11591 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 11592 SDValue N0 = N->getOperand(0); 11593 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 11594 N0.getOperand(0).getValueType() == VT) 11595 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11596 11597 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 11598 N0.getOperand(0).getValueType() == VT) 11599 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11600 11601 return SDValue(); 11602 } 11603 11604 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 11605 SDValue N0 = N->getOperand(0); 11606 EVT VT = N->getValueType(0); 11607 EVT OpVT = N0.getValueType(); 11608 11609 // fold (sint_to_fp c1) -> c1fp 11610 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11611 // ...but only if the target supports immediate floating-point values 11612 (!LegalOperations || 11613 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11614 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11615 11616 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 11617 // but UINT_TO_FP is legal on this target, try to convert. 11618 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 11619 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 11620 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 11621 if (DAG.SignBitIsZero(N0)) 11622 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11623 } 11624 11625 // The next optimizations are desirable only if SELECT_CC can be lowered. 11626 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11627 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11628 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 11629 !VT.isVector() && 11630 (!LegalOperations || 11631 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11632 SDLoc DL(N); 11633 SDValue Ops[] = 11634 { N0.getOperand(0), N0.getOperand(1), 11635 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11636 N0.getOperand(2) }; 11637 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11638 } 11639 11640 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 11641 // (select_cc x, y, 1.0, 0.0,, cc) 11642 if (N0.getOpcode() == ISD::ZERO_EXTEND && 11643 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 11644 (!LegalOperations || 11645 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11646 SDLoc DL(N); 11647 SDValue Ops[] = 11648 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 11649 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11650 N0.getOperand(0).getOperand(2) }; 11651 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11652 } 11653 } 11654 11655 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11656 return FTrunc; 11657 11658 return SDValue(); 11659 } 11660 11661 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 11662 SDValue N0 = N->getOperand(0); 11663 EVT VT = N->getValueType(0); 11664 EVT OpVT = N0.getValueType(); 11665 11666 // fold (uint_to_fp c1) -> c1fp 11667 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11668 // ...but only if the target supports immediate floating-point values 11669 (!LegalOperations || 11670 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11671 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11672 11673 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 11674 // but SINT_TO_FP is legal on this target, try to convert. 11675 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 11676 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 11677 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 11678 if (DAG.SignBitIsZero(N0)) 11679 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11680 } 11681 11682 // The next optimizations are desirable only if SELECT_CC can be lowered. 11683 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11684 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11685 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 11686 (!LegalOperations || 11687 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11688 SDLoc DL(N); 11689 SDValue Ops[] = 11690 { N0.getOperand(0), N0.getOperand(1), 11691 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11692 N0.getOperand(2) }; 11693 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11694 } 11695 } 11696 11697 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11698 return FTrunc; 11699 11700 return SDValue(); 11701 } 11702 11703 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 11704 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 11705 SDValue N0 = N->getOperand(0); 11706 EVT VT = N->getValueType(0); 11707 11708 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 11709 return SDValue(); 11710 11711 SDValue Src = N0.getOperand(0); 11712 EVT SrcVT = Src.getValueType(); 11713 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 11714 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 11715 11716 // We can safely assume the conversion won't overflow the output range, 11717 // because (for example) (uint8_t)18293.f is undefined behavior. 11718 11719 // Since we can assume the conversion won't overflow, our decision as to 11720 // whether the input will fit in the float should depend on the minimum 11721 // of the input range and output range. 11722 11723 // This means this is also safe for a signed input and unsigned output, since 11724 // a negative input would lead to undefined behavior. 11725 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 11726 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 11727 unsigned ActualSize = std::min(InputSize, OutputSize); 11728 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 11729 11730 // We can only fold away the float conversion if the input range can be 11731 // represented exactly in the float range. 11732 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 11733 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 11734 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 11735 : ISD::ZERO_EXTEND; 11736 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 11737 } 11738 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 11739 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 11740 return DAG.getBitcast(VT, Src); 11741 } 11742 return SDValue(); 11743 } 11744 11745 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 11746 SDValue N0 = N->getOperand(0); 11747 EVT VT = N->getValueType(0); 11748 11749 // fold (fp_to_sint c1fp) -> c1 11750 if (isConstantFPBuildVectorOrConstantFP(N0)) 11751 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 11752 11753 return FoldIntToFPToInt(N, DAG); 11754 } 11755 11756 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 11757 SDValue N0 = N->getOperand(0); 11758 EVT VT = N->getValueType(0); 11759 11760 // fold (fp_to_uint c1fp) -> c1 11761 if (isConstantFPBuildVectorOrConstantFP(N0)) 11762 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 11763 11764 return FoldIntToFPToInt(N, DAG); 11765 } 11766 11767 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 11768 SDValue N0 = N->getOperand(0); 11769 SDValue N1 = N->getOperand(1); 11770 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11771 EVT VT = N->getValueType(0); 11772 11773 // fold (fp_round c1fp) -> c1fp 11774 if (N0CFP) 11775 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 11776 11777 // fold (fp_round (fp_extend x)) -> x 11778 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 11779 return N0.getOperand(0); 11780 11781 // fold (fp_round (fp_round x)) -> (fp_round x) 11782 if (N0.getOpcode() == ISD::FP_ROUND) { 11783 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 11784 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 11785 11786 // Skip this folding if it results in an fp_round from f80 to f16. 11787 // 11788 // f80 to f16 always generates an expensive (and as yet, unimplemented) 11789 // libcall to __truncxfhf2 instead of selecting native f16 conversion 11790 // instructions from f32 or f64. Moreover, the first (value-preserving) 11791 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 11792 // x86. 11793 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 11794 return SDValue(); 11795 11796 // If the first fp_round isn't a value preserving truncation, it might 11797 // introduce a tie in the second fp_round, that wouldn't occur in the 11798 // single-step fp_round we want to fold to. 11799 // In other words, double rounding isn't the same as rounding. 11800 // Also, this is a value preserving truncation iff both fp_round's are. 11801 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 11802 SDLoc DL(N); 11803 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 11804 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 11805 } 11806 } 11807 11808 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 11809 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 11810 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 11811 N0.getOperand(0), N1); 11812 AddToWorklist(Tmp.getNode()); 11813 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 11814 Tmp, N0.getOperand(1)); 11815 } 11816 11817 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11818 return NewVSel; 11819 11820 return SDValue(); 11821 } 11822 11823 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 11824 SDValue N0 = N->getOperand(0); 11825 EVT VT = N->getValueType(0); 11826 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 11827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11828 11829 // fold (fp_round_inreg c1fp) -> c1fp 11830 if (N0CFP && isTypeLegal(EVT)) { 11831 SDLoc DL(N); 11832 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 11833 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 11834 } 11835 11836 return SDValue(); 11837 } 11838 11839 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 11840 SDValue N0 = N->getOperand(0); 11841 EVT VT = N->getValueType(0); 11842 11843 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 11844 if (N->hasOneUse() && 11845 N->use_begin()->getOpcode() == ISD::FP_ROUND) 11846 return SDValue(); 11847 11848 // fold (fp_extend c1fp) -> c1fp 11849 if (isConstantFPBuildVectorOrConstantFP(N0)) 11850 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 11851 11852 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 11853 if (N0.getOpcode() == ISD::FP16_TO_FP && 11854 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 11855 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 11856 11857 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 11858 // value of X. 11859 if (N0.getOpcode() == ISD::FP_ROUND 11860 && N0.getConstantOperandVal(1) == 1) { 11861 SDValue In = N0.getOperand(0); 11862 if (In.getValueType() == VT) return In; 11863 if (VT.bitsLT(In.getValueType())) 11864 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 11865 In, N0.getOperand(1)); 11866 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 11867 } 11868 11869 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 11870 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11871 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 11872 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11873 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 11874 LN0->getChain(), 11875 LN0->getBasePtr(), N0.getValueType(), 11876 LN0->getMemOperand()); 11877 CombineTo(N, ExtLoad); 11878 CombineTo(N0.getNode(), 11879 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 11880 N0.getValueType(), ExtLoad, 11881 DAG.getIntPtrConstant(1, SDLoc(N0))), 11882 ExtLoad.getValue(1)); 11883 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11884 } 11885 11886 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11887 return NewVSel; 11888 11889 return SDValue(); 11890 } 11891 11892 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 11893 SDValue N0 = N->getOperand(0); 11894 EVT VT = N->getValueType(0); 11895 11896 // fold (fceil c1) -> fceil(c1) 11897 if (isConstantFPBuildVectorOrConstantFP(N0)) 11898 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 11899 11900 return SDValue(); 11901 } 11902 11903 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 11904 SDValue N0 = N->getOperand(0); 11905 EVT VT = N->getValueType(0); 11906 11907 // fold (ftrunc c1) -> ftrunc(c1) 11908 if (isConstantFPBuildVectorOrConstantFP(N0)) 11909 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 11910 11911 // fold ftrunc (known rounded int x) -> x 11912 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 11913 // likely to be generated to extract integer from a rounded floating value. 11914 switch (N0.getOpcode()) { 11915 default: break; 11916 case ISD::FRINT: 11917 case ISD::FTRUNC: 11918 case ISD::FNEARBYINT: 11919 case ISD::FFLOOR: 11920 case ISD::FCEIL: 11921 return N0; 11922 } 11923 11924 return SDValue(); 11925 } 11926 11927 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 11928 SDValue N0 = N->getOperand(0); 11929 EVT VT = N->getValueType(0); 11930 11931 // fold (ffloor c1) -> ffloor(c1) 11932 if (isConstantFPBuildVectorOrConstantFP(N0)) 11933 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 11934 11935 return SDValue(); 11936 } 11937 11938 // FIXME: FNEG and FABS have a lot in common; refactor. 11939 SDValue DAGCombiner::visitFNEG(SDNode *N) { 11940 SDValue N0 = N->getOperand(0); 11941 EVT VT = N->getValueType(0); 11942 11943 // Constant fold FNEG. 11944 if (isConstantFPBuildVectorOrConstantFP(N0)) 11945 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 11946 11947 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 11948 &DAG.getTarget().Options)) 11949 return GetNegatedExpression(N0, DAG, LegalOperations); 11950 11951 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 11952 // constant pool values. 11953 if (!TLI.isFNegFree(VT) && 11954 N0.getOpcode() == ISD::BITCAST && 11955 N0.getNode()->hasOneUse()) { 11956 SDValue Int = N0.getOperand(0); 11957 EVT IntVT = Int.getValueType(); 11958 if (IntVT.isInteger() && !IntVT.isVector()) { 11959 APInt SignMask; 11960 if (N0.getValueType().isVector()) { 11961 // For a vector, get a mask such as 0x80... per scalar element 11962 // and splat it. 11963 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 11964 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11965 } else { 11966 // For a scalar, just generate 0x80... 11967 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 11968 } 11969 SDLoc DL0(N0); 11970 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 11971 DAG.getConstant(SignMask, DL0, IntVT)); 11972 AddToWorklist(Int.getNode()); 11973 return DAG.getBitcast(VT, Int); 11974 } 11975 } 11976 11977 // (fneg (fmul c, x)) -> (fmul -c, x) 11978 if (N0.getOpcode() == ISD::FMUL && 11979 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 11980 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 11981 if (CFP1) { 11982 APFloat CVal = CFP1->getValueAPF(); 11983 CVal.changeSign(); 11984 if (Level >= AfterLegalizeDAG && 11985 (TLI.isFPImmLegal(CVal, VT) || 11986 TLI.isOperationLegal(ISD::ConstantFP, VT))) 11987 return DAG.getNode( 11988 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 11989 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 11990 N0->getFlags()); 11991 } 11992 } 11993 11994 return SDValue(); 11995 } 11996 11997 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 11998 SDValue N0 = N->getOperand(0); 11999 SDValue N1 = N->getOperand(1); 12000 EVT VT = N->getValueType(0); 12001 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 12002 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 12003 12004 if (N0CFP && N1CFP) { 12005 const APFloat &C0 = N0CFP->getValueAPF(); 12006 const APFloat &C1 = N1CFP->getValueAPF(); 12007 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 12008 } 12009 12010 // Canonicalize to constant on RHS. 12011 if (isConstantFPBuildVectorOrConstantFP(N0) && 12012 !isConstantFPBuildVectorOrConstantFP(N1)) 12013 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 12014 12015 return SDValue(); 12016 } 12017 12018 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 12019 SDValue N0 = N->getOperand(0); 12020 SDValue N1 = N->getOperand(1); 12021 EVT VT = N->getValueType(0); 12022 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 12023 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 12024 12025 if (N0CFP && N1CFP) { 12026 const APFloat &C0 = N0CFP->getValueAPF(); 12027 const APFloat &C1 = N1CFP->getValueAPF(); 12028 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 12029 } 12030 12031 // Canonicalize to constant on RHS. 12032 if (isConstantFPBuildVectorOrConstantFP(N0) && 12033 !isConstantFPBuildVectorOrConstantFP(N1)) 12034 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 12035 12036 return SDValue(); 12037 } 12038 12039 SDValue DAGCombiner::visitFABS(SDNode *N) { 12040 SDValue N0 = N->getOperand(0); 12041 EVT VT = N->getValueType(0); 12042 12043 // fold (fabs c1) -> fabs(c1) 12044 if (isConstantFPBuildVectorOrConstantFP(N0)) 12045 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 12046 12047 // fold (fabs (fabs x)) -> (fabs x) 12048 if (N0.getOpcode() == ISD::FABS) 12049 return N->getOperand(0); 12050 12051 // fold (fabs (fneg x)) -> (fabs x) 12052 // fold (fabs (fcopysign x, y)) -> (fabs x) 12053 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 12054 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 12055 12056 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 12057 // constant pool values. 12058 if (!TLI.isFAbsFree(VT) && 12059 N0.getOpcode() == ISD::BITCAST && 12060 N0.getNode()->hasOneUse()) { 12061 SDValue Int = N0.getOperand(0); 12062 EVT IntVT = Int.getValueType(); 12063 if (IntVT.isInteger() && !IntVT.isVector()) { 12064 APInt SignMask; 12065 if (N0.getValueType().isVector()) { 12066 // For a vector, get a mask such as 0x7f... per scalar element 12067 // and splat it. 12068 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 12069 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 12070 } else { 12071 // For a scalar, just generate 0x7f... 12072 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 12073 } 12074 SDLoc DL(N0); 12075 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 12076 DAG.getConstant(SignMask, DL, IntVT)); 12077 AddToWorklist(Int.getNode()); 12078 return DAG.getBitcast(N->getValueType(0), Int); 12079 } 12080 } 12081 12082 return SDValue(); 12083 } 12084 12085 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 12086 SDValue Chain = N->getOperand(0); 12087 SDValue N1 = N->getOperand(1); 12088 SDValue N2 = N->getOperand(2); 12089 12090 // If N is a constant we could fold this into a fallthrough or unconditional 12091 // branch. However that doesn't happen very often in normal code, because 12092 // Instcombine/SimplifyCFG should have handled the available opportunities. 12093 // If we did this folding here, it would be necessary to update the 12094 // MachineBasicBlock CFG, which is awkward. 12095 12096 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 12097 // on the target. 12098 if (N1.getOpcode() == ISD::SETCC && 12099 TLI.isOperationLegalOrCustom(ISD::BR_CC, 12100 N1.getOperand(0).getValueType())) { 12101 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12102 Chain, N1.getOperand(2), 12103 N1.getOperand(0), N1.getOperand(1), N2); 12104 } 12105 12106 if (N1.hasOneUse()) { 12107 if (SDValue NewN1 = rebuildSetCC(N1)) 12108 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2); 12109 } 12110 12111 return SDValue(); 12112 } 12113 12114 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 12115 if (N.getOpcode() == ISD::SRL || 12116 (N.getOpcode() == ISD::TRUNCATE && 12117 (N.getOperand(0).hasOneUse() && 12118 N.getOperand(0).getOpcode() == ISD::SRL))) { 12119 // Look pass the truncate. 12120 if (N.getOpcode() == ISD::TRUNCATE) 12121 N = N.getOperand(0); 12122 12123 // Match this pattern so that we can generate simpler code: 12124 // 12125 // %a = ... 12126 // %b = and i32 %a, 2 12127 // %c = srl i32 %b, 1 12128 // brcond i32 %c ... 12129 // 12130 // into 12131 // 12132 // %a = ... 12133 // %b = and i32 %a, 2 12134 // %c = setcc eq %b, 0 12135 // brcond %c ... 12136 // 12137 // This applies only when the AND constant value has one bit set and the 12138 // SRL constant is equal to the log2 of the AND constant. The back-end is 12139 // smart enough to convert the result into a TEST/JMP sequence. 12140 SDValue Op0 = N.getOperand(0); 12141 SDValue Op1 = N.getOperand(1); 12142 12143 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 12144 SDValue AndOp1 = Op0.getOperand(1); 12145 12146 if (AndOp1.getOpcode() == ISD::Constant) { 12147 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 12148 12149 if (AndConst.isPowerOf2() && 12150 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 12151 SDLoc DL(N); 12152 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 12153 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 12154 ISD::SETNE); 12155 } 12156 } 12157 } 12158 } 12159 12160 // Transform br(xor(x, y)) -> br(x != y) 12161 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 12162 if (N.getOpcode() == ISD::XOR) { 12163 // Because we may call this on a speculatively constructed 12164 // SimplifiedSetCC Node, we need to simplify this node first. 12165 // Ideally this should be folded into SimplifySetCC and not 12166 // here. For now, grab a handle to N so we don't lose it from 12167 // replacements interal to the visit. 12168 HandleSDNode XORHandle(N); 12169 while (N.getOpcode() == ISD::XOR) { 12170 SDValue Tmp = visitXOR(N.getNode()); 12171 // No simplification done. 12172 if (!Tmp.getNode()) 12173 break; 12174 // Returning N is form in-visit replacement that may invalidated 12175 // N. Grab value from Handle. 12176 if (Tmp.getNode() == N.getNode()) 12177 N = XORHandle.getValue(); 12178 else // Node simplified. Try simplifying again. 12179 N = Tmp; 12180 } 12181 12182 if (N.getOpcode() != ISD::XOR) 12183 return N; 12184 12185 SDNode *TheXor = N.getNode(); 12186 12187 SDValue Op0 = TheXor->getOperand(0); 12188 SDValue Op1 = TheXor->getOperand(1); 12189 12190 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 12191 bool Equal = false; 12192 if (isOneConstant(Op0) && Op0.hasOneUse() && 12193 Op0.getOpcode() == ISD::XOR) { 12194 TheXor = Op0.getNode(); 12195 Equal = true; 12196 } 12197 12198 EVT SetCCVT = N.getValueType(); 12199 if (LegalTypes) 12200 SetCCVT = getSetCCResultType(SetCCVT); 12201 // Replace the uses of XOR with SETCC 12202 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1, 12203 Equal ? ISD::SETEQ : ISD::SETNE); 12204 } 12205 } 12206 12207 return SDValue(); 12208 } 12209 12210 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 12211 // 12212 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 12213 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 12214 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 12215 12216 // If N is a constant we could fold this into a fallthrough or unconditional 12217 // branch. However that doesn't happen very often in normal code, because 12218 // Instcombine/SimplifyCFG should have handled the available opportunities. 12219 // If we did this folding here, it would be necessary to update the 12220 // MachineBasicBlock CFG, which is awkward. 12221 12222 // Use SimplifySetCC to simplify SETCC's. 12223 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 12224 CondLHS, CondRHS, CC->get(), SDLoc(N), 12225 false); 12226 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 12227 12228 // fold to a simpler setcc 12229 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 12230 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12231 N->getOperand(0), Simp.getOperand(2), 12232 Simp.getOperand(0), Simp.getOperand(1), 12233 N->getOperand(4)); 12234 12235 return SDValue(); 12236 } 12237 12238 /// Return true if 'Use' is a load or a store that uses N as its base pointer 12239 /// and that N may be folded in the load / store addressing mode. 12240 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 12241 SelectionDAG &DAG, 12242 const TargetLowering &TLI) { 12243 EVT VT; 12244 unsigned AS; 12245 12246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 12247 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 12248 return false; 12249 VT = LD->getMemoryVT(); 12250 AS = LD->getAddressSpace(); 12251 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 12252 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 12253 return false; 12254 VT = ST->getMemoryVT(); 12255 AS = ST->getAddressSpace(); 12256 } else 12257 return false; 12258 12259 TargetLowering::AddrMode AM; 12260 if (N->getOpcode() == ISD::ADD) { 12261 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12262 if (Offset) 12263 // [reg +/- imm] 12264 AM.BaseOffs = Offset->getSExtValue(); 12265 else 12266 // [reg +/- reg] 12267 AM.Scale = 1; 12268 } else if (N->getOpcode() == ISD::SUB) { 12269 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12270 if (Offset) 12271 // [reg +/- imm] 12272 AM.BaseOffs = -Offset->getSExtValue(); 12273 else 12274 // [reg +/- reg] 12275 AM.Scale = 1; 12276 } else 12277 return false; 12278 12279 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 12280 VT.getTypeForEVT(*DAG.getContext()), AS); 12281 } 12282 12283 /// Try turning a load/store into a pre-indexed load/store when the base 12284 /// pointer is an add or subtract and it has other uses besides the load/store. 12285 /// After the transformation, the new indexed load/store has effectively folded 12286 /// the add/subtract in and all of its other uses are redirected to the 12287 /// new load/store. 12288 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 12289 if (Level < AfterLegalizeDAG) 12290 return false; 12291 12292 bool isLoad = true; 12293 SDValue Ptr; 12294 EVT VT; 12295 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12296 if (LD->isIndexed()) 12297 return false; 12298 VT = LD->getMemoryVT(); 12299 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 12300 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 12301 return false; 12302 Ptr = LD->getBasePtr(); 12303 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12304 if (ST->isIndexed()) 12305 return false; 12306 VT = ST->getMemoryVT(); 12307 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 12308 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 12309 return false; 12310 Ptr = ST->getBasePtr(); 12311 isLoad = false; 12312 } else { 12313 return false; 12314 } 12315 12316 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 12317 // out. There is no reason to make this a preinc/predec. 12318 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 12319 Ptr.getNode()->hasOneUse()) 12320 return false; 12321 12322 // Ask the target to do addressing mode selection. 12323 SDValue BasePtr; 12324 SDValue Offset; 12325 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12326 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 12327 return false; 12328 12329 // Backends without true r+i pre-indexed forms may need to pass a 12330 // constant base with a variable offset so that constant coercion 12331 // will work with the patterns in canonical form. 12332 bool Swapped = false; 12333 if (isa<ConstantSDNode>(BasePtr)) { 12334 std::swap(BasePtr, Offset); 12335 Swapped = true; 12336 } 12337 12338 // Don't create a indexed load / store with zero offset. 12339 if (isNullConstant(Offset)) 12340 return false; 12341 12342 // Try turning it into a pre-indexed load / store except when: 12343 // 1) The new base ptr is a frame index. 12344 // 2) If N is a store and the new base ptr is either the same as or is a 12345 // predecessor of the value being stored. 12346 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 12347 // that would create a cycle. 12348 // 4) All uses are load / store ops that use it as old base ptr. 12349 12350 // Check #1. Preinc'ing a frame index would require copying the stack pointer 12351 // (plus the implicit offset) to a register to preinc anyway. 12352 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12353 return false; 12354 12355 // Check #2. 12356 if (!isLoad) { 12357 SDValue Val = cast<StoreSDNode>(N)->getValue(); 12358 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 12359 return false; 12360 } 12361 12362 // Caches for hasPredecessorHelper. 12363 SmallPtrSet<const SDNode *, 32> Visited; 12364 SmallVector<const SDNode *, 16> Worklist; 12365 Worklist.push_back(N); 12366 12367 // If the offset is a constant, there may be other adds of constants that 12368 // can be folded with this one. We should do this to avoid having to keep 12369 // a copy of the original base pointer. 12370 SmallVector<SDNode *, 16> OtherUses; 12371 if (isa<ConstantSDNode>(Offset)) 12372 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 12373 UE = BasePtr.getNode()->use_end(); 12374 UI != UE; ++UI) { 12375 SDUse &Use = UI.getUse(); 12376 // Skip the use that is Ptr and uses of other results from BasePtr's 12377 // node (important for nodes that return multiple results). 12378 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 12379 continue; 12380 12381 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 12382 continue; 12383 12384 if (Use.getUser()->getOpcode() != ISD::ADD && 12385 Use.getUser()->getOpcode() != ISD::SUB) { 12386 OtherUses.clear(); 12387 break; 12388 } 12389 12390 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 12391 if (!isa<ConstantSDNode>(Op1)) { 12392 OtherUses.clear(); 12393 break; 12394 } 12395 12396 // FIXME: In some cases, we can be smarter about this. 12397 if (Op1.getValueType() != Offset.getValueType()) { 12398 OtherUses.clear(); 12399 break; 12400 } 12401 12402 OtherUses.push_back(Use.getUser()); 12403 } 12404 12405 if (Swapped) 12406 std::swap(BasePtr, Offset); 12407 12408 // Now check for #3 and #4. 12409 bool RealUse = false; 12410 12411 for (SDNode *Use : Ptr.getNode()->uses()) { 12412 if (Use == N) 12413 continue; 12414 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 12415 return false; 12416 12417 // If Ptr may be folded in addressing mode of other use, then it's 12418 // not profitable to do this transformation. 12419 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 12420 RealUse = true; 12421 } 12422 12423 if (!RealUse) 12424 return false; 12425 12426 SDValue Result; 12427 if (isLoad) 12428 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12429 BasePtr, Offset, AM); 12430 else 12431 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12432 BasePtr, Offset, AM); 12433 ++PreIndexedNodes; 12434 ++NodesCombined; 12435 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 12436 Result.getNode()->dump(&DAG); dbgs() << '\n'); 12437 WorklistRemover DeadNodes(*this); 12438 if (isLoad) { 12439 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12440 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12441 } else { 12442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12443 } 12444 12445 // Finally, since the node is now dead, remove it from the graph. 12446 deleteAndRecombine(N); 12447 12448 if (Swapped) 12449 std::swap(BasePtr, Offset); 12450 12451 // Replace other uses of BasePtr that can be updated to use Ptr 12452 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 12453 unsigned OffsetIdx = 1; 12454 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 12455 OffsetIdx = 0; 12456 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 12457 BasePtr.getNode() && "Expected BasePtr operand"); 12458 12459 // We need to replace ptr0 in the following expression: 12460 // x0 * offset0 + y0 * ptr0 = t0 12461 // knowing that 12462 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 12463 // 12464 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 12465 // indexed load/store and the expression that needs to be re-written. 12466 // 12467 // Therefore, we have: 12468 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 12469 12470 ConstantSDNode *CN = 12471 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 12472 int X0, X1, Y0, Y1; 12473 const APInt &Offset0 = CN->getAPIntValue(); 12474 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 12475 12476 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 12477 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 12478 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 12479 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 12480 12481 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 12482 12483 APInt CNV = Offset0; 12484 if (X0 < 0) CNV = -CNV; 12485 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 12486 else CNV = CNV - Offset1; 12487 12488 SDLoc DL(OtherUses[i]); 12489 12490 // We can now generate the new expression. 12491 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 12492 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 12493 12494 SDValue NewUse = DAG.getNode(Opcode, 12495 DL, 12496 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 12497 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 12498 deleteAndRecombine(OtherUses[i]); 12499 } 12500 12501 // Replace the uses of Ptr with uses of the updated base value. 12502 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 12503 deleteAndRecombine(Ptr.getNode()); 12504 AddToWorklist(Result.getNode()); 12505 12506 return true; 12507 } 12508 12509 /// Try to combine a load/store with a add/sub of the base pointer node into a 12510 /// post-indexed load/store. The transformation folded the add/subtract into the 12511 /// new indexed load/store effectively and all of its uses are redirected to the 12512 /// new load/store. 12513 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 12514 if (Level < AfterLegalizeDAG) 12515 return false; 12516 12517 bool isLoad = true; 12518 SDValue Ptr; 12519 EVT VT; 12520 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12521 if (LD->isIndexed()) 12522 return false; 12523 VT = LD->getMemoryVT(); 12524 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 12525 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 12526 return false; 12527 Ptr = LD->getBasePtr(); 12528 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12529 if (ST->isIndexed()) 12530 return false; 12531 VT = ST->getMemoryVT(); 12532 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 12533 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 12534 return false; 12535 Ptr = ST->getBasePtr(); 12536 isLoad = false; 12537 } else { 12538 return false; 12539 } 12540 12541 if (Ptr.getNode()->hasOneUse()) 12542 return false; 12543 12544 for (SDNode *Op : Ptr.getNode()->uses()) { 12545 if (Op == N || 12546 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 12547 continue; 12548 12549 SDValue BasePtr; 12550 SDValue Offset; 12551 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12552 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 12553 // Don't create a indexed load / store with zero offset. 12554 if (isNullConstant(Offset)) 12555 continue; 12556 12557 // Try turning it into a post-indexed load / store except when 12558 // 1) All uses are load / store ops that use it as base ptr (and 12559 // it may be folded as addressing mmode). 12560 // 2) Op must be independent of N, i.e. Op is neither a predecessor 12561 // nor a successor of N. Otherwise, if Op is folded that would 12562 // create a cycle. 12563 12564 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12565 continue; 12566 12567 // Check for #1. 12568 bool TryNext = false; 12569 for (SDNode *Use : BasePtr.getNode()->uses()) { 12570 if (Use == Ptr.getNode()) 12571 continue; 12572 12573 // If all the uses are load / store addresses, then don't do the 12574 // transformation. 12575 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 12576 bool RealUse = false; 12577 for (SDNode *UseUse : Use->uses()) { 12578 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 12579 RealUse = true; 12580 } 12581 12582 if (!RealUse) { 12583 TryNext = true; 12584 break; 12585 } 12586 } 12587 } 12588 12589 if (TryNext) 12590 continue; 12591 12592 // Check for #2 12593 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 12594 SDValue Result = isLoad 12595 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12596 BasePtr, Offset, AM) 12597 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12598 BasePtr, Offset, AM); 12599 ++PostIndexedNodes; 12600 ++NodesCombined; 12601 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 12602 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 12603 dbgs() << '\n'); 12604 WorklistRemover DeadNodes(*this); 12605 if (isLoad) { 12606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12607 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12608 } else { 12609 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12610 } 12611 12612 // Finally, since the node is now dead, remove it from the graph. 12613 deleteAndRecombine(N); 12614 12615 // Replace the uses of Use with uses of the updated base value. 12616 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 12617 Result.getValue(isLoad ? 1 : 0)); 12618 deleteAndRecombine(Op); 12619 return true; 12620 } 12621 } 12622 } 12623 12624 return false; 12625 } 12626 12627 /// Return the base-pointer arithmetic from an indexed \p LD. 12628 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 12629 ISD::MemIndexedMode AM = LD->getAddressingMode(); 12630 assert(AM != ISD::UNINDEXED); 12631 SDValue BP = LD->getOperand(1); 12632 SDValue Inc = LD->getOperand(2); 12633 12634 // Some backends use TargetConstants for load offsets, but don't expect 12635 // TargetConstants in general ADD nodes. We can convert these constants into 12636 // regular Constants (if the constant is not opaque). 12637 assert((Inc.getOpcode() != ISD::TargetConstant || 12638 !cast<ConstantSDNode>(Inc)->isOpaque()) && 12639 "Cannot split out indexing using opaque target constants"); 12640 if (Inc.getOpcode() == ISD::TargetConstant) { 12641 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 12642 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 12643 ConstInc->getValueType(0)); 12644 } 12645 12646 unsigned Opc = 12647 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 12648 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 12649 } 12650 12651 SDValue DAGCombiner::visitLOAD(SDNode *N) { 12652 LoadSDNode *LD = cast<LoadSDNode>(N); 12653 SDValue Chain = LD->getChain(); 12654 SDValue Ptr = LD->getBasePtr(); 12655 12656 // If load is not volatile and there are no uses of the loaded value (and 12657 // the updated indexed value in case of indexed loads), change uses of the 12658 // chain value into uses of the chain input (i.e. delete the dead load). 12659 if (!LD->isVolatile()) { 12660 if (N->getValueType(1) == MVT::Other) { 12661 // Unindexed loads. 12662 if (!N->hasAnyUseOfValue(0)) { 12663 // It's not safe to use the two value CombineTo variant here. e.g. 12664 // v1, chain2 = load chain1, loc 12665 // v2, chain3 = load chain2, loc 12666 // v3 = add v2, c 12667 // Now we replace use of chain2 with chain1. This makes the second load 12668 // isomorphic to the one we are deleting, and thus makes this load live. 12669 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 12670 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 12671 dbgs() << "\n"); 12672 WorklistRemover DeadNodes(*this); 12673 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12674 AddUsersToWorklist(Chain.getNode()); 12675 if (N->use_empty()) 12676 deleteAndRecombine(N); 12677 12678 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12679 } 12680 } else { 12681 // Indexed loads. 12682 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 12683 12684 // If this load has an opaque TargetConstant offset, then we cannot split 12685 // the indexing into an add/sub directly (that TargetConstant may not be 12686 // valid for a different type of node, and we cannot convert an opaque 12687 // target constant into a regular constant). 12688 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 12689 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 12690 12691 if (!N->hasAnyUseOfValue(0) && 12692 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 12693 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 12694 SDValue Index; 12695 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 12696 Index = SplitIndexingFromLoad(LD); 12697 // Try to fold the base pointer arithmetic into subsequent loads and 12698 // stores. 12699 AddUsersToWorklist(N); 12700 } else 12701 Index = DAG.getUNDEF(N->getValueType(1)); 12702 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 12703 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 12704 dbgs() << " and 2 other values\n"); 12705 WorklistRemover DeadNodes(*this); 12706 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 12707 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 12708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 12709 deleteAndRecombine(N); 12710 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12711 } 12712 } 12713 } 12714 12715 // If this load is directly stored, replace the load value with the stored 12716 // value. 12717 // TODO: Handle store large -> read small portion. 12718 // TODO: Handle TRUNCSTORE/LOADEXT 12719 if (OptLevel != CodeGenOpt::None && 12720 ISD::isNormalLoad(N) && !LD->isVolatile()) { 12721 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 12722 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 12723 if (PrevST->getBasePtr() == Ptr && 12724 PrevST->getValue().getValueType() == N->getValueType(0)) 12725 return CombineTo(N, PrevST->getOperand(1), Chain); 12726 } 12727 } 12728 12729 // Try to infer better alignment information than the load already has. 12730 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 12731 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12732 if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) { 12733 SDValue NewLoad = DAG.getExtLoad( 12734 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 12735 LD->getPointerInfo(), LD->getMemoryVT(), Align, 12736 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12737 // NewLoad will always be N as we are only refining the alignment 12738 assert(NewLoad.getNode() == N); 12739 (void)NewLoad; 12740 } 12741 } 12742 } 12743 12744 if (LD->isUnindexed()) { 12745 // Walk up chain skipping non-aliasing memory nodes. 12746 SDValue BetterChain = FindBetterChain(N, Chain); 12747 12748 // If there is a better chain. 12749 if (Chain != BetterChain) { 12750 SDValue ReplLoad; 12751 12752 // Replace the chain to void dependency. 12753 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 12754 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 12755 BetterChain, Ptr, LD->getMemOperand()); 12756 } else { 12757 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 12758 LD->getValueType(0), 12759 BetterChain, Ptr, LD->getMemoryVT(), 12760 LD->getMemOperand()); 12761 } 12762 12763 // Create token factor to keep old chain connected. 12764 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 12765 MVT::Other, Chain, ReplLoad.getValue(1)); 12766 12767 // Replace uses with load result and token factor 12768 return CombineTo(N, ReplLoad.getValue(0), Token); 12769 } 12770 } 12771 12772 // Try transforming N to an indexed load. 12773 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12774 return SDValue(N, 0); 12775 12776 // Try to slice up N to more direct loads if the slices are mapped to 12777 // different register banks or pairing can take place. 12778 if (SliceUpLoad(N)) 12779 return SDValue(N, 0); 12780 12781 return SDValue(); 12782 } 12783 12784 namespace { 12785 12786 /// Helper structure used to slice a load in smaller loads. 12787 /// Basically a slice is obtained from the following sequence: 12788 /// Origin = load Ty1, Base 12789 /// Shift = srl Ty1 Origin, CstTy Amount 12790 /// Inst = trunc Shift to Ty2 12791 /// 12792 /// Then, it will be rewritten into: 12793 /// Slice = load SliceTy, Base + SliceOffset 12794 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 12795 /// 12796 /// SliceTy is deduced from the number of bits that are actually used to 12797 /// build Inst. 12798 struct LoadedSlice { 12799 /// Helper structure used to compute the cost of a slice. 12800 struct Cost { 12801 /// Are we optimizing for code size. 12802 bool ForCodeSize; 12803 12804 /// Various cost. 12805 unsigned Loads = 0; 12806 unsigned Truncates = 0; 12807 unsigned CrossRegisterBanksCopies = 0; 12808 unsigned ZExts = 0; 12809 unsigned Shift = 0; 12810 12811 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 12812 12813 /// Get the cost of one isolated slice. 12814 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 12815 : ForCodeSize(ForCodeSize), Loads(1) { 12816 EVT TruncType = LS.Inst->getValueType(0); 12817 EVT LoadedType = LS.getLoadedType(); 12818 if (TruncType != LoadedType && 12819 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 12820 ZExts = 1; 12821 } 12822 12823 /// Account for slicing gain in the current cost. 12824 /// Slicing provide a few gains like removing a shift or a 12825 /// truncate. This method allows to grow the cost of the original 12826 /// load with the gain from this slice. 12827 void addSliceGain(const LoadedSlice &LS) { 12828 // Each slice saves a truncate. 12829 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 12830 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 12831 LS.Inst->getValueType(0))) 12832 ++Truncates; 12833 // If there is a shift amount, this slice gets rid of it. 12834 if (LS.Shift) 12835 ++Shift; 12836 // If this slice can merge a cross register bank copy, account for it. 12837 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 12838 ++CrossRegisterBanksCopies; 12839 } 12840 12841 Cost &operator+=(const Cost &RHS) { 12842 Loads += RHS.Loads; 12843 Truncates += RHS.Truncates; 12844 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 12845 ZExts += RHS.ZExts; 12846 Shift += RHS.Shift; 12847 return *this; 12848 } 12849 12850 bool operator==(const Cost &RHS) const { 12851 return Loads == RHS.Loads && Truncates == RHS.Truncates && 12852 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 12853 ZExts == RHS.ZExts && Shift == RHS.Shift; 12854 } 12855 12856 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 12857 12858 bool operator<(const Cost &RHS) const { 12859 // Assume cross register banks copies are as expensive as loads. 12860 // FIXME: Do we want some more target hooks? 12861 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 12862 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 12863 // Unless we are optimizing for code size, consider the 12864 // expensive operation first. 12865 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 12866 return ExpensiveOpsLHS < ExpensiveOpsRHS; 12867 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 12868 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 12869 } 12870 12871 bool operator>(const Cost &RHS) const { return RHS < *this; } 12872 12873 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 12874 12875 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 12876 }; 12877 12878 // The last instruction that represent the slice. This should be a 12879 // truncate instruction. 12880 SDNode *Inst; 12881 12882 // The original load instruction. 12883 LoadSDNode *Origin; 12884 12885 // The right shift amount in bits from the original load. 12886 unsigned Shift; 12887 12888 // The DAG from which Origin came from. 12889 // This is used to get some contextual information about legal types, etc. 12890 SelectionDAG *DAG; 12891 12892 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 12893 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 12894 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 12895 12896 /// Get the bits used in a chunk of bits \p BitWidth large. 12897 /// \return Result is \p BitWidth and has used bits set to 1 and 12898 /// not used bits set to 0. 12899 APInt getUsedBits() const { 12900 // Reproduce the trunc(lshr) sequence: 12901 // - Start from the truncated value. 12902 // - Zero extend to the desired bit width. 12903 // - Shift left. 12904 assert(Origin && "No original load to compare against."); 12905 unsigned BitWidth = Origin->getValueSizeInBits(0); 12906 assert(Inst && "This slice is not bound to an instruction"); 12907 assert(Inst->getValueSizeInBits(0) <= BitWidth && 12908 "Extracted slice is bigger than the whole type!"); 12909 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 12910 UsedBits.setAllBits(); 12911 UsedBits = UsedBits.zext(BitWidth); 12912 UsedBits <<= Shift; 12913 return UsedBits; 12914 } 12915 12916 /// Get the size of the slice to be loaded in bytes. 12917 unsigned getLoadedSize() const { 12918 unsigned SliceSize = getUsedBits().countPopulation(); 12919 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 12920 return SliceSize / 8; 12921 } 12922 12923 /// Get the type that will be loaded for this slice. 12924 /// Note: This may not be the final type for the slice. 12925 EVT getLoadedType() const { 12926 assert(DAG && "Missing context"); 12927 LLVMContext &Ctxt = *DAG->getContext(); 12928 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 12929 } 12930 12931 /// Get the alignment of the load used for this slice. 12932 unsigned getAlignment() const { 12933 unsigned Alignment = Origin->getAlignment(); 12934 unsigned Offset = getOffsetFromBase(); 12935 if (Offset != 0) 12936 Alignment = MinAlign(Alignment, Alignment + Offset); 12937 return Alignment; 12938 } 12939 12940 /// Check if this slice can be rewritten with legal operations. 12941 bool isLegal() const { 12942 // An invalid slice is not legal. 12943 if (!Origin || !Inst || !DAG) 12944 return false; 12945 12946 // Offsets are for indexed load only, we do not handle that. 12947 if (!Origin->getOffset().isUndef()) 12948 return false; 12949 12950 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12951 12952 // Check that the type is legal. 12953 EVT SliceType = getLoadedType(); 12954 if (!TLI.isTypeLegal(SliceType)) 12955 return false; 12956 12957 // Check that the load is legal for this type. 12958 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 12959 return false; 12960 12961 // Check that the offset can be computed. 12962 // 1. Check its type. 12963 EVT PtrType = Origin->getBasePtr().getValueType(); 12964 if (PtrType == MVT::Untyped || PtrType.isExtended()) 12965 return false; 12966 12967 // 2. Check that it fits in the immediate. 12968 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 12969 return false; 12970 12971 // 3. Check that the computation is legal. 12972 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 12973 return false; 12974 12975 // Check that the zext is legal if it needs one. 12976 EVT TruncateType = Inst->getValueType(0); 12977 if (TruncateType != SliceType && 12978 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 12979 return false; 12980 12981 return true; 12982 } 12983 12984 /// Get the offset in bytes of this slice in the original chunk of 12985 /// bits. 12986 /// \pre DAG != nullptr. 12987 uint64_t getOffsetFromBase() const { 12988 assert(DAG && "Missing context."); 12989 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 12990 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 12991 uint64_t Offset = Shift / 8; 12992 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 12993 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 12994 "The size of the original loaded type is not a multiple of a" 12995 " byte."); 12996 // If Offset is bigger than TySizeInBytes, it means we are loading all 12997 // zeros. This should have been optimized before in the process. 12998 assert(TySizeInBytes > Offset && 12999 "Invalid shift amount for given loaded size"); 13000 if (IsBigEndian) 13001 Offset = TySizeInBytes - Offset - getLoadedSize(); 13002 return Offset; 13003 } 13004 13005 /// Generate the sequence of instructions to load the slice 13006 /// represented by this object and redirect the uses of this slice to 13007 /// this new sequence of instructions. 13008 /// \pre this->Inst && this->Origin are valid Instructions and this 13009 /// object passed the legal check: LoadedSlice::isLegal returned true. 13010 /// \return The last instruction of the sequence used to load the slice. 13011 SDValue loadSlice() const { 13012 assert(Inst && Origin && "Unable to replace a non-existing slice."); 13013 const SDValue &OldBaseAddr = Origin->getBasePtr(); 13014 SDValue BaseAddr = OldBaseAddr; 13015 // Get the offset in that chunk of bytes w.r.t. the endianness. 13016 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 13017 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 13018 if (Offset) { 13019 // BaseAddr = BaseAddr + Offset. 13020 EVT ArithType = BaseAddr.getValueType(); 13021 SDLoc DL(Origin); 13022 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 13023 DAG->getConstant(Offset, DL, ArithType)); 13024 } 13025 13026 // Create the type of the loaded slice according to its size. 13027 EVT SliceType = getLoadedType(); 13028 13029 // Create the load for the slice. 13030 SDValue LastInst = 13031 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 13032 Origin->getPointerInfo().getWithOffset(Offset), 13033 getAlignment(), Origin->getMemOperand()->getFlags()); 13034 // If the final type is not the same as the loaded type, this means that 13035 // we have to pad with zero. Create a zero extend for that. 13036 EVT FinalType = Inst->getValueType(0); 13037 if (SliceType != FinalType) 13038 LastInst = 13039 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 13040 return LastInst; 13041 } 13042 13043 /// Check if this slice can be merged with an expensive cross register 13044 /// bank copy. E.g., 13045 /// i = load i32 13046 /// f = bitcast i32 i to float 13047 bool canMergeExpensiveCrossRegisterBankCopy() const { 13048 if (!Inst || !Inst->hasOneUse()) 13049 return false; 13050 SDNode *Use = *Inst->use_begin(); 13051 if (Use->getOpcode() != ISD::BITCAST) 13052 return false; 13053 assert(DAG && "Missing context"); 13054 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 13055 EVT ResVT = Use->getValueType(0); 13056 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 13057 const TargetRegisterClass *ArgRC = 13058 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 13059 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 13060 return false; 13061 13062 // At this point, we know that we perform a cross-register-bank copy. 13063 // Check if it is expensive. 13064 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 13065 // Assume bitcasts are cheap, unless both register classes do not 13066 // explicitly share a common sub class. 13067 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 13068 return false; 13069 13070 // Check if it will be merged with the load. 13071 // 1. Check the alignment constraint. 13072 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 13073 ResVT.getTypeForEVT(*DAG->getContext())); 13074 13075 if (RequiredAlignment > getAlignment()) 13076 return false; 13077 13078 // 2. Check that the load is a legal operation for that type. 13079 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 13080 return false; 13081 13082 // 3. Check that we do not have a zext in the way. 13083 if (Inst->getValueType(0) != getLoadedType()) 13084 return false; 13085 13086 return true; 13087 } 13088 }; 13089 13090 } // end anonymous namespace 13091 13092 /// Check that all bits set in \p UsedBits form a dense region, i.e., 13093 /// \p UsedBits looks like 0..0 1..1 0..0. 13094 static bool areUsedBitsDense(const APInt &UsedBits) { 13095 // If all the bits are one, this is dense! 13096 if (UsedBits.isAllOnesValue()) 13097 return true; 13098 13099 // Get rid of the unused bits on the right. 13100 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 13101 // Get rid of the unused bits on the left. 13102 if (NarrowedUsedBits.countLeadingZeros()) 13103 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 13104 // Check that the chunk of bits is completely used. 13105 return NarrowedUsedBits.isAllOnesValue(); 13106 } 13107 13108 /// Check whether or not \p First and \p Second are next to each other 13109 /// in memory. This means that there is no hole between the bits loaded 13110 /// by \p First and the bits loaded by \p Second. 13111 static bool areSlicesNextToEachOther(const LoadedSlice &First, 13112 const LoadedSlice &Second) { 13113 assert(First.Origin == Second.Origin && First.Origin && 13114 "Unable to match different memory origins."); 13115 APInt UsedBits = First.getUsedBits(); 13116 assert((UsedBits & Second.getUsedBits()) == 0 && 13117 "Slices are not supposed to overlap."); 13118 UsedBits |= Second.getUsedBits(); 13119 return areUsedBitsDense(UsedBits); 13120 } 13121 13122 /// Adjust the \p GlobalLSCost according to the target 13123 /// paring capabilities and the layout of the slices. 13124 /// \pre \p GlobalLSCost should account for at least as many loads as 13125 /// there is in the slices in \p LoadedSlices. 13126 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13127 LoadedSlice::Cost &GlobalLSCost) { 13128 unsigned NumberOfSlices = LoadedSlices.size(); 13129 // If there is less than 2 elements, no pairing is possible. 13130 if (NumberOfSlices < 2) 13131 return; 13132 13133 // Sort the slices so that elements that are likely to be next to each 13134 // other in memory are next to each other in the list. 13135 llvm::sort(LoadedSlices.begin(), LoadedSlices.end(), 13136 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 13137 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 13138 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 13139 }); 13140 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 13141 // First (resp. Second) is the first (resp. Second) potentially candidate 13142 // to be placed in a paired load. 13143 const LoadedSlice *First = nullptr; 13144 const LoadedSlice *Second = nullptr; 13145 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 13146 // Set the beginning of the pair. 13147 First = Second) { 13148 Second = &LoadedSlices[CurrSlice]; 13149 13150 // If First is NULL, it means we start a new pair. 13151 // Get to the next slice. 13152 if (!First) 13153 continue; 13154 13155 EVT LoadedType = First->getLoadedType(); 13156 13157 // If the types of the slices are different, we cannot pair them. 13158 if (LoadedType != Second->getLoadedType()) 13159 continue; 13160 13161 // Check if the target supplies paired loads for this type. 13162 unsigned RequiredAlignment = 0; 13163 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 13164 // move to the next pair, this type is hopeless. 13165 Second = nullptr; 13166 continue; 13167 } 13168 // Check if we meet the alignment requirement. 13169 if (RequiredAlignment > First->getAlignment()) 13170 continue; 13171 13172 // Check that both loads are next to each other in memory. 13173 if (!areSlicesNextToEachOther(*First, *Second)) 13174 continue; 13175 13176 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 13177 --GlobalLSCost.Loads; 13178 // Move to the next pair. 13179 Second = nullptr; 13180 } 13181 } 13182 13183 /// Check the profitability of all involved LoadedSlice. 13184 /// Currently, it is considered profitable if there is exactly two 13185 /// involved slices (1) which are (2) next to each other in memory, and 13186 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 13187 /// 13188 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 13189 /// the elements themselves. 13190 /// 13191 /// FIXME: When the cost model will be mature enough, we can relax 13192 /// constraints (1) and (2). 13193 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13194 const APInt &UsedBits, bool ForCodeSize) { 13195 unsigned NumberOfSlices = LoadedSlices.size(); 13196 if (StressLoadSlicing) 13197 return NumberOfSlices > 1; 13198 13199 // Check (1). 13200 if (NumberOfSlices != 2) 13201 return false; 13202 13203 // Check (2). 13204 if (!areUsedBitsDense(UsedBits)) 13205 return false; 13206 13207 // Check (3). 13208 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 13209 // The original code has one big load. 13210 OrigCost.Loads = 1; 13211 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 13212 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 13213 // Accumulate the cost of all the slices. 13214 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 13215 GlobalSlicingCost += SliceCost; 13216 13217 // Account as cost in the original configuration the gain obtained 13218 // with the current slices. 13219 OrigCost.addSliceGain(LS); 13220 } 13221 13222 // If the target supports paired load, adjust the cost accordingly. 13223 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 13224 return OrigCost > GlobalSlicingCost; 13225 } 13226 13227 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 13228 /// operations, split it in the various pieces being extracted. 13229 /// 13230 /// This sort of thing is introduced by SROA. 13231 /// This slicing takes care not to insert overlapping loads. 13232 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 13233 bool DAGCombiner::SliceUpLoad(SDNode *N) { 13234 if (Level < AfterLegalizeDAG) 13235 return false; 13236 13237 LoadSDNode *LD = cast<LoadSDNode>(N); 13238 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 13239 !LD->getValueType(0).isInteger()) 13240 return false; 13241 13242 // Keep track of already used bits to detect overlapping values. 13243 // In that case, we will just abort the transformation. 13244 APInt UsedBits(LD->getValueSizeInBits(0), 0); 13245 13246 SmallVector<LoadedSlice, 4> LoadedSlices; 13247 13248 // Check if this load is used as several smaller chunks of bits. 13249 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 13250 // of computation for each trunc. 13251 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 13252 UI != UIEnd; ++UI) { 13253 // Skip the uses of the chain. 13254 if (UI.getUse().getResNo() != 0) 13255 continue; 13256 13257 SDNode *User = *UI; 13258 unsigned Shift = 0; 13259 13260 // Check if this is a trunc(lshr). 13261 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 13262 isa<ConstantSDNode>(User->getOperand(1))) { 13263 Shift = User->getConstantOperandVal(1); 13264 User = *User->use_begin(); 13265 } 13266 13267 // At this point, User is a Truncate, iff we encountered, trunc or 13268 // trunc(lshr). 13269 if (User->getOpcode() != ISD::TRUNCATE) 13270 return false; 13271 13272 // The width of the type must be a power of 2 and greater than 8-bits. 13273 // Otherwise the load cannot be represented in LLVM IR. 13274 // Moreover, if we shifted with a non-8-bits multiple, the slice 13275 // will be across several bytes. We do not support that. 13276 unsigned Width = User->getValueSizeInBits(0); 13277 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 13278 return false; 13279 13280 // Build the slice for this chain of computations. 13281 LoadedSlice LS(User, LD, Shift, &DAG); 13282 APInt CurrentUsedBits = LS.getUsedBits(); 13283 13284 // Check if this slice overlaps with another. 13285 if ((CurrentUsedBits & UsedBits) != 0) 13286 return false; 13287 // Update the bits used globally. 13288 UsedBits |= CurrentUsedBits; 13289 13290 // Check if the new slice would be legal. 13291 if (!LS.isLegal()) 13292 return false; 13293 13294 // Record the slice. 13295 LoadedSlices.push_back(LS); 13296 } 13297 13298 // Abort slicing if it does not seem to be profitable. 13299 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 13300 return false; 13301 13302 ++SlicedLoads; 13303 13304 // Rewrite each chain to use an independent load. 13305 // By construction, each chain can be represented by a unique load. 13306 13307 // Prepare the argument for the new token factor for all the slices. 13308 SmallVector<SDValue, 8> ArgChains; 13309 for (SmallVectorImpl<LoadedSlice>::const_iterator 13310 LSIt = LoadedSlices.begin(), 13311 LSItEnd = LoadedSlices.end(); 13312 LSIt != LSItEnd; ++LSIt) { 13313 SDValue SliceInst = LSIt->loadSlice(); 13314 CombineTo(LSIt->Inst, SliceInst, true); 13315 if (SliceInst.getOpcode() != ISD::LOAD) 13316 SliceInst = SliceInst.getOperand(0); 13317 assert(SliceInst->getOpcode() == ISD::LOAD && 13318 "It takes more than a zext to get to the loaded slice!!"); 13319 ArgChains.push_back(SliceInst.getValue(1)); 13320 } 13321 13322 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 13323 ArgChains); 13324 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 13325 AddToWorklist(Chain.getNode()); 13326 return true; 13327 } 13328 13329 /// Check to see if V is (and load (ptr), imm), where the load is having 13330 /// specific bytes cleared out. If so, return the byte size being masked out 13331 /// and the shift amount. 13332 static std::pair<unsigned, unsigned> 13333 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 13334 std::pair<unsigned, unsigned> Result(0, 0); 13335 13336 // Check for the structure we're looking for. 13337 if (V->getOpcode() != ISD::AND || 13338 !isa<ConstantSDNode>(V->getOperand(1)) || 13339 !ISD::isNormalLoad(V->getOperand(0).getNode())) 13340 return Result; 13341 13342 // Check the chain and pointer. 13343 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 13344 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 13345 13346 // This only handles simple types. 13347 if (V.getValueType() != MVT::i16 && 13348 V.getValueType() != MVT::i32 && 13349 V.getValueType() != MVT::i64) 13350 return Result; 13351 13352 // Check the constant mask. Invert it so that the bits being masked out are 13353 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 13354 // follow the sign bit for uniformity. 13355 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 13356 unsigned NotMaskLZ = countLeadingZeros(NotMask); 13357 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 13358 unsigned NotMaskTZ = countTrailingZeros(NotMask); 13359 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 13360 if (NotMaskLZ == 64) return Result; // All zero mask. 13361 13362 // See if we have a continuous run of bits. If so, we have 0*1+0* 13363 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 13364 return Result; 13365 13366 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 13367 if (V.getValueType() != MVT::i64 && NotMaskLZ) 13368 NotMaskLZ -= 64-V.getValueSizeInBits(); 13369 13370 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 13371 switch (MaskedBytes) { 13372 case 1: 13373 case 2: 13374 case 4: break; 13375 default: return Result; // All one mask, or 5-byte mask. 13376 } 13377 13378 // Verify that the first bit starts at a multiple of mask so that the access 13379 // is aligned the same as the access width. 13380 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 13381 13382 // For narrowing to be valid, it must be the case that the load the 13383 // immediately preceeding memory operation before the store. 13384 if (LD == Chain.getNode()) 13385 ; // ok. 13386 else if (Chain->getOpcode() == ISD::TokenFactor && 13387 SDValue(LD, 1).hasOneUse()) { 13388 // LD has only 1 chain use so they are no indirect dependencies. 13389 bool isOk = false; 13390 for (const SDValue &ChainOp : Chain->op_values()) 13391 if (ChainOp.getNode() == LD) { 13392 isOk = true; 13393 break; 13394 } 13395 if (!isOk) 13396 return Result; 13397 } else 13398 return Result; // Fail. 13399 13400 Result.first = MaskedBytes; 13401 Result.second = NotMaskTZ/8; 13402 return Result; 13403 } 13404 13405 /// Check to see if IVal is something that provides a value as specified by 13406 /// MaskInfo. If so, replace the specified store with a narrower store of 13407 /// truncated IVal. 13408 static SDNode * 13409 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 13410 SDValue IVal, StoreSDNode *St, 13411 DAGCombiner *DC) { 13412 unsigned NumBytes = MaskInfo.first; 13413 unsigned ByteShift = MaskInfo.second; 13414 SelectionDAG &DAG = DC->getDAG(); 13415 13416 // Check to see if IVal is all zeros in the part being masked in by the 'or' 13417 // that uses this. If not, this is not a replacement. 13418 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 13419 ByteShift*8, (ByteShift+NumBytes)*8); 13420 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 13421 13422 // Check that it is legal on the target to do this. It is legal if the new 13423 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 13424 // legalization. 13425 MVT VT = MVT::getIntegerVT(NumBytes*8); 13426 if (!DC->isTypeLegal(VT)) 13427 return nullptr; 13428 13429 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 13430 // shifted by ByteShift and truncated down to NumBytes. 13431 if (ByteShift) { 13432 SDLoc DL(IVal); 13433 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 13434 DAG.getConstant(ByteShift*8, DL, 13435 DC->getShiftAmountTy(IVal.getValueType()))); 13436 } 13437 13438 // Figure out the offset for the store and the alignment of the access. 13439 unsigned StOffset; 13440 unsigned NewAlign = St->getAlignment(); 13441 13442 if (DAG.getDataLayout().isLittleEndian()) 13443 StOffset = ByteShift; 13444 else 13445 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 13446 13447 SDValue Ptr = St->getBasePtr(); 13448 if (StOffset) { 13449 SDLoc DL(IVal); 13450 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 13451 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 13452 NewAlign = MinAlign(NewAlign, StOffset); 13453 } 13454 13455 // Truncate down to the new size. 13456 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 13457 13458 ++OpsNarrowed; 13459 return DAG 13460 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 13461 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 13462 .getNode(); 13463 } 13464 13465 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 13466 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 13467 /// narrowing the load and store if it would end up being a win for performance 13468 /// or code size. 13469 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 13470 StoreSDNode *ST = cast<StoreSDNode>(N); 13471 if (ST->isVolatile()) 13472 return SDValue(); 13473 13474 SDValue Chain = ST->getChain(); 13475 SDValue Value = ST->getValue(); 13476 SDValue Ptr = ST->getBasePtr(); 13477 EVT VT = Value.getValueType(); 13478 13479 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 13480 return SDValue(); 13481 13482 unsigned Opc = Value.getOpcode(); 13483 13484 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 13485 // is a byte mask indicating a consecutive number of bytes, check to see if 13486 // Y is known to provide just those bytes. If so, we try to replace the 13487 // load + replace + store sequence with a single (narrower) store, which makes 13488 // the load dead. 13489 if (Opc == ISD::OR) { 13490 std::pair<unsigned, unsigned> MaskedLoad; 13491 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 13492 if (MaskedLoad.first) 13493 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13494 Value.getOperand(1), ST,this)) 13495 return SDValue(NewST, 0); 13496 13497 // Or is commutative, so try swapping X and Y. 13498 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 13499 if (MaskedLoad.first) 13500 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13501 Value.getOperand(0), ST,this)) 13502 return SDValue(NewST, 0); 13503 } 13504 13505 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 13506 Value.getOperand(1).getOpcode() != ISD::Constant) 13507 return SDValue(); 13508 13509 SDValue N0 = Value.getOperand(0); 13510 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 13511 Chain == SDValue(N0.getNode(), 1)) { 13512 LoadSDNode *LD = cast<LoadSDNode>(N0); 13513 if (LD->getBasePtr() != Ptr || 13514 LD->getPointerInfo().getAddrSpace() != 13515 ST->getPointerInfo().getAddrSpace()) 13516 return SDValue(); 13517 13518 // Find the type to narrow it the load / op / store to. 13519 SDValue N1 = Value.getOperand(1); 13520 unsigned BitWidth = N1.getValueSizeInBits(); 13521 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 13522 if (Opc == ISD::AND) 13523 Imm ^= APInt::getAllOnesValue(BitWidth); 13524 if (Imm == 0 || Imm.isAllOnesValue()) 13525 return SDValue(); 13526 unsigned ShAmt = Imm.countTrailingZeros(); 13527 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 13528 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 13529 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13530 // The narrowing should be profitable, the load/store operation should be 13531 // legal (or custom) and the store size should be equal to the NewVT width. 13532 while (NewBW < BitWidth && 13533 (NewVT.getStoreSizeInBits() != NewBW || 13534 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 13535 !TLI.isNarrowingProfitable(VT, NewVT))) { 13536 NewBW = NextPowerOf2(NewBW); 13537 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13538 } 13539 if (NewBW >= BitWidth) 13540 return SDValue(); 13541 13542 // If the lsb changed does not start at the type bitwidth boundary, 13543 // start at the previous one. 13544 if (ShAmt % NewBW) 13545 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 13546 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 13547 std::min(BitWidth, ShAmt + NewBW)); 13548 if ((Imm & Mask) == Imm) { 13549 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 13550 if (Opc == ISD::AND) 13551 NewImm ^= APInt::getAllOnesValue(NewBW); 13552 uint64_t PtrOff = ShAmt / 8; 13553 // For big endian targets, we need to adjust the offset to the pointer to 13554 // load the correct bytes. 13555 if (DAG.getDataLayout().isBigEndian()) 13556 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 13557 13558 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 13559 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 13560 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 13561 return SDValue(); 13562 13563 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 13564 Ptr.getValueType(), Ptr, 13565 DAG.getConstant(PtrOff, SDLoc(LD), 13566 Ptr.getValueType())); 13567 SDValue NewLD = 13568 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 13569 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 13570 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 13571 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 13572 DAG.getConstant(NewImm, SDLoc(Value), 13573 NewVT)); 13574 SDValue NewST = 13575 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 13576 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 13577 13578 AddToWorklist(NewPtr.getNode()); 13579 AddToWorklist(NewLD.getNode()); 13580 AddToWorklist(NewVal.getNode()); 13581 WorklistRemover DeadNodes(*this); 13582 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 13583 ++OpsNarrowed; 13584 return NewST; 13585 } 13586 } 13587 13588 return SDValue(); 13589 } 13590 13591 /// For a given floating point load / store pair, if the load value isn't used 13592 /// by any other operations, then consider transforming the pair to integer 13593 /// load / store operations if the target deems the transformation profitable. 13594 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 13595 StoreSDNode *ST = cast<StoreSDNode>(N); 13596 SDValue Chain = ST->getChain(); 13597 SDValue Value = ST->getValue(); 13598 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 13599 Value.hasOneUse() && 13600 Chain == SDValue(Value.getNode(), 1)) { 13601 LoadSDNode *LD = cast<LoadSDNode>(Value); 13602 EVT VT = LD->getMemoryVT(); 13603 if (!VT.isFloatingPoint() || 13604 VT != ST->getMemoryVT() || 13605 LD->isNonTemporal() || 13606 ST->isNonTemporal() || 13607 LD->getPointerInfo().getAddrSpace() != 0 || 13608 ST->getPointerInfo().getAddrSpace() != 0) 13609 return SDValue(); 13610 13611 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 13612 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 13613 !TLI.isOperationLegal(ISD::STORE, IntVT) || 13614 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 13615 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 13616 return SDValue(); 13617 13618 unsigned LDAlign = LD->getAlignment(); 13619 unsigned STAlign = ST->getAlignment(); 13620 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 13621 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 13622 if (LDAlign < ABIAlign || STAlign < ABIAlign) 13623 return SDValue(); 13624 13625 SDValue NewLD = 13626 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 13627 LD->getPointerInfo(), LDAlign); 13628 13629 SDValue NewST = 13630 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 13631 ST->getPointerInfo(), STAlign); 13632 13633 AddToWorklist(NewLD.getNode()); 13634 AddToWorklist(NewST.getNode()); 13635 WorklistRemover DeadNodes(*this); 13636 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 13637 ++LdStFP2Int; 13638 return NewST; 13639 } 13640 13641 return SDValue(); 13642 } 13643 13644 // This is a helper function for visitMUL to check the profitability 13645 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 13646 // MulNode is the original multiply, AddNode is (add x, c1), 13647 // and ConstNode is c2. 13648 // 13649 // If the (add x, c1) has multiple uses, we could increase 13650 // the number of adds if we make this transformation. 13651 // It would only be worth doing this if we can remove a 13652 // multiply in the process. Check for that here. 13653 // To illustrate: 13654 // (A + c1) * c3 13655 // (A + c2) * c3 13656 // We're checking for cases where we have common "c3 * A" expressions. 13657 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 13658 SDValue &AddNode, 13659 SDValue &ConstNode) { 13660 APInt Val; 13661 13662 // If the add only has one use, this would be OK to do. 13663 if (AddNode.getNode()->hasOneUse()) 13664 return true; 13665 13666 // Walk all the users of the constant with which we're multiplying. 13667 for (SDNode *Use : ConstNode->uses()) { 13668 if (Use == MulNode) // This use is the one we're on right now. Skip it. 13669 continue; 13670 13671 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 13672 SDNode *OtherOp; 13673 SDNode *MulVar = AddNode.getOperand(0).getNode(); 13674 13675 // OtherOp is what we're multiplying against the constant. 13676 if (Use->getOperand(0) == ConstNode) 13677 OtherOp = Use->getOperand(1).getNode(); 13678 else 13679 OtherOp = Use->getOperand(0).getNode(); 13680 13681 // Check to see if multiply is with the same operand of our "add". 13682 // 13683 // ConstNode = CONST 13684 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 13685 // ... 13686 // AddNode = (A + c1) <-- MulVar is A. 13687 // = AddNode * ConstNode <-- current visiting instruction. 13688 // 13689 // If we make this transformation, we will have a common 13690 // multiply (ConstNode * A) that we can save. 13691 if (OtherOp == MulVar) 13692 return true; 13693 13694 // Now check to see if a future expansion will give us a common 13695 // multiply. 13696 // 13697 // ConstNode = CONST 13698 // AddNode = (A + c1) 13699 // ... = AddNode * ConstNode <-- current visiting instruction. 13700 // ... 13701 // OtherOp = (A + c2) 13702 // Use = OtherOp * ConstNode <-- visiting Use. 13703 // 13704 // If we make this transformation, we will have a common 13705 // multiply (CONST * A) after we also do the same transformation 13706 // to the "t2" instruction. 13707 if (OtherOp->getOpcode() == ISD::ADD && 13708 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 13709 OtherOp->getOperand(0).getNode() == MulVar) 13710 return true; 13711 } 13712 } 13713 13714 // Didn't find a case where this would be profitable. 13715 return false; 13716 } 13717 13718 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 13719 unsigned NumStores) { 13720 SmallVector<SDValue, 8> Chains; 13721 SmallPtrSet<const SDNode *, 8> Visited; 13722 SDLoc StoreDL(StoreNodes[0].MemNode); 13723 13724 for (unsigned i = 0; i < NumStores; ++i) { 13725 Visited.insert(StoreNodes[i].MemNode); 13726 } 13727 13728 // don't include nodes that are children 13729 for (unsigned i = 0; i < NumStores; ++i) { 13730 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 13731 Chains.push_back(StoreNodes[i].MemNode->getChain()); 13732 } 13733 13734 assert(Chains.size() > 0 && "Chain should have generated a chain"); 13735 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 13736 } 13737 13738 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 13739 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 13740 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 13741 // Make sure we have something to merge. 13742 if (NumStores < 2) 13743 return false; 13744 13745 // The latest Node in the DAG. 13746 SDLoc DL(StoreNodes[0].MemNode); 13747 13748 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 13749 unsigned SizeInBits = NumStores * ElementSizeBits; 13750 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 13751 13752 EVT StoreTy; 13753 if (UseVector) { 13754 unsigned Elts = NumStores * NumMemElts; 13755 // Get the type for the merged vector store. 13756 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13757 } else 13758 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 13759 13760 SDValue StoredVal; 13761 if (UseVector) { 13762 if (IsConstantSrc) { 13763 SmallVector<SDValue, 8> BuildVector; 13764 for (unsigned I = 0; I != NumStores; ++I) { 13765 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 13766 SDValue Val = St->getValue(); 13767 // If constant is of the wrong type, convert it now. 13768 if (MemVT != Val.getValueType()) { 13769 Val = peekThroughBitcast(Val); 13770 // Deal with constants of wrong size. 13771 if (ElementSizeBits != Val.getValueSizeInBits()) { 13772 EVT IntMemVT = 13773 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 13774 if (isa<ConstantFPSDNode>(Val)) { 13775 // Not clear how to truncate FP values. 13776 return false; 13777 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 13778 Val = DAG.getConstant(C->getAPIntValue() 13779 .zextOrTrunc(Val.getValueSizeInBits()) 13780 .zextOrTrunc(ElementSizeBits), 13781 SDLoc(C), IntMemVT); 13782 } 13783 // Make sure correctly size type is the correct type. 13784 Val = DAG.getBitcast(MemVT, Val); 13785 } 13786 BuildVector.push_back(Val); 13787 } 13788 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 13789 : ISD::BUILD_VECTOR, 13790 DL, StoreTy, BuildVector); 13791 } else { 13792 SmallVector<SDValue, 8> Ops; 13793 for (unsigned i = 0; i < NumStores; ++i) { 13794 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13795 SDValue Val = peekThroughBitcast(St->getValue()); 13796 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 13797 // type MemVT. If the underlying value is not the correct 13798 // type, but it is an extraction of an appropriate vector we 13799 // can recast Val to be of the correct type. This may require 13800 // converting between EXTRACT_VECTOR_ELT and 13801 // EXTRACT_SUBVECTOR. 13802 if ((MemVT != Val.getValueType()) && 13803 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13804 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 13805 SDValue Vec = Val.getOperand(0); 13806 EVT MemVTScalarTy = MemVT.getScalarType(); 13807 // We may need to add a bitcast here to get types to line up. 13808 if (MemVTScalarTy != Vec.getValueType()) { 13809 unsigned Elts = Vec.getValueType().getSizeInBits() / 13810 MemVTScalarTy.getSizeInBits(); 13811 EVT NewVecTy = 13812 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 13813 Vec = DAG.getBitcast(NewVecTy, Vec); 13814 } 13815 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 13816 : ISD::EXTRACT_VECTOR_ELT; 13817 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1)); 13818 } 13819 Ops.push_back(Val); 13820 } 13821 13822 // Build the extracted vector elements back into a vector. 13823 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 13824 : ISD::BUILD_VECTOR, 13825 DL, StoreTy, Ops); 13826 } 13827 } else { 13828 // We should always use a vector store when merging extracted vector 13829 // elements, so this path implies a store of constants. 13830 assert(IsConstantSrc && "Merged vector elements should use vector store"); 13831 13832 APInt StoreInt(SizeInBits, 0); 13833 13834 // Construct a single integer constant which is made of the smaller 13835 // constant inputs. 13836 bool IsLE = DAG.getDataLayout().isLittleEndian(); 13837 for (unsigned i = 0; i < NumStores; ++i) { 13838 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 13839 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 13840 13841 SDValue Val = St->getValue(); 13842 Val = peekThroughBitcast(Val); 13843 StoreInt <<= ElementSizeBits; 13844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 13845 StoreInt |= C->getAPIntValue() 13846 .zextOrTrunc(ElementSizeBits) 13847 .zextOrTrunc(SizeInBits); 13848 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 13849 StoreInt |= C->getValueAPF() 13850 .bitcastToAPInt() 13851 .zextOrTrunc(ElementSizeBits) 13852 .zextOrTrunc(SizeInBits); 13853 // If fp truncation is necessary give up for now. 13854 if (MemVT.getSizeInBits() != ElementSizeBits) 13855 return false; 13856 } else { 13857 llvm_unreachable("Invalid constant element type"); 13858 } 13859 } 13860 13861 // Create the new Load and Store operations. 13862 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 13863 } 13864 13865 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13866 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 13867 13868 // make sure we use trunc store if it's necessary to be legal. 13869 SDValue NewStore; 13870 if (!UseTrunc) { 13871 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 13872 FirstInChain->getPointerInfo(), 13873 FirstInChain->getAlignment()); 13874 } else { // Must be realized as a trunc store 13875 EVT LegalizedStoredValTy = 13876 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 13877 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 13878 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 13879 SDValue ExtendedStoreVal = 13880 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 13881 LegalizedStoredValTy); 13882 NewStore = DAG.getTruncStore( 13883 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 13884 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 13885 FirstInChain->getAlignment(), 13886 FirstInChain->getMemOperand()->getFlags()); 13887 } 13888 13889 // Replace all merged stores with the new store. 13890 for (unsigned i = 0; i < NumStores; ++i) 13891 CombineTo(StoreNodes[i].MemNode, NewStore); 13892 13893 AddToWorklist(NewChain.getNode()); 13894 return true; 13895 } 13896 13897 void DAGCombiner::getStoreMergeCandidates( 13898 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 13899 SDNode *&RootNode) { 13900 // This holds the base pointer, index, and the offset in bytes from the base 13901 // pointer. 13902 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 13903 EVT MemVT = St->getMemoryVT(); 13904 13905 SDValue Val = peekThroughBitcast(St->getValue()); 13906 // We must have a base and an offset. 13907 if (!BasePtr.getBase().getNode()) 13908 return; 13909 13910 // Do not handle stores to undef base pointers. 13911 if (BasePtr.getBase().isUndef()) 13912 return; 13913 13914 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 13915 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13916 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13917 bool IsLoadSrc = isa<LoadSDNode>(Val); 13918 BaseIndexOffset LBasePtr; 13919 // Match on loadbaseptr if relevant. 13920 EVT LoadVT; 13921 if (IsLoadSrc) { 13922 auto *Ld = cast<LoadSDNode>(Val); 13923 LBasePtr = BaseIndexOffset::match(Ld, DAG); 13924 LoadVT = Ld->getMemoryVT(); 13925 // Load and store should be the same type. 13926 if (MemVT != LoadVT) 13927 return; 13928 // Loads must only have one use. 13929 if (!Ld->hasNUsesOfValue(1, 0)) 13930 return; 13931 // The memory operands must not be volatile. 13932 if (Ld->isVolatile() || Ld->isIndexed()) 13933 return; 13934 } 13935 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 13936 int64_t &Offset) -> bool { 13937 if (Other->isVolatile() || Other->isIndexed()) 13938 return false; 13939 SDValue Val = peekThroughBitcast(Other->getValue()); 13940 // Allow merging constants of different types as integers. 13941 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 13942 : Other->getMemoryVT() != MemVT; 13943 if (IsLoadSrc) { 13944 if (NoTypeMatch) 13945 return false; 13946 // The Load's Base Ptr must also match 13947 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 13948 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 13949 if (LoadVT != OtherLd->getMemoryVT()) 13950 return false; 13951 // Loads must only have one use. 13952 if (!OtherLd->hasNUsesOfValue(1, 0)) 13953 return false; 13954 // The memory operands must not be volatile. 13955 if (OtherLd->isVolatile() || OtherLd->isIndexed()) 13956 return false; 13957 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 13958 return false; 13959 } else 13960 return false; 13961 } 13962 if (IsConstantSrc) { 13963 if (NoTypeMatch) 13964 return false; 13965 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 13966 return false; 13967 } 13968 if (IsExtractVecSrc) { 13969 // Do not merge truncated stores here. 13970 if (Other->isTruncatingStore()) 13971 return false; 13972 if (!MemVT.bitsEq(Val.getValueType())) 13973 return false; 13974 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13975 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13976 return false; 13977 } 13978 Ptr = BaseIndexOffset::match(Other, DAG); 13979 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 13980 }; 13981 13982 // We looking for a root node which is an ancestor to all mergable 13983 // stores. We search up through a load, to our root and then down 13984 // through all children. For instance we will find Store{1,2,3} if 13985 // St is Store1, Store2. or Store3 where the root is not a load 13986 // which always true for nonvolatile ops. TODO: Expand 13987 // the search to find all valid candidates through multiple layers of loads. 13988 // 13989 // Root 13990 // |-------|-------| 13991 // Load Load Store3 13992 // | | 13993 // Store1 Store2 13994 // 13995 // FIXME: We should be able to climb and 13996 // descend TokenFactors to find candidates as well. 13997 13998 RootNode = St->getChain().getNode(); 13999 14000 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 14001 RootNode = Ldn->getChain().getNode(); 14002 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14003 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 14004 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 14005 if (I2.getOperandNo() == 0) 14006 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 14007 BaseIndexOffset Ptr; 14008 int64_t PtrDiff; 14009 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14010 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14011 } 14012 } else 14013 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14014 if (I.getOperandNo() == 0) 14015 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 14016 BaseIndexOffset Ptr; 14017 int64_t PtrDiff; 14018 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14019 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14020 } 14021 } 14022 14023 // We need to check that merging these stores does not cause a loop in 14024 // the DAG. Any store candidate may depend on another candidate 14025 // indirectly through its operand (we already consider dependencies 14026 // through the chain). Check in parallel by searching up from 14027 // non-chain operands of candidates. 14028 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 14029 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 14030 SDNode *RootNode) { 14031 // FIXME: We should be able to truncate a full search of 14032 // predecessors by doing a BFS and keeping tabs the originating 14033 // stores from which worklist nodes come from in a similar way to 14034 // TokenFactor simplfication. 14035 14036 SmallPtrSet<const SDNode *, 32> Visited; 14037 SmallVector<const SDNode *, 8> Worklist; 14038 14039 // RootNode is a predecessor to all candidates so we need not search 14040 // past it. Add RootNode (peeking through TokenFactors). Do not count 14041 // these towards size check. 14042 14043 Worklist.push_back(RootNode); 14044 while (!Worklist.empty()) { 14045 auto N = Worklist.pop_back_val(); 14046 if (!Visited.insert(N).second) 14047 continue; // Already present in Visited. 14048 if (N->getOpcode() == ISD::TokenFactor) { 14049 for (SDValue Op : N->ops()) 14050 Worklist.push_back(Op.getNode()); 14051 } 14052 } 14053 14054 // Don't count pruning nodes towards max. 14055 unsigned int Max = 1024 + Visited.size(); 14056 // Search Ops of store candidates. 14057 for (unsigned i = 0; i < NumStores; ++i) { 14058 SDNode *N = StoreNodes[i].MemNode; 14059 // Of the 4 Store Operands: 14060 // * Chain (Op 0) -> We have already considered these 14061 // in candidate selection and can be 14062 // safely ignored 14063 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 14064 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant 14065 // and so no cycles are possible. 14066 // * (Op 3) -> appears to always be undef. Cannot be source of cycle. 14067 // 14068 // Thus we need only check predecessors of the value operands. 14069 auto *Op = N->getOperand(1).getNode(); 14070 if (Visited.insert(Op).second) 14071 Worklist.push_back(Op); 14072 } 14073 // Search through DAG. We can stop early if we find a store node. 14074 for (unsigned i = 0; i < NumStores; ++i) 14075 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 14076 Max)) 14077 return false; 14078 return true; 14079 } 14080 14081 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 14082 if (OptLevel == CodeGenOpt::None) 14083 return false; 14084 14085 EVT MemVT = St->getMemoryVT(); 14086 int64_t ElementSizeBytes = MemVT.getStoreSize(); 14087 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14088 14089 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 14090 return false; 14091 14092 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 14093 Attribute::NoImplicitFloat); 14094 14095 // This function cannot currently deal with non-byte-sized memory sizes. 14096 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 14097 return false; 14098 14099 if (!MemVT.isSimple()) 14100 return false; 14101 14102 // Perform an early exit check. Do not bother looking at stored values that 14103 // are not constants, loads, or extracted vector elements. 14104 SDValue StoredVal = peekThroughBitcast(St->getValue()); 14105 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 14106 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 14107 isa<ConstantFPSDNode>(StoredVal); 14108 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14109 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14110 14111 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 14112 return false; 14113 14114 SmallVector<MemOpLink, 8> StoreNodes; 14115 SDNode *RootNode; 14116 // Find potential store merge candidates by searching through chain sub-DAG 14117 getStoreMergeCandidates(St, StoreNodes, RootNode); 14118 14119 // Check if there is anything to merge. 14120 if (StoreNodes.size() < 2) 14121 return false; 14122 14123 // Sort the memory operands according to their distance from the 14124 // base pointer. 14125 llvm::sort(StoreNodes.begin(), StoreNodes.end(), 14126 [](MemOpLink LHS, MemOpLink RHS) { 14127 return LHS.OffsetFromBase < RHS.OffsetFromBase; 14128 }); 14129 14130 // Store Merge attempts to merge the lowest stores. This generally 14131 // works out as if successful, as the remaining stores are checked 14132 // after the first collection of stores is merged. However, in the 14133 // case that a non-mergeable store is found first, e.g., {p[-2], 14134 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 14135 // mergeable cases. To prevent this, we prune such stores from the 14136 // front of StoreNodes here. 14137 14138 bool RV = false; 14139 while (StoreNodes.size() > 1) { 14140 unsigned StartIdx = 0; 14141 while ((StartIdx + 1 < StoreNodes.size()) && 14142 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 14143 StoreNodes[StartIdx + 1].OffsetFromBase) 14144 ++StartIdx; 14145 14146 // Bail if we don't have enough candidates to merge. 14147 if (StartIdx + 1 >= StoreNodes.size()) 14148 return RV; 14149 14150 if (StartIdx) 14151 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 14152 14153 // Scan the memory operations on the chain and find the first 14154 // non-consecutive store memory address. 14155 unsigned NumConsecutiveStores = 1; 14156 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 14157 // Check that the addresses are consecutive starting from the second 14158 // element in the list of stores. 14159 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 14160 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 14161 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14162 break; 14163 NumConsecutiveStores = i + 1; 14164 } 14165 14166 if (NumConsecutiveStores < 2) { 14167 StoreNodes.erase(StoreNodes.begin(), 14168 StoreNodes.begin() + NumConsecutiveStores); 14169 continue; 14170 } 14171 14172 // The node with the lowest store address. 14173 LLVMContext &Context = *DAG.getContext(); 14174 const DataLayout &DL = DAG.getDataLayout(); 14175 14176 // Store the constants into memory as one consecutive store. 14177 if (IsConstantSrc) { 14178 while (NumConsecutiveStores >= 2) { 14179 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14180 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14181 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14182 unsigned LastLegalType = 1; 14183 unsigned LastLegalVectorType = 1; 14184 bool LastIntegerTrunc = false; 14185 bool NonZero = false; 14186 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 14187 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14188 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 14189 SDValue StoredVal = ST->getValue(); 14190 bool IsElementZero = false; 14191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 14192 IsElementZero = C->isNullValue(); 14193 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 14194 IsElementZero = C->getConstantFPValue()->isNullValue(); 14195 if (IsElementZero) { 14196 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 14197 FirstZeroAfterNonZero = i; 14198 } 14199 NonZero |= !IsElementZero; 14200 14201 // Find a legal type for the constant store. 14202 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14203 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14204 bool IsFast = false; 14205 14206 // Break early when size is too large to be legal. 14207 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14208 break; 14209 14210 if (TLI.isTypeLegal(StoreTy) && 14211 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14212 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14213 FirstStoreAlign, &IsFast) && 14214 IsFast) { 14215 LastIntegerTrunc = false; 14216 LastLegalType = i + 1; 14217 // Or check whether a truncstore is legal. 14218 } else if (TLI.getTypeAction(Context, StoreTy) == 14219 TargetLowering::TypePromoteInteger) { 14220 EVT LegalizedStoredValTy = 14221 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 14222 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14223 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14224 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14225 FirstStoreAlign, &IsFast) && 14226 IsFast) { 14227 LastIntegerTrunc = true; 14228 LastLegalType = i + 1; 14229 } 14230 } 14231 14232 // We only use vectors if the constant is known to be zero or the 14233 // target allows it and the function is not marked with the 14234 // noimplicitfloat attribute. 14235 if ((!NonZero || 14236 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 14237 !NoVectors) { 14238 // Find a legal type for the vector store. 14239 unsigned Elts = (i + 1) * NumMemElts; 14240 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14241 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 14242 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14243 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14244 FirstStoreAlign, &IsFast) && 14245 IsFast) 14246 LastLegalVectorType = i + 1; 14247 } 14248 } 14249 14250 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 14251 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 14252 14253 // Check if we found a legal integer type that creates a meaningful 14254 // merge. 14255 if (NumElem < 2) { 14256 // We know that candidate stores are in order and of correct 14257 // shape. While there is no mergeable sequence from the 14258 // beginning one may start later in the sequence. The only 14259 // reason a merge of size N could have failed where another of 14260 // the same size would not have, is if the alignment has 14261 // improved or we've dropped a non-zero value. Drop as many 14262 // candidates as we can here. 14263 unsigned NumSkip = 1; 14264 while ( 14265 (NumSkip < NumConsecutiveStores) && 14266 (NumSkip < FirstZeroAfterNonZero) && 14267 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14268 NumSkip++; 14269 14270 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14271 NumConsecutiveStores -= NumSkip; 14272 continue; 14273 } 14274 14275 // Check that we can merge these candidates without causing a cycle. 14276 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14277 RootNode)) { 14278 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14279 NumConsecutiveStores -= NumElem; 14280 continue; 14281 } 14282 14283 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true, 14284 UseVector, LastIntegerTrunc); 14285 14286 // Remove merged stores for next iteration. 14287 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14288 NumConsecutiveStores -= NumElem; 14289 } 14290 continue; 14291 } 14292 14293 // When extracting multiple vector elements, try to store them 14294 // in one vector store rather than a sequence of scalar stores. 14295 if (IsExtractVecSrc) { 14296 // Loop on Consecutive Stores on success. 14297 while (NumConsecutiveStores >= 2) { 14298 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14299 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14300 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14301 unsigned NumStoresToMerge = 1; 14302 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14303 // Find a legal type for the vector store. 14304 unsigned Elts = (i + 1) * NumMemElts; 14305 EVT Ty = 14306 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 14307 bool IsFast; 14308 14309 // Break early when size is too large to be legal. 14310 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 14311 break; 14312 14313 if (TLI.isTypeLegal(Ty) && 14314 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14315 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14316 FirstStoreAlign, &IsFast) && 14317 IsFast) 14318 NumStoresToMerge = i + 1; 14319 } 14320 14321 // Check if we found a legal integer type creating a meaningful 14322 // merge. 14323 if (NumStoresToMerge < 2) { 14324 // We know that candidate stores are in order and of correct 14325 // shape. While there is no mergeable sequence from the 14326 // beginning one may start later in the sequence. The only 14327 // reason a merge of size N could have failed where another of 14328 // the same size would not have, is if the alignment has 14329 // improved. Drop as many candidates as we can here. 14330 unsigned NumSkip = 1; 14331 while ( 14332 (NumSkip < NumConsecutiveStores) && 14333 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14334 NumSkip++; 14335 14336 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14337 NumConsecutiveStores -= NumSkip; 14338 continue; 14339 } 14340 14341 // Check that we can merge these candidates without causing a cycle. 14342 if (!checkMergeStoreCandidatesForDependencies( 14343 StoreNodes, NumStoresToMerge, RootNode)) { 14344 StoreNodes.erase(StoreNodes.begin(), 14345 StoreNodes.begin() + NumStoresToMerge); 14346 NumConsecutiveStores -= NumStoresToMerge; 14347 continue; 14348 } 14349 14350 RV |= MergeStoresOfConstantsOrVecElts( 14351 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 14352 14353 StoreNodes.erase(StoreNodes.begin(), 14354 StoreNodes.begin() + NumStoresToMerge); 14355 NumConsecutiveStores -= NumStoresToMerge; 14356 } 14357 continue; 14358 } 14359 14360 // Below we handle the case of multiple consecutive stores that 14361 // come from multiple consecutive loads. We merge them into a single 14362 // wide load and a single wide store. 14363 14364 // Look for load nodes which are used by the stored values. 14365 SmallVector<MemOpLink, 8> LoadNodes; 14366 14367 // Find acceptable loads. Loads need to have the same chain (token factor), 14368 // must not be zext, volatile, indexed, and they must be consecutive. 14369 BaseIndexOffset LdBasePtr; 14370 14371 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14372 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 14373 SDValue Val = peekThroughBitcast(St->getValue()); 14374 LoadSDNode *Ld = cast<LoadSDNode>(Val); 14375 14376 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 14377 // If this is not the first ptr that we check. 14378 int64_t LdOffset = 0; 14379 if (LdBasePtr.getBase().getNode()) { 14380 // The base ptr must be the same. 14381 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 14382 break; 14383 } else { 14384 // Check that all other base pointers are the same as this one. 14385 LdBasePtr = LdPtr; 14386 } 14387 14388 // We found a potential memory operand to merge. 14389 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 14390 } 14391 14392 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 14393 // If we have load/store pair instructions and we only have two values, 14394 // don't bother merging. 14395 unsigned RequiredAlignment; 14396 if (LoadNodes.size() == 2 && 14397 TLI.hasPairedLoad(MemVT, RequiredAlignment) && 14398 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 14399 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 14400 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 14401 break; 14402 } 14403 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14404 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14405 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14406 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 14407 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 14408 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 14409 14410 // Scan the memory operations on the chain and find the first 14411 // non-consecutive load memory address. These variables hold the index in 14412 // the store node array. 14413 14414 unsigned LastConsecutiveLoad = 1; 14415 14416 // This variable refers to the size and not index in the array. 14417 unsigned LastLegalVectorType = 1; 14418 unsigned LastLegalIntegerType = 1; 14419 bool isDereferenceable = true; 14420 bool DoIntegerTruncate = false; 14421 StartAddress = LoadNodes[0].OffsetFromBase; 14422 SDValue FirstChain = FirstLoad->getChain(); 14423 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 14424 // All loads must share the same chain. 14425 if (LoadNodes[i].MemNode->getChain() != FirstChain) 14426 break; 14427 14428 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 14429 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14430 break; 14431 LastConsecutiveLoad = i; 14432 14433 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 14434 isDereferenceable = false; 14435 14436 // Find a legal type for the vector store. 14437 unsigned Elts = (i + 1) * NumMemElts; 14438 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14439 14440 // Break early when size is too large to be legal. 14441 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14442 break; 14443 14444 bool IsFastSt, IsFastLd; 14445 if (TLI.isTypeLegal(StoreTy) && 14446 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14447 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14448 FirstStoreAlign, &IsFastSt) && 14449 IsFastSt && 14450 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14451 FirstLoadAlign, &IsFastLd) && 14452 IsFastLd) { 14453 LastLegalVectorType = i + 1; 14454 } 14455 14456 // Find a legal type for the integer store. 14457 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14458 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14459 if (TLI.isTypeLegal(StoreTy) && 14460 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14461 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14462 FirstStoreAlign, &IsFastSt) && 14463 IsFastSt && 14464 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14465 FirstLoadAlign, &IsFastLd) && 14466 IsFastLd) { 14467 LastLegalIntegerType = i + 1; 14468 DoIntegerTruncate = false; 14469 // Or check whether a truncstore and extload is legal. 14470 } else if (TLI.getTypeAction(Context, StoreTy) == 14471 TargetLowering::TypePromoteInteger) { 14472 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 14473 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14474 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14475 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, 14476 StoreTy) && 14477 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, 14478 StoreTy) && 14479 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 14480 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14481 FirstStoreAlign, &IsFastSt) && 14482 IsFastSt && 14483 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14484 FirstLoadAlign, &IsFastLd) && 14485 IsFastLd) { 14486 LastLegalIntegerType = i + 1; 14487 DoIntegerTruncate = true; 14488 } 14489 } 14490 } 14491 14492 // Only use vector types if the vector type is larger than the integer 14493 // type. If they are the same, use integers. 14494 bool UseVectorTy = 14495 LastLegalVectorType > LastLegalIntegerType && !NoVectors; 14496 unsigned LastLegalType = 14497 std::max(LastLegalVectorType, LastLegalIntegerType); 14498 14499 // We add +1 here because the LastXXX variables refer to location while 14500 // the NumElem refers to array/index size. 14501 unsigned NumElem = 14502 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 14503 NumElem = std::min(LastLegalType, NumElem); 14504 14505 if (NumElem < 2) { 14506 // We know that candidate stores are in order and of correct 14507 // shape. While there is no mergeable sequence from the 14508 // beginning one may start later in the sequence. The only 14509 // reason a merge of size N could have failed where another of 14510 // the same size would not have is if the alignment or either 14511 // the load or store has improved. Drop as many candidates as we 14512 // can here. 14513 unsigned NumSkip = 1; 14514 while ((NumSkip < LoadNodes.size()) && 14515 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 14516 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14517 NumSkip++; 14518 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14519 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 14520 NumConsecutiveStores -= NumSkip; 14521 continue; 14522 } 14523 14524 // Check that we can merge these candidates without causing a cycle. 14525 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14526 RootNode)) { 14527 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14528 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14529 NumConsecutiveStores -= NumElem; 14530 continue; 14531 } 14532 14533 // Find if it is better to use vectors or integers to load and store 14534 // to memory. 14535 EVT JointMemOpVT; 14536 if (UseVectorTy) { 14537 // Find a legal type for the vector store. 14538 unsigned Elts = NumElem * NumMemElts; 14539 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14540 } else { 14541 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 14542 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 14543 } 14544 14545 SDLoc LoadDL(LoadNodes[0].MemNode); 14546 SDLoc StoreDL(StoreNodes[0].MemNode); 14547 14548 // The merged loads are required to have the same incoming chain, so 14549 // using the first's chain is acceptable. 14550 14551 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 14552 AddToWorklist(NewStoreChain.getNode()); 14553 14554 MachineMemOperand::Flags MMOFlags = 14555 isDereferenceable ? MachineMemOperand::MODereferenceable 14556 : MachineMemOperand::MONone; 14557 14558 SDValue NewLoad, NewStore; 14559 if (UseVectorTy || !DoIntegerTruncate) { 14560 NewLoad = 14561 DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 14562 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 14563 FirstLoadAlign, MMOFlags); 14564 NewStore = DAG.getStore( 14565 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 14566 FirstInChain->getPointerInfo(), FirstStoreAlign); 14567 } else { // This must be the truncstore/extload case 14568 EVT ExtendedTy = 14569 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 14570 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 14571 FirstLoad->getChain(), FirstLoad->getBasePtr(), 14572 FirstLoad->getPointerInfo(), JointMemOpVT, 14573 FirstLoadAlign, MMOFlags); 14574 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 14575 FirstInChain->getBasePtr(), 14576 FirstInChain->getPointerInfo(), 14577 JointMemOpVT, FirstInChain->getAlignment(), 14578 FirstInChain->getMemOperand()->getFlags()); 14579 } 14580 14581 // Transfer chain users from old loads to the new load. 14582 for (unsigned i = 0; i < NumElem; ++i) { 14583 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 14584 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 14585 SDValue(NewLoad.getNode(), 1)); 14586 } 14587 14588 // Replace the all stores with the new store. Recursively remove 14589 // corresponding value if its no longer used. 14590 for (unsigned i = 0; i < NumElem; ++i) { 14591 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 14592 CombineTo(StoreNodes[i].MemNode, NewStore); 14593 if (Val.getNode()->use_empty()) 14594 recursivelyDeleteUnusedNodes(Val.getNode()); 14595 } 14596 14597 RV = true; 14598 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14599 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14600 NumConsecutiveStores -= NumElem; 14601 } 14602 } 14603 return RV; 14604 } 14605 14606 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 14607 SDLoc SL(ST); 14608 SDValue ReplStore; 14609 14610 // Replace the chain to avoid dependency. 14611 if (ST->isTruncatingStore()) { 14612 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 14613 ST->getBasePtr(), ST->getMemoryVT(), 14614 ST->getMemOperand()); 14615 } else { 14616 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 14617 ST->getMemOperand()); 14618 } 14619 14620 // Create token to keep both nodes around. 14621 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 14622 MVT::Other, ST->getChain(), ReplStore); 14623 14624 // Make sure the new and old chains are cleaned up. 14625 AddToWorklist(Token.getNode()); 14626 14627 // Don't add users to work list. 14628 return CombineTo(ST, Token, false); 14629 } 14630 14631 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 14632 SDValue Value = ST->getValue(); 14633 if (Value.getOpcode() == ISD::TargetConstantFP) 14634 return SDValue(); 14635 14636 SDLoc DL(ST); 14637 14638 SDValue Chain = ST->getChain(); 14639 SDValue Ptr = ST->getBasePtr(); 14640 14641 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 14642 14643 // NOTE: If the original store is volatile, this transform must not increase 14644 // the number of stores. For example, on x86-32 an f64 can be stored in one 14645 // processor operation but an i64 (which is not legal) requires two. So the 14646 // transform should not be done in this case. 14647 14648 SDValue Tmp; 14649 switch (CFP->getSimpleValueType(0).SimpleTy) { 14650 default: 14651 llvm_unreachable("Unknown FP type"); 14652 case MVT::f16: // We don't do this for these yet. 14653 case MVT::f80: 14654 case MVT::f128: 14655 case MVT::ppcf128: 14656 return SDValue(); 14657 case MVT::f32: 14658 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 14659 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14660 ; 14661 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 14662 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 14663 MVT::i32); 14664 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 14665 } 14666 14667 return SDValue(); 14668 case MVT::f64: 14669 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 14670 !ST->isVolatile()) || 14671 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 14672 ; 14673 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 14674 getZExtValue(), SDLoc(CFP), MVT::i64); 14675 return DAG.getStore(Chain, DL, Tmp, 14676 Ptr, ST->getMemOperand()); 14677 } 14678 14679 if (!ST->isVolatile() && 14680 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14681 // Many FP stores are not made apparent until after legalize, e.g. for 14682 // argument passing. Since this is so common, custom legalize the 14683 // 64-bit integer store into two 32-bit stores. 14684 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 14685 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 14686 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 14687 if (DAG.getDataLayout().isBigEndian()) 14688 std::swap(Lo, Hi); 14689 14690 unsigned Alignment = ST->getAlignment(); 14691 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 14692 AAMDNodes AAInfo = ST->getAAInfo(); 14693 14694 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14695 ST->getAlignment(), MMOFlags, AAInfo); 14696 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14697 DAG.getConstant(4, DL, Ptr.getValueType())); 14698 Alignment = MinAlign(Alignment, 4U); 14699 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 14700 ST->getPointerInfo().getWithOffset(4), 14701 Alignment, MMOFlags, AAInfo); 14702 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 14703 St0, St1); 14704 } 14705 14706 return SDValue(); 14707 } 14708 } 14709 14710 SDValue DAGCombiner::visitSTORE(SDNode *N) { 14711 StoreSDNode *ST = cast<StoreSDNode>(N); 14712 SDValue Chain = ST->getChain(); 14713 SDValue Value = ST->getValue(); 14714 SDValue Ptr = ST->getBasePtr(); 14715 14716 // If this is a store of a bit convert, store the input value if the 14717 // resultant store does not need a higher alignment than the original. 14718 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 14719 ST->isUnindexed()) { 14720 EVT SVT = Value.getOperand(0).getValueType(); 14721 // If the store is volatile, we only want to change the store type if the 14722 // resulting store is legal. Otherwise we might increase the number of 14723 // memory accesses. We don't care if the original type was legal or not 14724 // as we assume software couldn't rely on the number of accesses of an 14725 // illegal type. 14726 if (((!LegalOperations && !ST->isVolatile()) || 14727 TLI.isOperationLegal(ISD::STORE, SVT)) && 14728 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 14729 unsigned OrigAlign = ST->getAlignment(); 14730 bool Fast = false; 14731 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 14732 ST->getAddressSpace(), OrigAlign, &Fast) && 14733 Fast) { 14734 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 14735 ST->getPointerInfo(), OrigAlign, 14736 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 14737 } 14738 } 14739 } 14740 14741 // Turn 'store undef, Ptr' -> nothing. 14742 if (Value.isUndef() && ST->isUnindexed()) 14743 return Chain; 14744 14745 // Try to infer better alignment information than the store already has. 14746 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 14747 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 14748 if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) { 14749 SDValue NewStore = 14750 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 14751 ST->getMemoryVT(), Align, 14752 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 14753 // NewStore will always be N as we are only refining the alignment 14754 assert(NewStore.getNode() == N); 14755 (void)NewStore; 14756 } 14757 } 14758 } 14759 14760 // Try transforming a pair floating point load / store ops to integer 14761 // load / store ops. 14762 if (SDValue NewST = TransformFPLoadStorePair(N)) 14763 return NewST; 14764 14765 if (ST->isUnindexed()) { 14766 // Walk up chain skipping non-aliasing memory nodes, on this store and any 14767 // adjacent stores. 14768 if (findBetterNeighborChains(ST)) { 14769 // replaceStoreChain uses CombineTo, which handled all of the worklist 14770 // manipulation. Return the original node to not do anything else. 14771 return SDValue(ST, 0); 14772 } 14773 Chain = ST->getChain(); 14774 } 14775 14776 // FIXME: is there such a thing as a truncating indexed store? 14777 if (ST->isTruncatingStore() && ST->isUnindexed() && 14778 Value.getValueType().isInteger()) { 14779 // See if we can simplify the input to this truncstore with knowledge that 14780 // only the low bits are being used. For example: 14781 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 14782 SDValue Shorter = DAG.GetDemandedBits( 14783 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 14784 ST->getMemoryVT().getScalarSizeInBits())); 14785 AddToWorklist(Value.getNode()); 14786 if (Shorter.getNode()) 14787 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 14788 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 14789 14790 // Otherwise, see if we can simplify the operation with 14791 // SimplifyDemandedBits, which only works if the value has a single use. 14792 if (SimplifyDemandedBits( 14793 Value, 14794 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 14795 ST->getMemoryVT().getScalarSizeInBits()))) { 14796 // Re-visit the store if anything changed and the store hasn't been merged 14797 // with another node (N is deleted) SimplifyDemandedBits will add Value's 14798 // node back to the worklist if necessary, but we also need to re-visit 14799 // the Store node itself. 14800 if (N->getOpcode() != ISD::DELETED_NODE) 14801 AddToWorklist(N); 14802 return SDValue(N, 0); 14803 } 14804 } 14805 14806 // If this is a load followed by a store to the same location, then the store 14807 // is dead/noop. 14808 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 14809 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 14810 ST->isUnindexed() && !ST->isVolatile() && 14811 // There can't be any side effects between the load and store, such as 14812 // a call or store. 14813 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 14814 // The store is dead, remove it. 14815 return Chain; 14816 } 14817 } 14818 14819 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 14820 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 14821 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 14822 ST->getMemoryVT() == ST1->getMemoryVT()) { 14823 // If this is a store followed by a store with the same value to the same 14824 // location, then the store is dead/noop. 14825 if (ST1->getValue() == Value) { 14826 // The store is dead, remove it. 14827 return Chain; 14828 } 14829 14830 // If this is a store who's preceeding store to the same location 14831 // and no one other node is chained to that store we can effectively 14832 // drop the store. Do not remove stores to undef as they may be used as 14833 // data sinks. 14834 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 14835 !ST1->getBasePtr().isUndef()) { 14836 // ST1 is fully overwritten and can be elided. Combine with it's chain 14837 // value. 14838 CombineTo(ST1, ST1->getChain()); 14839 return SDValue(); 14840 } 14841 } 14842 } 14843 14844 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 14845 // truncating store. We can do this even if this is already a truncstore. 14846 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 14847 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 14848 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 14849 ST->getMemoryVT())) { 14850 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 14851 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 14852 } 14853 14854 // Always perform this optimization before types are legal. If the target 14855 // prefers, also try this after legalization to catch stores that were created 14856 // by intrinsics or other nodes. 14857 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 14858 while (true) { 14859 // There can be multiple store sequences on the same chain. 14860 // Keep trying to merge store sequences until we are unable to do so 14861 // or until we merge the last store on the chain. 14862 bool Changed = MergeConsecutiveStores(ST); 14863 if (!Changed) break; 14864 // Return N as merge only uses CombineTo and no worklist clean 14865 // up is necessary. 14866 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 14867 return SDValue(N, 0); 14868 } 14869 } 14870 14871 // Try transforming N to an indexed store. 14872 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 14873 return SDValue(N, 0); 14874 14875 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 14876 // 14877 // Make sure to do this only after attempting to merge stores in order to 14878 // avoid changing the types of some subset of stores due to visit order, 14879 // preventing their merging. 14880 if (isa<ConstantFPSDNode>(ST->getValue())) { 14881 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 14882 return NewSt; 14883 } 14884 14885 if (SDValue NewSt = splitMergedValStore(ST)) 14886 return NewSt; 14887 14888 return ReduceLoadOpStoreWidth(N); 14889 } 14890 14891 /// For the instruction sequence of store below, F and I values 14892 /// are bundled together as an i64 value before being stored into memory. 14893 /// Sometimes it is more efficent to generate separate stores for F and I, 14894 /// which can remove the bitwise instructions or sink them to colder places. 14895 /// 14896 /// (store (or (zext (bitcast F to i32) to i64), 14897 /// (shl (zext I to i64), 32)), addr) --> 14898 /// (store F, addr) and (store I, addr+4) 14899 /// 14900 /// Similarly, splitting for other merged store can also be beneficial, like: 14901 /// For pair of {i32, i32}, i64 store --> two i32 stores. 14902 /// For pair of {i32, i16}, i64 store --> two i32 stores. 14903 /// For pair of {i16, i16}, i32 store --> two i16 stores. 14904 /// For pair of {i16, i8}, i32 store --> two i16 stores. 14905 /// For pair of {i8, i8}, i16 store --> two i8 stores. 14906 /// 14907 /// We allow each target to determine specifically which kind of splitting is 14908 /// supported. 14909 /// 14910 /// The store patterns are commonly seen from the simple code snippet below 14911 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 14912 /// void goo(const std::pair<int, float> &); 14913 /// hoo() { 14914 /// ... 14915 /// goo(std::make_pair(tmp, ftmp)); 14916 /// ... 14917 /// } 14918 /// 14919 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 14920 if (OptLevel == CodeGenOpt::None) 14921 return SDValue(); 14922 14923 SDValue Val = ST->getValue(); 14924 SDLoc DL(ST); 14925 14926 // Match OR operand. 14927 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 14928 return SDValue(); 14929 14930 // Match SHL operand and get Lower and Higher parts of Val. 14931 SDValue Op1 = Val.getOperand(0); 14932 SDValue Op2 = Val.getOperand(1); 14933 SDValue Lo, Hi; 14934 if (Op1.getOpcode() != ISD::SHL) { 14935 std::swap(Op1, Op2); 14936 if (Op1.getOpcode() != ISD::SHL) 14937 return SDValue(); 14938 } 14939 Lo = Op2; 14940 Hi = Op1.getOperand(0); 14941 if (!Op1.hasOneUse()) 14942 return SDValue(); 14943 14944 // Match shift amount to HalfValBitSize. 14945 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 14946 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 14947 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 14948 return SDValue(); 14949 14950 // Lo and Hi are zero-extended from int with size less equal than 32 14951 // to i64. 14952 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 14953 !Lo.getOperand(0).getValueType().isScalarInteger() || 14954 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 14955 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 14956 !Hi.getOperand(0).getValueType().isScalarInteger() || 14957 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 14958 return SDValue(); 14959 14960 // Use the EVT of low and high parts before bitcast as the input 14961 // of target query. 14962 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 14963 ? Lo.getOperand(0).getValueType() 14964 : Lo.getValueType(); 14965 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 14966 ? Hi.getOperand(0).getValueType() 14967 : Hi.getValueType(); 14968 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 14969 return SDValue(); 14970 14971 // Start to split store. 14972 unsigned Alignment = ST->getAlignment(); 14973 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 14974 AAMDNodes AAInfo = ST->getAAInfo(); 14975 14976 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 14977 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 14978 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 14979 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 14980 14981 SDValue Chain = ST->getChain(); 14982 SDValue Ptr = ST->getBasePtr(); 14983 // Lower value store. 14984 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14985 ST->getAlignment(), MMOFlags, AAInfo); 14986 Ptr = 14987 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14988 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 14989 // Higher value store. 14990 SDValue St1 = 14991 DAG.getStore(St0, DL, Hi, Ptr, 14992 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 14993 Alignment / 2, MMOFlags, AAInfo); 14994 return St1; 14995 } 14996 14997 /// Convert a disguised subvector insertion into a shuffle: 14998 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 14999 /// bitcast(shuffle (bitcast V), (extended X), Mask) 15000 /// Note: We do not use an insert_subvector node because that requires a legal 15001 /// subvector type. 15002 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 15003 SDValue InsertVal = N->getOperand(1); 15004 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 15005 !InsertVal.getOperand(0).getValueType().isVector()) 15006 return SDValue(); 15007 15008 SDValue SubVec = InsertVal.getOperand(0); 15009 SDValue DestVec = N->getOperand(0); 15010 EVT SubVecVT = SubVec.getValueType(); 15011 EVT VT = DestVec.getValueType(); 15012 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 15013 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 15014 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 15015 15016 // Step 1: Create a shuffle mask that implements this insert operation. The 15017 // vector that we are inserting into will be operand 0 of the shuffle, so 15018 // those elements are just 'i'. The inserted subvector is in the first 15019 // positions of operand 1 of the shuffle. Example: 15020 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 15021 SmallVector<int, 16> Mask(NumMaskVals); 15022 for (unsigned i = 0; i != NumMaskVals; ++i) { 15023 if (i / NumSrcElts == InsIndex) 15024 Mask[i] = (i % NumSrcElts) + NumMaskVals; 15025 else 15026 Mask[i] = i; 15027 } 15028 15029 // Bail out if the target can not handle the shuffle we want to create. 15030 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 15031 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 15032 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 15033 return SDValue(); 15034 15035 // Step 2: Create a wide vector from the inserted source vector by appending 15036 // undefined elements. This is the same size as our destination vector. 15037 SDLoc DL(N); 15038 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 15039 ConcatOps[0] = SubVec; 15040 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 15041 15042 // Step 3: Shuffle in the padded subvector. 15043 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 15044 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 15045 AddToWorklist(PaddedSubV.getNode()); 15046 AddToWorklist(DestVecBC.getNode()); 15047 AddToWorklist(Shuf.getNode()); 15048 return DAG.getBitcast(VT, Shuf); 15049 } 15050 15051 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 15052 SDValue InVec = N->getOperand(0); 15053 SDValue InVal = N->getOperand(1); 15054 SDValue EltNo = N->getOperand(2); 15055 SDLoc DL(N); 15056 15057 // If the inserted element is an UNDEF, just use the input vector. 15058 if (InVal.isUndef()) 15059 return InVec; 15060 15061 EVT VT = InVec.getValueType(); 15062 15063 // Remove redundant insertions: 15064 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 15065 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15066 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 15067 return InVec; 15068 15069 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 15070 if (!IndexC) { 15071 // If this is variable insert to undef vector, it might be better to splat: 15072 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > 15073 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { 15074 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal); 15075 return DAG.getBuildVector(VT, DL, Ops); 15076 } 15077 return SDValue(); 15078 } 15079 15080 // We must know which element is being inserted for folds below here. 15081 unsigned Elt = IndexC->getZExtValue(); 15082 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 15083 return Shuf; 15084 15085 // Canonicalize insert_vector_elt dag nodes. 15086 // Example: 15087 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 15088 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 15089 // 15090 // Do this only if the child insert_vector node has one use; also 15091 // do this only if indices are both constants and Idx1 < Idx0. 15092 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 15093 && isa<ConstantSDNode>(InVec.getOperand(2))) { 15094 unsigned OtherElt = InVec.getConstantOperandVal(2); 15095 if (Elt < OtherElt) { 15096 // Swap nodes. 15097 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 15098 InVec.getOperand(0), InVal, EltNo); 15099 AddToWorklist(NewOp.getNode()); 15100 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 15101 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 15102 } 15103 } 15104 15105 // If we can't generate a legal BUILD_VECTOR, exit 15106 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 15107 return SDValue(); 15108 15109 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 15110 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 15111 // vector elements. 15112 SmallVector<SDValue, 8> Ops; 15113 // Do not combine these two vectors if the output vector will not replace 15114 // the input vector. 15115 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 15116 Ops.append(InVec.getNode()->op_begin(), 15117 InVec.getNode()->op_end()); 15118 } else if (InVec.isUndef()) { 15119 unsigned NElts = VT.getVectorNumElements(); 15120 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 15121 } else { 15122 return SDValue(); 15123 } 15124 15125 // Insert the element 15126 if (Elt < Ops.size()) { 15127 // All the operands of BUILD_VECTOR must have the same type; 15128 // we enforce that here. 15129 EVT OpVT = Ops[0].getValueType(); 15130 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 15131 } 15132 15133 // Return the new vector 15134 return DAG.getBuildVector(VT, DL, Ops); 15135 } 15136 15137 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 15138 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 15139 assert(!OriginalLoad->isVolatile()); 15140 15141 EVT ResultVT = EVE->getValueType(0); 15142 EVT VecEltVT = InVecVT.getVectorElementType(); 15143 unsigned Align = OriginalLoad->getAlignment(); 15144 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 15145 VecEltVT.getTypeForEVT(*DAG.getContext())); 15146 15147 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 15148 return SDValue(); 15149 15150 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 15151 ISD::NON_EXTLOAD : ISD::EXTLOAD; 15152 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 15153 return SDValue(); 15154 15155 Align = NewAlign; 15156 15157 SDValue NewPtr = OriginalLoad->getBasePtr(); 15158 SDValue Offset; 15159 EVT PtrType = NewPtr.getValueType(); 15160 MachinePointerInfo MPI; 15161 SDLoc DL(EVE); 15162 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 15163 int Elt = ConstEltNo->getZExtValue(); 15164 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 15165 Offset = DAG.getConstant(PtrOff, DL, PtrType); 15166 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 15167 } else { 15168 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 15169 Offset = DAG.getNode( 15170 ISD::MUL, DL, PtrType, Offset, 15171 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 15172 MPI = OriginalLoad->getPointerInfo(); 15173 } 15174 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 15175 15176 // The replacement we need to do here is a little tricky: we need to 15177 // replace an extractelement of a load with a load. 15178 // Use ReplaceAllUsesOfValuesWith to do the replacement. 15179 // Note that this replacement assumes that the extractvalue is the only 15180 // use of the load; that's okay because we don't want to perform this 15181 // transformation in other cases anyway. 15182 SDValue Load; 15183 SDValue Chain; 15184 if (ResultVT.bitsGT(VecEltVT)) { 15185 // If the result type of vextract is wider than the load, then issue an 15186 // extending load instead. 15187 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 15188 VecEltVT) 15189 ? ISD::ZEXTLOAD 15190 : ISD::EXTLOAD; 15191 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 15192 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 15193 Align, OriginalLoad->getMemOperand()->getFlags(), 15194 OriginalLoad->getAAInfo()); 15195 Chain = Load.getValue(1); 15196 } else { 15197 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 15198 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 15199 OriginalLoad->getAAInfo()); 15200 Chain = Load.getValue(1); 15201 if (ResultVT.bitsLT(VecEltVT)) 15202 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 15203 else 15204 Load = DAG.getBitcast(ResultVT, Load); 15205 } 15206 WorklistRemover DeadNodes(*this); 15207 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 15208 SDValue To[] = { Load, Chain }; 15209 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 15210 // Since we're explicitly calling ReplaceAllUses, add the new node to the 15211 // worklist explicitly as well. 15212 AddToWorklist(Load.getNode()); 15213 AddUsersToWorklist(Load.getNode()); // Add users too 15214 // Make sure to revisit this node to clean it up; it will usually be dead. 15215 AddToWorklist(EVE); 15216 ++OpsNarrowed; 15217 return SDValue(EVE, 0); 15218 } 15219 15220 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 15221 // (vextract (scalar_to_vector val, 0) -> val 15222 SDValue InVec = N->getOperand(0); 15223 EVT VT = InVec.getValueType(); 15224 EVT NVT = N->getValueType(0); 15225 15226 if (InVec.isUndef()) 15227 return DAG.getUNDEF(NVT); 15228 15229 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15230 // Check if the result type doesn't match the inserted element type. A 15231 // SCALAR_TO_VECTOR may truncate the inserted element and the 15232 // EXTRACT_VECTOR_ELT may widen the extracted vector. 15233 SDValue InOp = InVec.getOperand(0); 15234 if (InOp.getValueType() != NVT) { 15235 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15236 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 15237 } 15238 return InOp; 15239 } 15240 15241 SDValue EltNo = N->getOperand(1); 15242 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 15243 15244 // extract_vector_elt of out-of-bounds element -> UNDEF 15245 if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements())) 15246 return DAG.getUNDEF(NVT); 15247 15248 // extract_vector_elt (build_vector x, y), 1 -> y 15249 if (ConstEltNo && 15250 InVec.getOpcode() == ISD::BUILD_VECTOR && 15251 TLI.isTypeLegal(VT) && 15252 (InVec.hasOneUse() || 15253 TLI.aggressivelyPreferBuildVectorSources(VT))) { 15254 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 15255 EVT InEltVT = Elt.getValueType(); 15256 15257 // Sometimes build_vector's scalar input types do not match result type. 15258 if (NVT == InEltVT) 15259 return Elt; 15260 15261 // TODO: It may be useful to truncate if free if the build_vector implicitly 15262 // converts. 15263 } 15264 15265 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 15266 bool isLE = DAG.getDataLayout().isLittleEndian(); 15267 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 15268 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 15269 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 15270 SDValue BCSrc = InVec.getOperand(0); 15271 if (BCSrc.getValueType().isScalarInteger()) 15272 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 15273 } 15274 15275 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 15276 // 15277 // This only really matters if the index is non-constant since other combines 15278 // on the constant elements already work. 15279 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 15280 EltNo == InVec.getOperand(2)) { 15281 SDValue Elt = InVec.getOperand(1); 15282 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 15283 } 15284 15285 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 15286 // We only perform this optimization before the op legalization phase because 15287 // we may introduce new vector instructions which are not backed by TD 15288 // patterns. For example on AVX, extracting elements from a wide vector 15289 // without using extract_subvector. However, if we can find an underlying 15290 // scalar value, then we can always use that. 15291 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 15292 int NumElem = VT.getVectorNumElements(); 15293 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 15294 // Find the new index to extract from. 15295 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 15296 15297 // Extracting an undef index is undef. 15298 if (OrigElt == -1) 15299 return DAG.getUNDEF(NVT); 15300 15301 // Select the right vector half to extract from. 15302 SDValue SVInVec; 15303 if (OrigElt < NumElem) { 15304 SVInVec = InVec->getOperand(0); 15305 } else { 15306 SVInVec = InVec->getOperand(1); 15307 OrigElt -= NumElem; 15308 } 15309 15310 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 15311 SDValue InOp = SVInVec.getOperand(OrigElt); 15312 if (InOp.getValueType() != NVT) { 15313 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15314 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 15315 } 15316 15317 return InOp; 15318 } 15319 15320 // FIXME: We should handle recursing on other vector shuffles and 15321 // scalar_to_vector here as well. 15322 15323 if (!LegalOperations || 15324 // FIXME: Should really be just isOperationLegalOrCustom. 15325 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 15326 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 15327 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15328 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 15329 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 15330 } 15331 } 15332 15333 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 15334 // simplify it based on the (valid) extraction indices. 15335 if (llvm::all_of(InVec->uses(), [&](SDNode *Use) { 15336 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15337 Use->getOperand(0) == InVec && 15338 isa<ConstantSDNode>(Use->getOperand(1)); 15339 })) { 15340 APInt DemandedElts = APInt::getNullValue(VT.getVectorNumElements()); 15341 for (SDNode *Use : InVec->uses()) { 15342 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 15343 if (CstElt->getAPIntValue().ult(VT.getVectorNumElements())) 15344 DemandedElts.setBit(CstElt->getZExtValue()); 15345 } 15346 if (SimplifyDemandedVectorElts(InVec, DemandedElts, true)) 15347 return SDValue(N, 0); 15348 } 15349 15350 bool BCNumEltsChanged = false; 15351 EVT ExtVT = VT.getVectorElementType(); 15352 EVT LVT = ExtVT; 15353 15354 // If the result of load has to be truncated, then it's not necessarily 15355 // profitable. 15356 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 15357 return SDValue(); 15358 15359 if (InVec.getOpcode() == ISD::BITCAST) { 15360 // Don't duplicate a load with other uses. 15361 if (!InVec.hasOneUse()) 15362 return SDValue(); 15363 15364 EVT BCVT = InVec.getOperand(0).getValueType(); 15365 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 15366 return SDValue(); 15367 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 15368 BCNumEltsChanged = true; 15369 InVec = InVec.getOperand(0); 15370 ExtVT = BCVT.getVectorElementType(); 15371 } 15372 15373 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 15374 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 15375 ISD::isNormalLoad(InVec.getNode()) && 15376 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 15377 SDValue Index = N->getOperand(1); 15378 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 15379 if (!OrigLoad->isVolatile()) { 15380 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 15381 OrigLoad); 15382 } 15383 } 15384 } 15385 15386 // Perform only after legalization to ensure build_vector / vector_shuffle 15387 // optimizations have already been done. 15388 if (!LegalOperations) return SDValue(); 15389 15390 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 15391 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 15392 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 15393 15394 if (ConstEltNo) { 15395 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 15396 15397 LoadSDNode *LN0 = nullptr; 15398 const ShuffleVectorSDNode *SVN = nullptr; 15399 if (ISD::isNormalLoad(InVec.getNode())) { 15400 LN0 = cast<LoadSDNode>(InVec); 15401 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 15402 InVec.getOperand(0).getValueType() == ExtVT && 15403 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 15404 // Don't duplicate a load with other uses. 15405 if (!InVec.hasOneUse()) 15406 return SDValue(); 15407 15408 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 15409 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 15410 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 15411 // => 15412 // (load $addr+1*size) 15413 15414 // Don't duplicate a load with other uses. 15415 if (!InVec.hasOneUse()) 15416 return SDValue(); 15417 15418 // If the bit convert changed the number of elements, it is unsafe 15419 // to examine the mask. 15420 if (BCNumEltsChanged) 15421 return SDValue(); 15422 15423 // Select the input vector, guarding against out of range extract vector. 15424 unsigned NumElems = VT.getVectorNumElements(); 15425 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 15426 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 15427 15428 if (InVec.getOpcode() == ISD::BITCAST) { 15429 // Don't duplicate a load with other uses. 15430 if (!InVec.hasOneUse()) 15431 return SDValue(); 15432 15433 InVec = InVec.getOperand(0); 15434 } 15435 if (ISD::isNormalLoad(InVec.getNode())) { 15436 LN0 = cast<LoadSDNode>(InVec); 15437 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 15438 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 15439 } 15440 } 15441 15442 // Make sure we found a non-volatile load and the extractelement is 15443 // the only use. 15444 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 15445 return SDValue(); 15446 15447 // If Idx was -1 above, Elt is going to be -1, so just return undef. 15448 if (Elt == -1) 15449 return DAG.getUNDEF(LVT); 15450 15451 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 15452 } 15453 15454 return SDValue(); 15455 } 15456 15457 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 15458 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 15459 // We perform this optimization post type-legalization because 15460 // the type-legalizer often scalarizes integer-promoted vectors. 15461 // Performing this optimization before may create bit-casts which 15462 // will be type-legalized to complex code sequences. 15463 // We perform this optimization only before the operation legalizer because we 15464 // may introduce illegal operations. 15465 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 15466 return SDValue(); 15467 15468 unsigned NumInScalars = N->getNumOperands(); 15469 SDLoc DL(N); 15470 EVT VT = N->getValueType(0); 15471 15472 // Check to see if this is a BUILD_VECTOR of a bunch of values 15473 // which come from any_extend or zero_extend nodes. If so, we can create 15474 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 15475 // optimizations. We do not handle sign-extend because we can't fill the sign 15476 // using shuffles. 15477 EVT SourceType = MVT::Other; 15478 bool AllAnyExt = true; 15479 15480 for (unsigned i = 0; i != NumInScalars; ++i) { 15481 SDValue In = N->getOperand(i); 15482 // Ignore undef inputs. 15483 if (In.isUndef()) continue; 15484 15485 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 15486 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 15487 15488 // Abort if the element is not an extension. 15489 if (!ZeroExt && !AnyExt) { 15490 SourceType = MVT::Other; 15491 break; 15492 } 15493 15494 // The input is a ZeroExt or AnyExt. Check the original type. 15495 EVT InTy = In.getOperand(0).getValueType(); 15496 15497 // Check that all of the widened source types are the same. 15498 if (SourceType == MVT::Other) 15499 // First time. 15500 SourceType = InTy; 15501 else if (InTy != SourceType) { 15502 // Multiple income types. Abort. 15503 SourceType = MVT::Other; 15504 break; 15505 } 15506 15507 // Check if all of the extends are ANY_EXTENDs. 15508 AllAnyExt &= AnyExt; 15509 } 15510 15511 // In order to have valid types, all of the inputs must be extended from the 15512 // same source type and all of the inputs must be any or zero extend. 15513 // Scalar sizes must be a power of two. 15514 EVT OutScalarTy = VT.getScalarType(); 15515 bool ValidTypes = SourceType != MVT::Other && 15516 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 15517 isPowerOf2_32(SourceType.getSizeInBits()); 15518 15519 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 15520 // turn into a single shuffle instruction. 15521 if (!ValidTypes) 15522 return SDValue(); 15523 15524 bool isLE = DAG.getDataLayout().isLittleEndian(); 15525 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 15526 assert(ElemRatio > 1 && "Invalid element size ratio"); 15527 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 15528 DAG.getConstant(0, DL, SourceType); 15529 15530 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 15531 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 15532 15533 // Populate the new build_vector 15534 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15535 SDValue Cast = N->getOperand(i); 15536 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 15537 Cast.getOpcode() == ISD::ZERO_EXTEND || 15538 Cast.isUndef()) && "Invalid cast opcode"); 15539 SDValue In; 15540 if (Cast.isUndef()) 15541 In = DAG.getUNDEF(SourceType); 15542 else 15543 In = Cast->getOperand(0); 15544 unsigned Index = isLE ? (i * ElemRatio) : 15545 (i * ElemRatio + (ElemRatio - 1)); 15546 15547 assert(Index < Ops.size() && "Invalid index"); 15548 Ops[Index] = In; 15549 } 15550 15551 // The type of the new BUILD_VECTOR node. 15552 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 15553 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 15554 "Invalid vector size"); 15555 // Check if the new vector type is legal. 15556 if (!isTypeLegal(VecVT) || 15557 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 15558 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 15559 return SDValue(); 15560 15561 // Make the new BUILD_VECTOR. 15562 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 15563 15564 // The new BUILD_VECTOR node has the potential to be further optimized. 15565 AddToWorklist(BV.getNode()); 15566 // Bitcast to the desired type. 15567 return DAG.getBitcast(VT, BV); 15568 } 15569 15570 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 15571 EVT VT = N->getValueType(0); 15572 15573 unsigned NumInScalars = N->getNumOperands(); 15574 SDLoc DL(N); 15575 15576 EVT SrcVT = MVT::Other; 15577 unsigned Opcode = ISD::DELETED_NODE; 15578 unsigned NumDefs = 0; 15579 15580 for (unsigned i = 0; i != NumInScalars; ++i) { 15581 SDValue In = N->getOperand(i); 15582 unsigned Opc = In.getOpcode(); 15583 15584 if (Opc == ISD::UNDEF) 15585 continue; 15586 15587 // If all scalar values are floats and converted from integers. 15588 if (Opcode == ISD::DELETED_NODE && 15589 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 15590 Opcode = Opc; 15591 } 15592 15593 if (Opc != Opcode) 15594 return SDValue(); 15595 15596 EVT InVT = In.getOperand(0).getValueType(); 15597 15598 // If all scalar values are typed differently, bail out. It's chosen to 15599 // simplify BUILD_VECTOR of integer types. 15600 if (SrcVT == MVT::Other) 15601 SrcVT = InVT; 15602 if (SrcVT != InVT) 15603 return SDValue(); 15604 NumDefs++; 15605 } 15606 15607 // If the vector has just one element defined, it's not worth to fold it into 15608 // a vectorized one. 15609 if (NumDefs < 2) 15610 return SDValue(); 15611 15612 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 15613 && "Should only handle conversion from integer to float."); 15614 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 15615 15616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 15617 15618 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 15619 return SDValue(); 15620 15621 // Just because the floating-point vector type is legal does not necessarily 15622 // mean that the corresponding integer vector type is. 15623 if (!isTypeLegal(NVT)) 15624 return SDValue(); 15625 15626 SmallVector<SDValue, 8> Opnds; 15627 for (unsigned i = 0; i != NumInScalars; ++i) { 15628 SDValue In = N->getOperand(i); 15629 15630 if (In.isUndef()) 15631 Opnds.push_back(DAG.getUNDEF(SrcVT)); 15632 else 15633 Opnds.push_back(In.getOperand(0)); 15634 } 15635 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 15636 AddToWorklist(BV.getNode()); 15637 15638 return DAG.getNode(Opcode, DL, VT, BV); 15639 } 15640 15641 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 15642 ArrayRef<int> VectorMask, 15643 SDValue VecIn1, SDValue VecIn2, 15644 unsigned LeftIdx) { 15645 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15646 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 15647 15648 EVT VT = N->getValueType(0); 15649 EVT InVT1 = VecIn1.getValueType(); 15650 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 15651 15652 unsigned Vec2Offset = 0; 15653 unsigned NumElems = VT.getVectorNumElements(); 15654 unsigned ShuffleNumElems = NumElems; 15655 15656 // In case both the input vectors are extracted from same base 15657 // vector we do not need extra addend (Vec2Offset) while 15658 // computing shuffle mask. 15659 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15660 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15661 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 15662 Vec2Offset = InVT1.getVectorNumElements(); 15663 15664 // We can't generate a shuffle node with mismatched input and output types. 15665 // Try to make the types match the type of the output. 15666 if (InVT1 != VT || InVT2 != VT) { 15667 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 15668 // If the output vector length is a multiple of both input lengths, 15669 // we can concatenate them and pad the rest with undefs. 15670 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 15671 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 15672 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 15673 ConcatOps[0] = VecIn1; 15674 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 15675 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 15676 VecIn2 = SDValue(); 15677 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 15678 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 15679 return SDValue(); 15680 15681 if (!VecIn2.getNode()) { 15682 // If we only have one input vector, and it's twice the size of the 15683 // output, split it in two. 15684 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 15685 DAG.getConstant(NumElems, DL, IdxTy)); 15686 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 15687 // Since we now have shorter input vectors, adjust the offset of the 15688 // second vector's start. 15689 Vec2Offset = NumElems; 15690 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 15691 // VecIn1 is wider than the output, and we have another, possibly 15692 // smaller input. Pad the smaller input with undefs, shuffle at the 15693 // input vector width, and extract the output. 15694 // The shuffle type is different than VT, so check legality again. 15695 if (LegalOperations && 15696 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 15697 return SDValue(); 15698 15699 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 15700 // lower it back into a BUILD_VECTOR. So if the inserted type is 15701 // illegal, don't even try. 15702 if (InVT1 != InVT2) { 15703 if (!TLI.isTypeLegal(InVT2)) 15704 return SDValue(); 15705 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 15706 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 15707 } 15708 ShuffleNumElems = NumElems * 2; 15709 } else { 15710 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 15711 // than VecIn1. We can't handle this for now - this case will disappear 15712 // when we start sorting the vectors by type. 15713 return SDValue(); 15714 } 15715 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 15716 InVT1.getSizeInBits() == VT.getSizeInBits()) { 15717 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 15718 ConcatOps[0] = VecIn2; 15719 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 15720 } else { 15721 // TODO: Support cases where the length mismatch isn't exactly by a 15722 // factor of 2. 15723 // TODO: Move this check upwards, so that if we have bad type 15724 // mismatches, we don't create any DAG nodes. 15725 return SDValue(); 15726 } 15727 } 15728 15729 // Initialize mask to undef. 15730 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 15731 15732 // Only need to run up to the number of elements actually used, not the 15733 // total number of elements in the shuffle - if we are shuffling a wider 15734 // vector, the high lanes should be set to undef. 15735 for (unsigned i = 0; i != NumElems; ++i) { 15736 if (VectorMask[i] <= 0) 15737 continue; 15738 15739 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 15740 if (VectorMask[i] == (int)LeftIdx) { 15741 Mask[i] = ExtIndex; 15742 } else if (VectorMask[i] == (int)LeftIdx + 1) { 15743 Mask[i] = Vec2Offset + ExtIndex; 15744 } 15745 } 15746 15747 // The type the input vectors may have changed above. 15748 InVT1 = VecIn1.getValueType(); 15749 15750 // If we already have a VecIn2, it should have the same type as VecIn1. 15751 // If we don't, get an undef/zero vector of the appropriate type. 15752 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 15753 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 15754 15755 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 15756 if (ShuffleNumElems > NumElems) 15757 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 15758 15759 return Shuffle; 15760 } 15761 15762 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 15763 // operations. If the types of the vectors we're extracting from allow it, 15764 // turn this into a vector_shuffle node. 15765 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 15766 SDLoc DL(N); 15767 EVT VT = N->getValueType(0); 15768 15769 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 15770 if (!isTypeLegal(VT)) 15771 return SDValue(); 15772 15773 // May only combine to shuffle after legalize if shuffle is legal. 15774 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 15775 return SDValue(); 15776 15777 bool UsesZeroVector = false; 15778 unsigned NumElems = N->getNumOperands(); 15779 15780 // Record, for each element of the newly built vector, which input vector 15781 // that element comes from. -1 stands for undef, 0 for the zero vector, 15782 // and positive values for the input vectors. 15783 // VectorMask maps each element to its vector number, and VecIn maps vector 15784 // numbers to their initial SDValues. 15785 15786 SmallVector<int, 8> VectorMask(NumElems, -1); 15787 SmallVector<SDValue, 8> VecIn; 15788 VecIn.push_back(SDValue()); 15789 15790 for (unsigned i = 0; i != NumElems; ++i) { 15791 SDValue Op = N->getOperand(i); 15792 15793 if (Op.isUndef()) 15794 continue; 15795 15796 // See if we can use a blend with a zero vector. 15797 // TODO: Should we generalize this to a blend with an arbitrary constant 15798 // vector? 15799 if (isNullConstant(Op) || isNullFPConstant(Op)) { 15800 UsesZeroVector = true; 15801 VectorMask[i] = 0; 15802 continue; 15803 } 15804 15805 // Not an undef or zero. If the input is something other than an 15806 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 15807 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 15808 !isa<ConstantSDNode>(Op.getOperand(1))) 15809 return SDValue(); 15810 SDValue ExtractedFromVec = Op.getOperand(0); 15811 15812 APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue(); 15813 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 15814 return SDValue(); 15815 15816 // All inputs must have the same element type as the output. 15817 if (VT.getVectorElementType() != 15818 ExtractedFromVec.getValueType().getVectorElementType()) 15819 return SDValue(); 15820 15821 // Have we seen this input vector before? 15822 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 15823 // a map back from SDValues to numbers isn't worth it. 15824 unsigned Idx = std::distance( 15825 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 15826 if (Idx == VecIn.size()) 15827 VecIn.push_back(ExtractedFromVec); 15828 15829 VectorMask[i] = Idx; 15830 } 15831 15832 // If we didn't find at least one input vector, bail out. 15833 if (VecIn.size() < 2) 15834 return SDValue(); 15835 15836 // If all the Operands of BUILD_VECTOR extract from same 15837 // vector, then split the vector efficiently based on the maximum 15838 // vector access index and adjust the VectorMask and 15839 // VecIn accordingly. 15840 if (VecIn.size() == 2) { 15841 unsigned MaxIndex = 0; 15842 unsigned NearestPow2 = 0; 15843 SDValue Vec = VecIn.back(); 15844 EVT InVT = Vec.getValueType(); 15845 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15846 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 15847 15848 for (unsigned i = 0; i < NumElems; i++) { 15849 if (VectorMask[i] <= 0) 15850 continue; 15851 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 15852 IndexVec[i] = Index; 15853 MaxIndex = std::max(MaxIndex, Index); 15854 } 15855 15856 NearestPow2 = PowerOf2Ceil(MaxIndex); 15857 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 15858 NumElems * 2 < NearestPow2) { 15859 unsigned SplitSize = NearestPow2 / 2; 15860 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 15861 InVT.getVectorElementType(), SplitSize); 15862 if (TLI.isTypeLegal(SplitVT)) { 15863 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 15864 DAG.getConstant(SplitSize, DL, IdxTy)); 15865 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 15866 DAG.getConstant(0, DL, IdxTy)); 15867 VecIn.pop_back(); 15868 VecIn.push_back(VecIn1); 15869 VecIn.push_back(VecIn2); 15870 15871 for (unsigned i = 0; i < NumElems; i++) { 15872 if (VectorMask[i] <= 0) 15873 continue; 15874 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 15875 } 15876 } 15877 } 15878 } 15879 15880 // TODO: We want to sort the vectors by descending length, so that adjacent 15881 // pairs have similar length, and the longer vector is always first in the 15882 // pair. 15883 15884 // TODO: Should this fire if some of the input vectors has illegal type (like 15885 // it does now), or should we let legalization run its course first? 15886 15887 // Shuffle phase: 15888 // Take pairs of vectors, and shuffle them so that the result has elements 15889 // from these vectors in the correct places. 15890 // For example, given: 15891 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 15892 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 15893 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 15894 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 15895 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 15896 // We will generate: 15897 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 15898 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 15899 SmallVector<SDValue, 4> Shuffles; 15900 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 15901 unsigned LeftIdx = 2 * In + 1; 15902 SDValue VecLeft = VecIn[LeftIdx]; 15903 SDValue VecRight = 15904 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 15905 15906 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 15907 VecRight, LeftIdx)) 15908 Shuffles.push_back(Shuffle); 15909 else 15910 return SDValue(); 15911 } 15912 15913 // If we need the zero vector as an "ingredient" in the blend tree, add it 15914 // to the list of shuffles. 15915 if (UsesZeroVector) 15916 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 15917 : DAG.getConstantFP(0.0, DL, VT)); 15918 15919 // If we only have one shuffle, we're done. 15920 if (Shuffles.size() == 1) 15921 return Shuffles[0]; 15922 15923 // Update the vector mask to point to the post-shuffle vectors. 15924 for (int &Vec : VectorMask) 15925 if (Vec == 0) 15926 Vec = Shuffles.size() - 1; 15927 else 15928 Vec = (Vec - 1) / 2; 15929 15930 // More than one shuffle. Generate a binary tree of blends, e.g. if from 15931 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 15932 // generate: 15933 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 15934 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 15935 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 15936 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 15937 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 15938 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 15939 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 15940 15941 // Make sure the initial size of the shuffle list is even. 15942 if (Shuffles.size() % 2) 15943 Shuffles.push_back(DAG.getUNDEF(VT)); 15944 15945 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 15946 if (CurSize % 2) { 15947 Shuffles[CurSize] = DAG.getUNDEF(VT); 15948 CurSize++; 15949 } 15950 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 15951 int Left = 2 * In; 15952 int Right = 2 * In + 1; 15953 SmallVector<int, 8> Mask(NumElems, -1); 15954 for (unsigned i = 0; i != NumElems; ++i) { 15955 if (VectorMask[i] == Left) { 15956 Mask[i] = i; 15957 VectorMask[i] = In; 15958 } else if (VectorMask[i] == Right) { 15959 Mask[i] = i + NumElems; 15960 VectorMask[i] = In; 15961 } 15962 } 15963 15964 Shuffles[In] = 15965 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 15966 } 15967 } 15968 return Shuffles[0]; 15969 } 15970 15971 // Try to turn a build vector of zero extends of extract vector elts into a 15972 // a vector zero extend and possibly an extract subvector. 15973 // TODO: Support sign extend or any extend? 15974 // TODO: Allow undef elements? 15975 // TODO: Don't require the extracts to start at element 0. 15976 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 15977 if (LegalOperations) 15978 return SDValue(); 15979 15980 EVT VT = N->getValueType(0); 15981 15982 SDValue Op0 = N->getOperand(0); 15983 auto checkElem = [&](SDValue Op) -> int64_t { 15984 if (Op.getOpcode() == ISD::ZERO_EXTEND && 15985 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15986 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 15987 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 15988 return C->getZExtValue(); 15989 return -1; 15990 }; 15991 15992 // Make sure the first element matches 15993 // (zext (extract_vector_elt X, C)) 15994 int64_t Offset = checkElem(Op0); 15995 if (Offset < 0) 15996 return SDValue(); 15997 15998 unsigned NumElems = N->getNumOperands(); 15999 SDValue In = Op0.getOperand(0).getOperand(0); 16000 EVT InSVT = In.getValueType().getScalarType(); 16001 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 16002 16003 // Don't create an illegal input type after type legalization. 16004 if (LegalTypes && !TLI.isTypeLegal(InVT)) 16005 return SDValue(); 16006 16007 // Ensure all the elements come from the same vector and are adjacent. 16008 for (unsigned i = 1; i != NumElems; ++i) { 16009 if ((Offset + i) != checkElem(N->getOperand(i))) 16010 return SDValue(); 16011 } 16012 16013 SDLoc DL(N); 16014 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 16015 Op0.getOperand(0).getOperand(1)); 16016 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In); 16017 } 16018 16019 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 16020 EVT VT = N->getValueType(0); 16021 16022 // A vector built entirely of undefs is undef. 16023 if (ISD::allOperandsUndef(N)) 16024 return DAG.getUNDEF(VT); 16025 16026 // If this is a splat of a bitcast from another vector, change to a 16027 // concat_vector. 16028 // For example: 16029 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 16030 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 16031 // 16032 // If X is a build_vector itself, the concat can become a larger build_vector. 16033 // TODO: Maybe this is useful for non-splat too? 16034 if (!LegalOperations) { 16035 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 16036 Splat = peekThroughBitcast(Splat); 16037 EVT SrcVT = Splat.getValueType(); 16038 if (SrcVT.isVector()) { 16039 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 16040 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 16041 SrcVT.getVectorElementType(), NumElts); 16042 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 16043 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 16044 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 16045 NewVT, Ops); 16046 return DAG.getBitcast(VT, Concat); 16047 } 16048 } 16049 } 16050 } 16051 16052 // Check if we can express BUILD VECTOR via subvector extract. 16053 if (!LegalTypes && (N->getNumOperands() > 1)) { 16054 SDValue Op0 = N->getOperand(0); 16055 auto checkElem = [&](SDValue Op) -> uint64_t { 16056 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 16057 (Op0.getOperand(0) == Op.getOperand(0))) 16058 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 16059 return CNode->getZExtValue(); 16060 return -1; 16061 }; 16062 16063 int Offset = checkElem(Op0); 16064 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 16065 if (Offset + i != checkElem(N->getOperand(i))) { 16066 Offset = -1; 16067 break; 16068 } 16069 } 16070 16071 if ((Offset == 0) && 16072 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 16073 return Op0.getOperand(0); 16074 if ((Offset != -1) && 16075 ((Offset % N->getValueType(0).getVectorNumElements()) == 16076 0)) // IDX must be multiple of output size. 16077 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 16078 Op0.getOperand(0), Op0.getOperand(1)); 16079 } 16080 16081 if (SDValue V = convertBuildVecZextToZext(N)) 16082 return V; 16083 16084 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 16085 return V; 16086 16087 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 16088 return V; 16089 16090 if (SDValue V = reduceBuildVecToShuffle(N)) 16091 return V; 16092 16093 return SDValue(); 16094 } 16095 16096 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 16097 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16098 EVT OpVT = N->getOperand(0).getValueType(); 16099 16100 // If the operands are legal vectors, leave them alone. 16101 if (TLI.isTypeLegal(OpVT)) 16102 return SDValue(); 16103 16104 SDLoc DL(N); 16105 EVT VT = N->getValueType(0); 16106 SmallVector<SDValue, 8> Ops; 16107 16108 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 16109 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16110 16111 // Keep track of what we encounter. 16112 bool AnyInteger = false; 16113 bool AnyFP = false; 16114 for (const SDValue &Op : N->ops()) { 16115 if (ISD::BITCAST == Op.getOpcode() && 16116 !Op.getOperand(0).getValueType().isVector()) 16117 Ops.push_back(Op.getOperand(0)); 16118 else if (ISD::UNDEF == Op.getOpcode()) 16119 Ops.push_back(ScalarUndef); 16120 else 16121 return SDValue(); 16122 16123 // Note whether we encounter an integer or floating point scalar. 16124 // If it's neither, bail out, it could be something weird like x86mmx. 16125 EVT LastOpVT = Ops.back().getValueType(); 16126 if (LastOpVT.isFloatingPoint()) 16127 AnyFP = true; 16128 else if (LastOpVT.isInteger()) 16129 AnyInteger = true; 16130 else 16131 return SDValue(); 16132 } 16133 16134 // If any of the operands is a floating point scalar bitcast to a vector, 16135 // use floating point types throughout, and bitcast everything. 16136 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 16137 if (AnyFP) { 16138 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 16139 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16140 if (AnyInteger) { 16141 for (SDValue &Op : Ops) { 16142 if (Op.getValueType() == SVT) 16143 continue; 16144 if (Op.isUndef()) 16145 Op = ScalarUndef; 16146 else 16147 Op = DAG.getBitcast(SVT, Op); 16148 } 16149 } 16150 } 16151 16152 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 16153 VT.getSizeInBits() / SVT.getSizeInBits()); 16154 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 16155 } 16156 16157 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 16158 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 16159 // most two distinct vectors the same size as the result, attempt to turn this 16160 // into a legal shuffle. 16161 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 16162 EVT VT = N->getValueType(0); 16163 EVT OpVT = N->getOperand(0).getValueType(); 16164 int NumElts = VT.getVectorNumElements(); 16165 int NumOpElts = OpVT.getVectorNumElements(); 16166 16167 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 16168 SmallVector<int, 8> Mask; 16169 16170 for (SDValue Op : N->ops()) { 16171 // Peek through any bitcast. 16172 Op = peekThroughBitcast(Op); 16173 16174 // UNDEF nodes convert to UNDEF shuffle mask values. 16175 if (Op.isUndef()) { 16176 Mask.append((unsigned)NumOpElts, -1); 16177 continue; 16178 } 16179 16180 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16181 return SDValue(); 16182 16183 // What vector are we extracting the subvector from and at what index? 16184 SDValue ExtVec = Op.getOperand(0); 16185 16186 // We want the EVT of the original extraction to correctly scale the 16187 // extraction index. 16188 EVT ExtVT = ExtVec.getValueType(); 16189 16190 // Peek through any bitcast. 16191 ExtVec = peekThroughBitcast(ExtVec); 16192 16193 // UNDEF nodes convert to UNDEF shuffle mask values. 16194 if (ExtVec.isUndef()) { 16195 Mask.append((unsigned)NumOpElts, -1); 16196 continue; 16197 } 16198 16199 if (!isa<ConstantSDNode>(Op.getOperand(1))) 16200 return SDValue(); 16201 int ExtIdx = Op.getConstantOperandVal(1); 16202 16203 // Ensure that we are extracting a subvector from a vector the same 16204 // size as the result. 16205 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 16206 return SDValue(); 16207 16208 // Scale the subvector index to account for any bitcast. 16209 int NumExtElts = ExtVT.getVectorNumElements(); 16210 if (0 == (NumExtElts % NumElts)) 16211 ExtIdx /= (NumExtElts / NumElts); 16212 else if (0 == (NumElts % NumExtElts)) 16213 ExtIdx *= (NumElts / NumExtElts); 16214 else 16215 return SDValue(); 16216 16217 // At most we can reference 2 inputs in the final shuffle. 16218 if (SV0.isUndef() || SV0 == ExtVec) { 16219 SV0 = ExtVec; 16220 for (int i = 0; i != NumOpElts; ++i) 16221 Mask.push_back(i + ExtIdx); 16222 } else if (SV1.isUndef() || SV1 == ExtVec) { 16223 SV1 = ExtVec; 16224 for (int i = 0; i != NumOpElts; ++i) 16225 Mask.push_back(i + ExtIdx + NumElts); 16226 } else { 16227 return SDValue(); 16228 } 16229 } 16230 16231 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 16232 return SDValue(); 16233 16234 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 16235 DAG.getBitcast(VT, SV1), Mask); 16236 } 16237 16238 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 16239 // If we only have one input vector, we don't need to do any concatenation. 16240 if (N->getNumOperands() == 1) 16241 return N->getOperand(0); 16242 16243 // Check if all of the operands are undefs. 16244 EVT VT = N->getValueType(0); 16245 if (ISD::allOperandsUndef(N)) 16246 return DAG.getUNDEF(VT); 16247 16248 // Optimize concat_vectors where all but the first of the vectors are undef. 16249 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 16250 return Op.isUndef(); 16251 })) { 16252 SDValue In = N->getOperand(0); 16253 assert(In.getValueType().isVector() && "Must concat vectors"); 16254 16255 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 16256 if (In->getOpcode() == ISD::BITCAST && 16257 !In->getOperand(0).getValueType().isVector()) { 16258 SDValue Scalar = In->getOperand(0); 16259 16260 // If the bitcast type isn't legal, it might be a trunc of a legal type; 16261 // look through the trunc so we can still do the transform: 16262 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 16263 if (Scalar->getOpcode() == ISD::TRUNCATE && 16264 !TLI.isTypeLegal(Scalar.getValueType()) && 16265 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 16266 Scalar = Scalar->getOperand(0); 16267 16268 EVT SclTy = Scalar->getValueType(0); 16269 16270 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 16271 return SDValue(); 16272 16273 // Bail out if the vector size is not a multiple of the scalar size. 16274 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 16275 return SDValue(); 16276 16277 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 16278 if (VNTNumElms < 2) 16279 return SDValue(); 16280 16281 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 16282 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 16283 return SDValue(); 16284 16285 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 16286 return DAG.getBitcast(VT, Res); 16287 } 16288 } 16289 16290 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 16291 // We have already tested above for an UNDEF only concatenation. 16292 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 16293 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 16294 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 16295 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 16296 }; 16297 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 16298 SmallVector<SDValue, 8> Opnds; 16299 EVT SVT = VT.getScalarType(); 16300 16301 EVT MinVT = SVT; 16302 if (!SVT.isFloatingPoint()) { 16303 // If BUILD_VECTOR are from built from integer, they may have different 16304 // operand types. Get the smallest type and truncate all operands to it. 16305 bool FoundMinVT = false; 16306 for (const SDValue &Op : N->ops()) 16307 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16308 EVT OpSVT = Op.getOperand(0).getValueType(); 16309 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 16310 FoundMinVT = true; 16311 } 16312 assert(FoundMinVT && "Concat vector type mismatch"); 16313 } 16314 16315 for (const SDValue &Op : N->ops()) { 16316 EVT OpVT = Op.getValueType(); 16317 unsigned NumElts = OpVT.getVectorNumElements(); 16318 16319 if (ISD::UNDEF == Op.getOpcode()) 16320 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 16321 16322 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16323 if (SVT.isFloatingPoint()) { 16324 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 16325 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 16326 } else { 16327 for (unsigned i = 0; i != NumElts; ++i) 16328 Opnds.push_back( 16329 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 16330 } 16331 } 16332 } 16333 16334 assert(VT.getVectorNumElements() == Opnds.size() && 16335 "Concat vector type mismatch"); 16336 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 16337 } 16338 16339 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 16340 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 16341 return V; 16342 16343 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 16344 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16345 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 16346 return V; 16347 16348 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 16349 // nodes often generate nop CONCAT_VECTOR nodes. 16350 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 16351 // place the incoming vectors at the exact same location. 16352 SDValue SingleSource = SDValue(); 16353 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 16354 16355 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16356 SDValue Op = N->getOperand(i); 16357 16358 if (Op.isUndef()) 16359 continue; 16360 16361 // Check if this is the identity extract: 16362 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16363 return SDValue(); 16364 16365 // Find the single incoming vector for the extract_subvector. 16366 if (SingleSource.getNode()) { 16367 if (Op.getOperand(0) != SingleSource) 16368 return SDValue(); 16369 } else { 16370 SingleSource = Op.getOperand(0); 16371 16372 // Check the source type is the same as the type of the result. 16373 // If not, this concat may extend the vector, so we can not 16374 // optimize it away. 16375 if (SingleSource.getValueType() != N->getValueType(0)) 16376 return SDValue(); 16377 } 16378 16379 unsigned IdentityIndex = i * PartNumElem; 16380 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 16381 // The extract index must be constant. 16382 if (!CS) 16383 return SDValue(); 16384 16385 // Check that we are reading from the identity index. 16386 if (CS->getZExtValue() != IdentityIndex) 16387 return SDValue(); 16388 } 16389 16390 if (SingleSource.getNode()) 16391 return SingleSource; 16392 16393 return SDValue(); 16394 } 16395 16396 /// If we are extracting a subvector produced by a wide binary operator with at 16397 /// at least one operand that was the result of a vector concatenation, then try 16398 /// to use the narrow vector operands directly to avoid the concatenation and 16399 /// extraction. 16400 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 16401 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 16402 // some of these bailouts with other transforms. 16403 16404 // The extract index must be a constant, so we can map it to a concat operand. 16405 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16406 if (!ExtractIndex) 16407 return SDValue(); 16408 16409 // Only handle the case where we are doubling and then halving. A larger ratio 16410 // may require more than two narrow binops to replace the wide binop. 16411 EVT VT = Extract->getValueType(0); 16412 unsigned NumElems = VT.getVectorNumElements(); 16413 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 16414 "Extract index is not a multiple of the vector length."); 16415 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 16416 return SDValue(); 16417 16418 // We are looking for an optionally bitcasted wide vector binary operator 16419 // feeding an extract subvector. 16420 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 16421 16422 // TODO: The motivating case for this transform is an x86 AVX1 target. That 16423 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 16424 // flavors, but no other 256-bit integer support. This could be extended to 16425 // handle any binop, but that may require fixing/adding other folds to avoid 16426 // codegen regressions. 16427 unsigned BOpcode = BinOp.getOpcode(); 16428 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 16429 return SDValue(); 16430 16431 // The binop must be a vector type, so we can chop it in half. 16432 EVT WideBVT = BinOp.getValueType(); 16433 if (!WideBVT.isVector()) 16434 return SDValue(); 16435 16436 // Bail out if the target does not support a narrower version of the binop. 16437 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 16438 WideBVT.getVectorNumElements() / 2); 16439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16440 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 16441 return SDValue(); 16442 16443 // Peek through bitcasts of the binary operator operands if needed. 16444 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 16445 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 16446 16447 // We need at least one concatenation operation of a binop operand to make 16448 // this transform worthwhile. The concat must double the input vector sizes. 16449 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 16450 bool ConcatL = 16451 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 16452 bool ConcatR = 16453 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 16454 if (!ConcatL && !ConcatR) 16455 return SDValue(); 16456 16457 // If one of the binop operands was not the result of a concat, we must 16458 // extract a half-sized operand for our new narrow binop. We can't just reuse 16459 // the original extract index operand because we may have bitcasted. 16460 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 16461 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 16462 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 16463 SDLoc DL(Extract); 16464 16465 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 16466 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 16467 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 16468 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 16469 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16470 BinOp.getOperand(0), 16471 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16472 16473 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 16474 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16475 BinOp.getOperand(1), 16476 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16477 16478 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 16479 return DAG.getBitcast(VT, NarrowBinOp); 16480 } 16481 16482 /// If we are extracting a subvector from a wide vector load, convert to a 16483 /// narrow load to eliminate the extraction: 16484 /// (extract_subvector (load wide vector)) --> (load narrow vector) 16485 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 16486 // TODO: Add support for big-endian. The offset calculation must be adjusted. 16487 if (DAG.getDataLayout().isBigEndian()) 16488 return SDValue(); 16489 16490 // TODO: The one-use check is overly conservative. Check the cost of the 16491 // extract instead or remove that condition entirely. 16492 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 16493 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16494 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 16495 !ExtIdx) 16496 return SDValue(); 16497 16498 // The narrow load will be offset from the base address of the old load if 16499 // we are extracting from something besides index 0 (little-endian). 16500 EVT VT = Extract->getValueType(0); 16501 SDLoc DL(Extract); 16502 SDValue BaseAddr = Ld->getOperand(1); 16503 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 16504 16505 // TODO: Use "BaseIndexOffset" to make this more effective. 16506 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 16507 MachineFunction &MF = DAG.getMachineFunction(); 16508 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 16509 VT.getStoreSize()); 16510 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 16511 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 16512 return NewLd; 16513 } 16514 16515 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 16516 EVT NVT = N->getValueType(0); 16517 SDValue V = N->getOperand(0); 16518 16519 // Extract from UNDEF is UNDEF. 16520 if (V.isUndef()) 16521 return DAG.getUNDEF(NVT); 16522 16523 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 16524 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 16525 return NarrowLoad; 16526 16527 // Combine: 16528 // (extract_subvec (concat V1, V2, ...), i) 16529 // Into: 16530 // Vi if possible 16531 // Only operand 0 is checked as 'concat' assumes all inputs of the same 16532 // type. 16533 if (V->getOpcode() == ISD::CONCAT_VECTORS && 16534 isa<ConstantSDNode>(N->getOperand(1)) && 16535 V->getOperand(0).getValueType() == NVT) { 16536 unsigned Idx = N->getConstantOperandVal(1); 16537 unsigned NumElems = NVT.getVectorNumElements(); 16538 assert((Idx % NumElems) == 0 && 16539 "IDX in concat is not a multiple of the result vector length."); 16540 return V->getOperand(Idx / NumElems); 16541 } 16542 16543 // Skip bitcasting 16544 V = peekThroughBitcast(V); 16545 16546 // If the input is a build vector. Try to make a smaller build vector. 16547 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16548 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 16549 EVT InVT = V->getValueType(0); 16550 unsigned ExtractSize = NVT.getSizeInBits(); 16551 unsigned EltSize = InVT.getScalarSizeInBits(); 16552 // Only do this if we won't split any elements. 16553 if (ExtractSize % EltSize == 0) { 16554 unsigned NumElems = ExtractSize / EltSize; 16555 EVT EltVT = InVT.getVectorElementType(); 16556 EVT ExtractVT = NumElems == 1 ? EltVT : 16557 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 16558 if ((Level < AfterLegalizeDAG || 16559 (NumElems == 1 || 16560 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 16561 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 16562 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 16563 EltSize; 16564 if (NumElems == 1) { 16565 SDValue Src = V->getOperand(IdxVal); 16566 if (EltVT != Src.getValueType()) 16567 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 16568 16569 return DAG.getBitcast(NVT, Src); 16570 } 16571 16572 // Extract the pieces from the original build_vector. 16573 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 16574 makeArrayRef(V->op_begin() + IdxVal, 16575 NumElems)); 16576 return DAG.getBitcast(NVT, BuildVec); 16577 } 16578 } 16579 } 16580 } 16581 16582 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 16583 // Handle only simple case where vector being inserted and vector 16584 // being extracted are of same size. 16585 EVT SmallVT = V->getOperand(1).getValueType(); 16586 if (!NVT.bitsEq(SmallVT)) 16587 return SDValue(); 16588 16589 // Only handle cases where both indexes are constants. 16590 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16591 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 16592 16593 if (InsIdx && ExtIdx) { 16594 // Combine: 16595 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 16596 // Into: 16597 // indices are equal or bit offsets are equal => V1 16598 // otherwise => (extract_subvec V1, ExtIdx) 16599 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 16600 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 16601 return DAG.getBitcast(NVT, V->getOperand(1)); 16602 return DAG.getNode( 16603 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 16604 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 16605 N->getOperand(1)); 16606 } 16607 } 16608 16609 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 16610 return NarrowBOp; 16611 16612 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 16613 return SDValue(N, 0); 16614 16615 return SDValue(); 16616 } 16617 16618 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 16619 // or turn a shuffle of a single concat into simpler shuffle then concat. 16620 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 16621 EVT VT = N->getValueType(0); 16622 unsigned NumElts = VT.getVectorNumElements(); 16623 16624 SDValue N0 = N->getOperand(0); 16625 SDValue N1 = N->getOperand(1); 16626 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 16627 16628 SmallVector<SDValue, 4> Ops; 16629 EVT ConcatVT = N0.getOperand(0).getValueType(); 16630 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 16631 unsigned NumConcats = NumElts / NumElemsPerConcat; 16632 16633 // Special case: shuffle(concat(A,B)) can be more efficiently represented 16634 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 16635 // half vector elements. 16636 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 16637 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 16638 SVN->getMask().end(), [](int i) { return i == -1; })) { 16639 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 16640 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 16641 N1 = DAG.getUNDEF(ConcatVT); 16642 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 16643 } 16644 16645 // Look at every vector that's inserted. We're looking for exact 16646 // subvector-sized copies from a concatenated vector 16647 for (unsigned I = 0; I != NumConcats; ++I) { 16648 // Make sure we're dealing with a copy. 16649 unsigned Begin = I * NumElemsPerConcat; 16650 bool AllUndef = true, NoUndef = true; 16651 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 16652 if (SVN->getMaskElt(J) >= 0) 16653 AllUndef = false; 16654 else 16655 NoUndef = false; 16656 } 16657 16658 if (NoUndef) { 16659 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 16660 return SDValue(); 16661 16662 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 16663 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 16664 return SDValue(); 16665 16666 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 16667 if (FirstElt < N0.getNumOperands()) 16668 Ops.push_back(N0.getOperand(FirstElt)); 16669 else 16670 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 16671 16672 } else if (AllUndef) { 16673 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 16674 } else { // Mixed with general masks and undefs, can't do optimization. 16675 return SDValue(); 16676 } 16677 } 16678 16679 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16680 } 16681 16682 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16683 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16684 // 16685 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 16686 // a simplification in some sense, but it isn't appropriate in general: some 16687 // BUILD_VECTORs are substantially cheaper than others. The general case 16688 // of a BUILD_VECTOR requires inserting each element individually (or 16689 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 16690 // all constants is a single constant pool load. A BUILD_VECTOR where each 16691 // element is identical is a splat. A BUILD_VECTOR where most of the operands 16692 // are undef lowers to a small number of element insertions. 16693 // 16694 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 16695 // We don't fold shuffles where one side is a non-zero constant, and we don't 16696 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 16697 // non-constant operands. This seems to work out reasonably well in practice. 16698 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 16699 SelectionDAG &DAG, 16700 const TargetLowering &TLI) { 16701 EVT VT = SVN->getValueType(0); 16702 unsigned NumElts = VT.getVectorNumElements(); 16703 SDValue N0 = SVN->getOperand(0); 16704 SDValue N1 = SVN->getOperand(1); 16705 16706 if (!N0->hasOneUse() || !N1->hasOneUse()) 16707 return SDValue(); 16708 16709 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 16710 // discussed above. 16711 if (!N1.isUndef()) { 16712 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 16713 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 16714 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 16715 return SDValue(); 16716 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 16717 return SDValue(); 16718 } 16719 16720 // If both inputs are splats of the same value then we can safely merge this 16721 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 16722 bool IsSplat = false; 16723 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 16724 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 16725 if (BV0 && BV1) 16726 if (SDValue Splat0 = BV0->getSplatValue()) 16727 IsSplat = (Splat0 == BV1->getSplatValue()); 16728 16729 SmallVector<SDValue, 8> Ops; 16730 SmallSet<SDValue, 16> DuplicateOps; 16731 for (int M : SVN->getMask()) { 16732 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 16733 if (M >= 0) { 16734 int Idx = M < (int)NumElts ? M : M - NumElts; 16735 SDValue &S = (M < (int)NumElts ? N0 : N1); 16736 if (S.getOpcode() == ISD::BUILD_VECTOR) { 16737 Op = S.getOperand(Idx); 16738 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 16739 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 16740 Op = S.getOperand(0); 16741 } else { 16742 // Operand can't be combined - bail out. 16743 return SDValue(); 16744 } 16745 } 16746 16747 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 16748 // generating a splat; semantically, this is fine, but it's likely to 16749 // generate low-quality code if the target can't reconstruct an appropriate 16750 // shuffle. 16751 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 16752 if (!IsSplat && !DuplicateOps.insert(Op).second) 16753 return SDValue(); 16754 16755 Ops.push_back(Op); 16756 } 16757 16758 // BUILD_VECTOR requires all inputs to be of the same type, find the 16759 // maximum type and extend them all. 16760 EVT SVT = VT.getScalarType(); 16761 if (SVT.isInteger()) 16762 for (SDValue &Op : Ops) 16763 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 16764 if (SVT != VT.getScalarType()) 16765 for (SDValue &Op : Ops) 16766 Op = TLI.isZExtFree(Op.getValueType(), SVT) 16767 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 16768 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 16769 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 16770 } 16771 16772 // Match shuffles that can be converted to any_vector_extend_in_reg. 16773 // This is often generated during legalization. 16774 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 16775 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 16776 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 16777 SelectionDAG &DAG, 16778 const TargetLowering &TLI, 16779 bool LegalOperations, 16780 bool LegalTypes) { 16781 EVT VT = SVN->getValueType(0); 16782 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 16783 16784 // TODO Add support for big-endian when we have a test case. 16785 if (!VT.isInteger() || IsBigEndian) 16786 return SDValue(); 16787 16788 unsigned NumElts = VT.getVectorNumElements(); 16789 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 16790 ArrayRef<int> Mask = SVN->getMask(); 16791 SDValue N0 = SVN->getOperand(0); 16792 16793 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 16794 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 16795 for (unsigned i = 0; i != NumElts; ++i) { 16796 if (Mask[i] < 0) 16797 continue; 16798 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 16799 continue; 16800 return false; 16801 } 16802 return true; 16803 }; 16804 16805 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 16806 // power-of-2 extensions as they are the most likely. 16807 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 16808 // Check for non power of 2 vector sizes 16809 if (NumElts % Scale != 0) 16810 continue; 16811 if (!isAnyExtend(Scale)) 16812 continue; 16813 16814 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 16815 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 16816 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 16817 if (!LegalOperations || 16818 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 16819 return DAG.getBitcast(VT, 16820 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 16821 } 16822 16823 return SDValue(); 16824 } 16825 16826 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 16827 // each source element of a large type into the lowest elements of a smaller 16828 // destination type. This is often generated during legalization. 16829 // If the source node itself was a '*_extend_vector_inreg' node then we should 16830 // then be able to remove it. 16831 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 16832 SelectionDAG &DAG) { 16833 EVT VT = SVN->getValueType(0); 16834 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 16835 16836 // TODO Add support for big-endian when we have a test case. 16837 if (!VT.isInteger() || IsBigEndian) 16838 return SDValue(); 16839 16840 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 16841 16842 unsigned Opcode = N0.getOpcode(); 16843 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 16844 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 16845 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 16846 return SDValue(); 16847 16848 SDValue N00 = N0.getOperand(0); 16849 ArrayRef<int> Mask = SVN->getMask(); 16850 unsigned NumElts = VT.getVectorNumElements(); 16851 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 16852 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 16853 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 16854 16855 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 16856 return SDValue(); 16857 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 16858 16859 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 16860 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 16861 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 16862 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 16863 for (unsigned i = 0; i != NumElts; ++i) { 16864 if (Mask[i] < 0) 16865 continue; 16866 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 16867 continue; 16868 return false; 16869 } 16870 return true; 16871 }; 16872 16873 // At the moment we just handle the case where we've truncated back to the 16874 // same size as before the extension. 16875 // TODO: handle more extension/truncation cases as cases arise. 16876 if (EltSizeInBits != ExtSrcSizeInBits) 16877 return SDValue(); 16878 16879 // We can remove *extend_vector_inreg only if the truncation happens at 16880 // the same scale as the extension. 16881 if (isTruncate(ExtScale)) 16882 return DAG.getBitcast(VT, N00); 16883 16884 return SDValue(); 16885 } 16886 16887 // Combine shuffles of splat-shuffles of the form: 16888 // shuffle (shuffle V, undef, splat-mask), undef, M 16889 // If splat-mask contains undef elements, we need to be careful about 16890 // introducing undef's in the folded mask which are not the result of composing 16891 // the masks of the shuffles. 16892 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 16893 ShuffleVectorSDNode *Splat, 16894 SelectionDAG &DAG) { 16895 ArrayRef<int> SplatMask = Splat->getMask(); 16896 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 16897 16898 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 16899 // every undef mask element in the splat-shuffle has a corresponding undef 16900 // element in the user-shuffle's mask or if the composition of mask elements 16901 // would result in undef. 16902 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 16903 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 16904 // In this case it is not legal to simplify to the splat-shuffle because we 16905 // may be exposing the users of the shuffle an undef element at index 1 16906 // which was not there before the combine. 16907 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 16908 // In this case the composition of masks yields SplatMask, so it's ok to 16909 // simplify to the splat-shuffle. 16910 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 16911 // In this case the composed mask includes all undef elements of SplatMask 16912 // and in addition sets element zero to undef. It is safe to simplify to 16913 // the splat-shuffle. 16914 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 16915 ArrayRef<int> SplatMask) { 16916 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 16917 if (UserMask[i] != -1 && SplatMask[i] == -1 && 16918 SplatMask[UserMask[i]] != -1) 16919 return false; 16920 return true; 16921 }; 16922 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 16923 return SDValue(Splat, 0); 16924 16925 // Create a new shuffle with a mask that is composed of the two shuffles' 16926 // masks. 16927 SmallVector<int, 32> NewMask; 16928 for (int Idx : UserMask) 16929 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 16930 16931 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 16932 Splat->getOperand(0), Splat->getOperand(1), 16933 NewMask); 16934 } 16935 16936 /// If the shuffle mask is taking exactly one element from the first vector 16937 /// operand and passing through all other elements from the second vector 16938 /// operand, return the index of the mask element that is choosing an element 16939 /// from the first operand. Otherwise, return -1. 16940 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 16941 int MaskSize = Mask.size(); 16942 int EltFromOp0 = -1; 16943 // TODO: This does not match if there are undef elements in the shuffle mask. 16944 // Should we ignore undefs in the shuffle mask instead? The trade-off is 16945 // removing an instruction (a shuffle), but losing the knowledge that some 16946 // vector lanes are not needed. 16947 for (int i = 0; i != MaskSize; ++i) { 16948 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 16949 // We're looking for a shuffle of exactly one element from operand 0. 16950 if (EltFromOp0 != -1) 16951 return -1; 16952 EltFromOp0 = i; 16953 } else if (Mask[i] != i + MaskSize) { 16954 // Nothing from operand 1 can change lanes. 16955 return -1; 16956 } 16957 } 16958 return EltFromOp0; 16959 } 16960 16961 /// If a shuffle inserts exactly one element from a source vector operand into 16962 /// another vector operand and we can access the specified element as a scalar, 16963 /// then we can eliminate the shuffle. 16964 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 16965 SelectionDAG &DAG) { 16966 // First, check if we are taking one element of a vector and shuffling that 16967 // element into another vector. 16968 ArrayRef<int> Mask = Shuf->getMask(); 16969 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 16970 SDValue Op0 = Shuf->getOperand(0); 16971 SDValue Op1 = Shuf->getOperand(1); 16972 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 16973 if (ShufOp0Index == -1) { 16974 // Commute mask and check again. 16975 ShuffleVectorSDNode::commuteMask(CommutedMask); 16976 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 16977 if (ShufOp0Index == -1) 16978 return SDValue(); 16979 // Commute operands to match the commuted shuffle mask. 16980 std::swap(Op0, Op1); 16981 Mask = CommutedMask; 16982 } 16983 16984 // The shuffle inserts exactly one element from operand 0 into operand 1. 16985 // Now see if we can access that element as a scalar via a real insert element 16986 // instruction. 16987 // TODO: We can try harder to locate the element as a scalar. Examples: it 16988 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 16989 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 16990 "Shuffle mask value must be from operand 0"); 16991 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 16992 return SDValue(); 16993 16994 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 16995 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 16996 return SDValue(); 16997 16998 // There's an existing insertelement with constant insertion index, so we 16999 // don't need to check the legality/profitability of a replacement operation 17000 // that differs at most in the constant value. The target should be able to 17001 // lower any of those in a similar way. If not, legalization will expand this 17002 // to a scalar-to-vector plus shuffle. 17003 // 17004 // Note that the shuffle may move the scalar from the position that the insert 17005 // element used. Therefore, our new insert element occurs at the shuffle's 17006 // mask index value, not the insert's index value. 17007 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 17008 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 17009 Op0.getOperand(2).getValueType()); 17010 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 17011 Op1, Op0.getOperand(1), NewInsIndex); 17012 } 17013 17014 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 17015 EVT VT = N->getValueType(0); 17016 unsigned NumElts = VT.getVectorNumElements(); 17017 17018 SDValue N0 = N->getOperand(0); 17019 SDValue N1 = N->getOperand(1); 17020 17021 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 17022 17023 // Canonicalize shuffle undef, undef -> undef 17024 if (N0.isUndef() && N1.isUndef()) 17025 return DAG.getUNDEF(VT); 17026 17027 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 17028 17029 // Canonicalize shuffle v, v -> v, undef 17030 if (N0 == N1) { 17031 SmallVector<int, 8> NewMask; 17032 for (unsigned i = 0; i != NumElts; ++i) { 17033 int Idx = SVN->getMaskElt(i); 17034 if (Idx >= (int)NumElts) Idx -= NumElts; 17035 NewMask.push_back(Idx); 17036 } 17037 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 17038 } 17039 17040 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 17041 if (N0.isUndef()) 17042 return DAG.getCommutedVectorShuffle(*SVN); 17043 17044 // Remove references to rhs if it is undef 17045 if (N1.isUndef()) { 17046 bool Changed = false; 17047 SmallVector<int, 8> NewMask; 17048 for (unsigned i = 0; i != NumElts; ++i) { 17049 int Idx = SVN->getMaskElt(i); 17050 if (Idx >= (int)NumElts) { 17051 Idx = -1; 17052 Changed = true; 17053 } 17054 NewMask.push_back(Idx); 17055 } 17056 if (Changed) 17057 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 17058 } 17059 17060 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 17061 return InsElt; 17062 17063 // A shuffle of a single vector that is a splat can always be folded. 17064 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 17065 if (N1->isUndef() && N0Shuf->isSplat()) 17066 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 17067 17068 // If it is a splat, check if the argument vector is another splat or a 17069 // build_vector. 17070 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 17071 SDNode *V = N0.getNode(); 17072 17073 // If this is a bit convert that changes the element type of the vector but 17074 // not the number of vector elements, look through it. Be careful not to 17075 // look though conversions that change things like v4f32 to v2f64. 17076 if (V->getOpcode() == ISD::BITCAST) { 17077 SDValue ConvInput = V->getOperand(0); 17078 if (ConvInput.getValueType().isVector() && 17079 ConvInput.getValueType().getVectorNumElements() == NumElts) 17080 V = ConvInput.getNode(); 17081 } 17082 17083 if (V->getOpcode() == ISD::BUILD_VECTOR) { 17084 assert(V->getNumOperands() == NumElts && 17085 "BUILD_VECTOR has wrong number of operands"); 17086 SDValue Base; 17087 bool AllSame = true; 17088 for (unsigned i = 0; i != NumElts; ++i) { 17089 if (!V->getOperand(i).isUndef()) { 17090 Base = V->getOperand(i); 17091 break; 17092 } 17093 } 17094 // Splat of <u, u, u, u>, return <u, u, u, u> 17095 if (!Base.getNode()) 17096 return N0; 17097 for (unsigned i = 0; i != NumElts; ++i) { 17098 if (V->getOperand(i) != Base) { 17099 AllSame = false; 17100 break; 17101 } 17102 } 17103 // Splat of <x, x, x, x>, return <x, x, x, x> 17104 if (AllSame) 17105 return N0; 17106 17107 // Canonicalize any other splat as a build_vector. 17108 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 17109 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 17110 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 17111 17112 // We may have jumped through bitcasts, so the type of the 17113 // BUILD_VECTOR may not match the type of the shuffle. 17114 if (V->getValueType(0) != VT) 17115 NewBV = DAG.getBitcast(VT, NewBV); 17116 return NewBV; 17117 } 17118 } 17119 17120 // Simplify source operands based on shuffle mask. 17121 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 17122 return SDValue(N, 0); 17123 17124 // Match shuffles that can be converted to any_vector_extend_in_reg. 17125 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 17126 return V; 17127 17128 // Combine "truncate_vector_in_reg" style shuffles. 17129 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 17130 return V; 17131 17132 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 17133 Level < AfterLegalizeVectorOps && 17134 (N1.isUndef() || 17135 (N1.getOpcode() == ISD::CONCAT_VECTORS && 17136 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 17137 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 17138 return V; 17139 } 17140 17141 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 17142 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 17143 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 17144 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 17145 return Res; 17146 17147 // If this shuffle only has a single input that is a bitcasted shuffle, 17148 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 17149 // back to their original types. 17150 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 17151 N1.isUndef() && Level < AfterLegalizeVectorOps && 17152 TLI.isTypeLegal(VT)) { 17153 17154 // Peek through the bitcast only if there is one user. 17155 SDValue BC0 = N0; 17156 while (BC0.getOpcode() == ISD::BITCAST) { 17157 if (!BC0.hasOneUse()) 17158 break; 17159 BC0 = BC0.getOperand(0); 17160 } 17161 17162 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 17163 if (Scale == 1) 17164 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 17165 17166 SmallVector<int, 8> NewMask; 17167 for (int M : Mask) 17168 for (int s = 0; s != Scale; ++s) 17169 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 17170 return NewMask; 17171 }; 17172 17173 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 17174 EVT SVT = VT.getScalarType(); 17175 EVT InnerVT = BC0->getValueType(0); 17176 EVT InnerSVT = InnerVT.getScalarType(); 17177 17178 // Determine which shuffle works with the smaller scalar type. 17179 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 17180 EVT ScaleSVT = ScaleVT.getScalarType(); 17181 17182 if (TLI.isTypeLegal(ScaleVT) && 17183 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 17184 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 17185 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17186 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17187 17188 // Scale the shuffle masks to the smaller scalar type. 17189 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 17190 SmallVector<int, 8> InnerMask = 17191 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 17192 SmallVector<int, 8> OuterMask = 17193 ScaleShuffleMask(SVN->getMask(), OuterScale); 17194 17195 // Merge the shuffle masks. 17196 SmallVector<int, 8> NewMask; 17197 for (int M : OuterMask) 17198 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 17199 17200 // Test for shuffle mask legality over both commutations. 17201 SDValue SV0 = BC0->getOperand(0); 17202 SDValue SV1 = BC0->getOperand(1); 17203 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17204 if (!LegalMask) { 17205 std::swap(SV0, SV1); 17206 ShuffleVectorSDNode::commuteMask(NewMask); 17207 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17208 } 17209 17210 if (LegalMask) { 17211 SV0 = DAG.getBitcast(ScaleVT, SV0); 17212 SV1 = DAG.getBitcast(ScaleVT, SV1); 17213 return DAG.getBitcast( 17214 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 17215 } 17216 } 17217 } 17218 } 17219 17220 // Canonicalize shuffles according to rules: 17221 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 17222 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 17223 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 17224 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 17225 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 17226 TLI.isTypeLegal(VT)) { 17227 // The incoming shuffle must be of the same type as the result of the 17228 // current shuffle. 17229 assert(N1->getOperand(0).getValueType() == VT && 17230 "Shuffle types don't match"); 17231 17232 SDValue SV0 = N1->getOperand(0); 17233 SDValue SV1 = N1->getOperand(1); 17234 bool HasSameOp0 = N0 == SV0; 17235 bool IsSV1Undef = SV1.isUndef(); 17236 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 17237 // Commute the operands of this shuffle so that next rule 17238 // will trigger. 17239 return DAG.getCommutedVectorShuffle(*SVN); 17240 } 17241 17242 // Try to fold according to rules: 17243 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17244 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17245 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17246 // Don't try to fold shuffles with illegal type. 17247 // Only fold if this shuffle is the only user of the other shuffle. 17248 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 17249 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 17250 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 17251 17252 // Don't try to fold splats; they're likely to simplify somehow, or they 17253 // might be free. 17254 if (OtherSV->isSplat()) 17255 return SDValue(); 17256 17257 // The incoming shuffle must be of the same type as the result of the 17258 // current shuffle. 17259 assert(OtherSV->getOperand(0).getValueType() == VT && 17260 "Shuffle types don't match"); 17261 17262 SDValue SV0, SV1; 17263 SmallVector<int, 4> Mask; 17264 // Compute the combined shuffle mask for a shuffle with SV0 as the first 17265 // operand, and SV1 as the second operand. 17266 for (unsigned i = 0; i != NumElts; ++i) { 17267 int Idx = SVN->getMaskElt(i); 17268 if (Idx < 0) { 17269 // Propagate Undef. 17270 Mask.push_back(Idx); 17271 continue; 17272 } 17273 17274 SDValue CurrentVec; 17275 if (Idx < (int)NumElts) { 17276 // This shuffle index refers to the inner shuffle N0. Lookup the inner 17277 // shuffle mask to identify which vector is actually referenced. 17278 Idx = OtherSV->getMaskElt(Idx); 17279 if (Idx < 0) { 17280 // Propagate Undef. 17281 Mask.push_back(Idx); 17282 continue; 17283 } 17284 17285 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 17286 : OtherSV->getOperand(1); 17287 } else { 17288 // This shuffle index references an element within N1. 17289 CurrentVec = N1; 17290 } 17291 17292 // Simple case where 'CurrentVec' is UNDEF. 17293 if (CurrentVec.isUndef()) { 17294 Mask.push_back(-1); 17295 continue; 17296 } 17297 17298 // Canonicalize the shuffle index. We don't know yet if CurrentVec 17299 // will be the first or second operand of the combined shuffle. 17300 Idx = Idx % NumElts; 17301 if (!SV0.getNode() || SV0 == CurrentVec) { 17302 // Ok. CurrentVec is the left hand side. 17303 // Update the mask accordingly. 17304 SV0 = CurrentVec; 17305 Mask.push_back(Idx); 17306 continue; 17307 } 17308 17309 // Bail out if we cannot convert the shuffle pair into a single shuffle. 17310 if (SV1.getNode() && SV1 != CurrentVec) 17311 return SDValue(); 17312 17313 // Ok. CurrentVec is the right hand side. 17314 // Update the mask accordingly. 17315 SV1 = CurrentVec; 17316 Mask.push_back(Idx + NumElts); 17317 } 17318 17319 // Check if all indices in Mask are Undef. In case, propagate Undef. 17320 bool isUndefMask = true; 17321 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 17322 isUndefMask &= Mask[i] < 0; 17323 17324 if (isUndefMask) 17325 return DAG.getUNDEF(VT); 17326 17327 if (!SV0.getNode()) 17328 SV0 = DAG.getUNDEF(VT); 17329 if (!SV1.getNode()) 17330 SV1 = DAG.getUNDEF(VT); 17331 17332 // Avoid introducing shuffles with illegal mask. 17333 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 17334 ShuffleVectorSDNode::commuteMask(Mask); 17335 17336 if (!TLI.isShuffleMaskLegal(Mask, VT)) 17337 return SDValue(); 17338 17339 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 17340 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 17341 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 17342 std::swap(SV0, SV1); 17343 } 17344 17345 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17346 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17347 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17348 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 17349 } 17350 17351 return SDValue(); 17352 } 17353 17354 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 17355 SDValue InVal = N->getOperand(0); 17356 EVT VT = N->getValueType(0); 17357 17358 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 17359 // with a VECTOR_SHUFFLE and possible truncate. 17360 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 17361 SDValue InVec = InVal->getOperand(0); 17362 SDValue EltNo = InVal->getOperand(1); 17363 auto InVecT = InVec.getValueType(); 17364 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 17365 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 17366 int Elt = C0->getZExtValue(); 17367 NewMask[0] = Elt; 17368 SDValue Val; 17369 // If we have an implict truncate do truncate here as long as it's legal. 17370 // if it's not legal, this should 17371 if (VT.getScalarType() != InVal.getValueType() && 17372 InVal.getValueType().isScalarInteger() && 17373 isTypeLegal(VT.getScalarType())) { 17374 Val = 17375 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 17376 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 17377 } 17378 if (VT.getScalarType() == InVecT.getScalarType() && 17379 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 17380 TLI.isShuffleMaskLegal(NewMask, VT)) { 17381 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 17382 DAG.getUNDEF(InVecT), NewMask); 17383 // If the initial vector is the correct size this shuffle is a 17384 // valid result. 17385 if (VT == InVecT) 17386 return Val; 17387 // If not we must truncate the vector. 17388 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 17389 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 17390 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 17391 EVT SubVT = 17392 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 17393 VT.getVectorNumElements()); 17394 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 17395 ZeroIdx); 17396 return Val; 17397 } 17398 } 17399 } 17400 } 17401 17402 return SDValue(); 17403 } 17404 17405 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 17406 EVT VT = N->getValueType(0); 17407 SDValue N0 = N->getOperand(0); 17408 SDValue N1 = N->getOperand(1); 17409 SDValue N2 = N->getOperand(2); 17410 17411 // If inserting an UNDEF, just return the original vector. 17412 if (N1.isUndef()) 17413 return N0; 17414 17415 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 17416 // us to pull BITCASTs from input to output. 17417 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 17418 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 17419 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 17420 17421 // If this is an insert of an extracted vector into an undef vector, we can 17422 // just use the input to the extract. 17423 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 17424 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 17425 return N1.getOperand(0); 17426 17427 // If we are inserting a bitcast value into an undef, with the same 17428 // number of elements, just use the bitcast input of the extract. 17429 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 17430 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 17431 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 17432 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 17433 N1.getOperand(0).getOperand(1) == N2 && 17434 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 17435 VT.getVectorNumElements() && 17436 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 17437 VT.getSizeInBits()) { 17438 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 17439 } 17440 17441 // If both N1 and N2 are bitcast values on which insert_subvector 17442 // would makes sense, pull the bitcast through. 17443 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 17444 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 17445 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 17446 SDValue CN0 = N0.getOperand(0); 17447 SDValue CN1 = N1.getOperand(0); 17448 EVT CN0VT = CN0.getValueType(); 17449 EVT CN1VT = CN1.getValueType(); 17450 if (CN0VT.isVector() && CN1VT.isVector() && 17451 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 17452 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) { 17453 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 17454 CN0.getValueType(), CN0, CN1, N2); 17455 return DAG.getBitcast(VT, NewINSERT); 17456 } 17457 } 17458 17459 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 17460 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 17461 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 17462 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 17463 N0.getOperand(1).getValueType() == N1.getValueType() && 17464 N0.getOperand(2) == N2) 17465 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 17466 N1, N2); 17467 17468 if (!isa<ConstantSDNode>(N2)) 17469 return SDValue(); 17470 17471 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 17472 17473 // Canonicalize insert_subvector dag nodes. 17474 // Example: 17475 // (insert_subvector (insert_subvector A, Idx0), Idx1) 17476 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 17477 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 17478 N1.getValueType() == N0.getOperand(1).getValueType() && 17479 isa<ConstantSDNode>(N0.getOperand(2))) { 17480 unsigned OtherIdx = N0.getConstantOperandVal(2); 17481 if (InsIdx < OtherIdx) { 17482 // Swap nodes. 17483 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 17484 N0.getOperand(0), N1, N2); 17485 AddToWorklist(NewOp.getNode()); 17486 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 17487 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 17488 } 17489 } 17490 17491 // If the input vector is a concatenation, and the insert replaces 17492 // one of the pieces, we can optimize into a single concat_vectors. 17493 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 17494 N0.getOperand(0).getValueType() == N1.getValueType()) { 17495 unsigned Factor = N1.getValueType().getVectorNumElements(); 17496 17497 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 17498 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 17499 17500 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 17501 } 17502 17503 return SDValue(); 17504 } 17505 17506 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 17507 SDValue N0 = N->getOperand(0); 17508 17509 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 17510 if (N0->getOpcode() == ISD::FP16_TO_FP) 17511 return N0->getOperand(0); 17512 17513 return SDValue(); 17514 } 17515 17516 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 17517 SDValue N0 = N->getOperand(0); 17518 17519 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 17520 if (N0->getOpcode() == ISD::AND) { 17521 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 17522 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 17523 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 17524 N0.getOperand(0)); 17525 } 17526 } 17527 17528 return SDValue(); 17529 } 17530 17531 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 17532 /// with the destination vector and a zero vector. 17533 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 17534 /// vector_shuffle V, Zero, <0, 4, 2, 4> 17535 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 17536 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 17537 17538 EVT VT = N->getValueType(0); 17539 SDValue LHS = N->getOperand(0); 17540 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 17541 SDLoc DL(N); 17542 17543 // Make sure we're not running after operation legalization where it 17544 // may have custom lowered the vector shuffles. 17545 if (LegalOperations) 17546 return SDValue(); 17547 17548 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 17549 return SDValue(); 17550 17551 EVT RVT = RHS.getValueType(); 17552 unsigned NumElts = RHS.getNumOperands(); 17553 17554 // Attempt to create a valid clear mask, splitting the mask into 17555 // sub elements and checking to see if each is 17556 // all zeros or all ones - suitable for shuffle masking. 17557 auto BuildClearMask = [&](int Split) { 17558 int NumSubElts = NumElts * Split; 17559 int NumSubBits = RVT.getScalarSizeInBits() / Split; 17560 17561 SmallVector<int, 8> Indices; 17562 for (int i = 0; i != NumSubElts; ++i) { 17563 int EltIdx = i / Split; 17564 int SubIdx = i % Split; 17565 SDValue Elt = RHS.getOperand(EltIdx); 17566 if (Elt.isUndef()) { 17567 Indices.push_back(-1); 17568 continue; 17569 } 17570 17571 APInt Bits; 17572 if (isa<ConstantSDNode>(Elt)) 17573 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 17574 else if (isa<ConstantFPSDNode>(Elt)) 17575 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 17576 else 17577 return SDValue(); 17578 17579 // Extract the sub element from the constant bit mask. 17580 if (DAG.getDataLayout().isBigEndian()) { 17581 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 17582 } else { 17583 Bits.lshrInPlace(SubIdx * NumSubBits); 17584 } 17585 17586 if (Split > 1) 17587 Bits = Bits.trunc(NumSubBits); 17588 17589 if (Bits.isAllOnesValue()) 17590 Indices.push_back(i); 17591 else if (Bits == 0) 17592 Indices.push_back(i + NumSubElts); 17593 else 17594 return SDValue(); 17595 } 17596 17597 // Let's see if the target supports this vector_shuffle. 17598 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 17599 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 17600 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 17601 return SDValue(); 17602 17603 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 17604 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 17605 DAG.getBitcast(ClearVT, LHS), 17606 Zero, Indices)); 17607 }; 17608 17609 // Determine maximum split level (byte level masking). 17610 int MaxSplit = 1; 17611 if (RVT.getScalarSizeInBits() % 8 == 0) 17612 MaxSplit = RVT.getScalarSizeInBits() / 8; 17613 17614 for (int Split = 1; Split <= MaxSplit; ++Split) 17615 if (RVT.getScalarSizeInBits() % Split == 0) 17616 if (SDValue S = BuildClearMask(Split)) 17617 return S; 17618 17619 return SDValue(); 17620 } 17621 17622 /// Visit a binary vector operation, like ADD. 17623 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 17624 assert(N->getValueType(0).isVector() && 17625 "SimplifyVBinOp only works on vectors!"); 17626 17627 SDValue LHS = N->getOperand(0); 17628 SDValue RHS = N->getOperand(1); 17629 SDValue Ops[] = {LHS, RHS}; 17630 17631 // See if we can constant fold the vector operation. 17632 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 17633 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 17634 return Fold; 17635 17636 // Type legalization might introduce new shuffles in the DAG. 17637 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 17638 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 17639 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 17640 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 17641 LHS.getOperand(1).isUndef() && 17642 RHS.getOperand(1).isUndef()) { 17643 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 17644 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 17645 17646 if (SVN0->getMask().equals(SVN1->getMask())) { 17647 EVT VT = N->getValueType(0); 17648 SDValue UndefVector = LHS.getOperand(1); 17649 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 17650 LHS.getOperand(0), RHS.getOperand(0), 17651 N->getFlags()); 17652 AddUsersToWorklist(N); 17653 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 17654 SVN0->getMask()); 17655 } 17656 } 17657 17658 return SDValue(); 17659 } 17660 17661 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 17662 SDValue N2) { 17663 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 17664 17665 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 17666 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 17667 17668 // If we got a simplified select_cc node back from SimplifySelectCC, then 17669 // break it down into a new SETCC node, and a new SELECT node, and then return 17670 // the SELECT node, since we were called with a SELECT node. 17671 if (SCC.getNode()) { 17672 // Check to see if we got a select_cc back (to turn into setcc/select). 17673 // Otherwise, just return whatever node we got back, like fabs. 17674 if (SCC.getOpcode() == ISD::SELECT_CC) { 17675 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 17676 N0.getValueType(), 17677 SCC.getOperand(0), SCC.getOperand(1), 17678 SCC.getOperand(4)); 17679 AddToWorklist(SETCC.getNode()); 17680 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 17681 SCC.getOperand(2), SCC.getOperand(3)); 17682 } 17683 17684 return SCC; 17685 } 17686 return SDValue(); 17687 } 17688 17689 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 17690 /// being selected between, see if we can simplify the select. Callers of this 17691 /// should assume that TheSelect is deleted if this returns true. As such, they 17692 /// should return the appropriate thing (e.g. the node) back to the top-level of 17693 /// the DAG combiner loop to avoid it being looked at. 17694 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 17695 SDValue RHS) { 17696 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17697 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 17698 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 17699 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 17700 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 17701 SDValue Sqrt = RHS; 17702 ISD::CondCode CC; 17703 SDValue CmpLHS; 17704 const ConstantFPSDNode *Zero = nullptr; 17705 17706 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 17707 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 17708 CmpLHS = TheSelect->getOperand(0); 17709 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 17710 } else { 17711 // SELECT or VSELECT 17712 SDValue Cmp = TheSelect->getOperand(0); 17713 if (Cmp.getOpcode() == ISD::SETCC) { 17714 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 17715 CmpLHS = Cmp.getOperand(0); 17716 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 17717 } 17718 } 17719 if (Zero && Zero->isZero() && 17720 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 17721 CC == ISD::SETULT || CC == ISD::SETLT)) { 17722 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17723 CombineTo(TheSelect, Sqrt); 17724 return true; 17725 } 17726 } 17727 } 17728 // Cannot simplify select with vector condition 17729 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 17730 17731 // If this is a select from two identical things, try to pull the operation 17732 // through the select. 17733 if (LHS.getOpcode() != RHS.getOpcode() || 17734 !LHS.hasOneUse() || !RHS.hasOneUse()) 17735 return false; 17736 17737 // If this is a load and the token chain is identical, replace the select 17738 // of two loads with a load through a select of the address to load from. 17739 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 17740 // constants have been dropped into the constant pool. 17741 if (LHS.getOpcode() == ISD::LOAD) { 17742 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 17743 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 17744 17745 // Token chains must be identical. 17746 if (LHS.getOperand(0) != RHS.getOperand(0) || 17747 // Do not let this transformation reduce the number of volatile loads. 17748 LLD->isVolatile() || RLD->isVolatile() || 17749 // FIXME: If either is a pre/post inc/dec load, 17750 // we'd need to split out the address adjustment. 17751 LLD->isIndexed() || RLD->isIndexed() || 17752 // If this is an EXTLOAD, the VT's must match. 17753 LLD->getMemoryVT() != RLD->getMemoryVT() || 17754 // If this is an EXTLOAD, the kind of extension must match. 17755 (LLD->getExtensionType() != RLD->getExtensionType() && 17756 // The only exception is if one of the extensions is anyext. 17757 LLD->getExtensionType() != ISD::EXTLOAD && 17758 RLD->getExtensionType() != ISD::EXTLOAD) || 17759 // FIXME: this discards src value information. This is 17760 // over-conservative. It would be beneficial to be able to remember 17761 // both potential memory locations. Since we are discarding 17762 // src value info, don't do the transformation if the memory 17763 // locations are not in the default address space. 17764 LLD->getPointerInfo().getAddrSpace() != 0 || 17765 RLD->getPointerInfo().getAddrSpace() != 0 || 17766 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 17767 LLD->getBasePtr().getValueType())) 17768 return false; 17769 17770 // Check that the select condition doesn't reach either load. If so, 17771 // folding this will induce a cycle into the DAG. If not, this is safe to 17772 // xform, so create a select of the addresses. 17773 SDValue Addr; 17774 if (TheSelect->getOpcode() == ISD::SELECT) { 17775 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 17776 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 17777 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 17778 return false; 17779 // The loads must not depend on one another. 17780 if (LLD->isPredecessorOf(RLD) || 17781 RLD->isPredecessorOf(LLD)) 17782 return false; 17783 Addr = DAG.getSelect(SDLoc(TheSelect), 17784 LLD->getBasePtr().getValueType(), 17785 TheSelect->getOperand(0), LLD->getBasePtr(), 17786 RLD->getBasePtr()); 17787 } else { // Otherwise SELECT_CC 17788 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 17789 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 17790 17791 if ((LLD->hasAnyUseOfValue(1) && 17792 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 17793 (RLD->hasAnyUseOfValue(1) && 17794 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 17795 return false; 17796 17797 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 17798 LLD->getBasePtr().getValueType(), 17799 TheSelect->getOperand(0), 17800 TheSelect->getOperand(1), 17801 LLD->getBasePtr(), RLD->getBasePtr(), 17802 TheSelect->getOperand(4)); 17803 } 17804 17805 SDValue Load; 17806 // It is safe to replace the two loads if they have different alignments, 17807 // but the new load must be the minimum (most restrictive) alignment of the 17808 // inputs. 17809 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 17810 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 17811 if (!RLD->isInvariant()) 17812 MMOFlags &= ~MachineMemOperand::MOInvariant; 17813 if (!RLD->isDereferenceable()) 17814 MMOFlags &= ~MachineMemOperand::MODereferenceable; 17815 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 17816 // FIXME: Discards pointer and AA info. 17817 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 17818 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 17819 MMOFlags); 17820 } else { 17821 // FIXME: Discards pointer and AA info. 17822 Load = DAG.getExtLoad( 17823 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 17824 : LLD->getExtensionType(), 17825 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 17826 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 17827 } 17828 17829 // Users of the select now use the result of the load. 17830 CombineTo(TheSelect, Load); 17831 17832 // Users of the old loads now use the new load's chain. We know the 17833 // old-load value is dead now. 17834 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 17835 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 17836 return true; 17837 } 17838 17839 return false; 17840 } 17841 17842 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 17843 /// bitwise 'and'. 17844 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 17845 SDValue N1, SDValue N2, SDValue N3, 17846 ISD::CondCode CC) { 17847 // If this is a select where the false operand is zero and the compare is a 17848 // check of the sign bit, see if we can perform the "gzip trick": 17849 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 17850 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 17851 EVT XType = N0.getValueType(); 17852 EVT AType = N2.getValueType(); 17853 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 17854 return SDValue(); 17855 17856 // If the comparison is testing for a positive value, we have to invert 17857 // the sign bit mask, so only do that transform if the target has a bitwise 17858 // 'and not' instruction (the invert is free). 17859 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 17860 // (X > -1) ? A : 0 17861 // (X > 0) ? X : 0 <-- This is canonical signed max. 17862 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 17863 return SDValue(); 17864 } else if (CC == ISD::SETLT) { 17865 // (X < 0) ? A : 0 17866 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 17867 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 17868 return SDValue(); 17869 } else { 17870 return SDValue(); 17871 } 17872 17873 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 17874 // constant. 17875 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 17876 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 17877 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 17878 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 17879 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 17880 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 17881 AddToWorklist(Shift.getNode()); 17882 17883 if (XType.bitsGT(AType)) { 17884 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 17885 AddToWorklist(Shift.getNode()); 17886 } 17887 17888 if (CC == ISD::SETGT) 17889 Shift = DAG.getNOT(DL, Shift, AType); 17890 17891 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 17892 } 17893 17894 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 17895 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 17896 AddToWorklist(Shift.getNode()); 17897 17898 if (XType.bitsGT(AType)) { 17899 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 17900 AddToWorklist(Shift.getNode()); 17901 } 17902 17903 if (CC == ISD::SETGT) 17904 Shift = DAG.getNOT(DL, Shift, AType); 17905 17906 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 17907 } 17908 17909 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 17910 /// where 'cond' is the comparison specified by CC. 17911 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 17912 SDValue N2, SDValue N3, ISD::CondCode CC, 17913 bool NotExtCompare) { 17914 // (x ? y : y) -> y. 17915 if (N2 == N3) return N2; 17916 17917 EVT VT = N2.getValueType(); 17918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 17919 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 17920 17921 // Determine if the condition we're dealing with is constant 17922 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 17923 N0, N1, CC, DL, false); 17924 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 17925 17926 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 17927 // fold select_cc true, x, y -> x 17928 // fold select_cc false, x, y -> y 17929 return !SCCC->isNullValue() ? N2 : N3; 17930 } 17931 17932 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 17933 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 17934 // in it. This is a win when the constant is not otherwise available because 17935 // it replaces two constant pool loads with one. We only do this if the FP 17936 // type is known to be legal, because if it isn't, then we are before legalize 17937 // types an we want the other legalization to happen first (e.g. to avoid 17938 // messing with soft float) and if the ConstantFP is not legal, because if 17939 // it is legal, we may not need to store the FP constant in a constant pool. 17940 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 17941 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 17942 if (TLI.isTypeLegal(N2.getValueType()) && 17943 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 17944 TargetLowering::Legal && 17945 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 17946 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 17947 // If both constants have multiple uses, then we won't need to do an 17948 // extra load, they are likely around in registers for other users. 17949 (TV->hasOneUse() || FV->hasOneUse())) { 17950 Constant *Elts[] = { 17951 const_cast<ConstantFP*>(FV->getConstantFPValue()), 17952 const_cast<ConstantFP*>(TV->getConstantFPValue()) 17953 }; 17954 Type *FPTy = Elts[0]->getType(); 17955 const DataLayout &TD = DAG.getDataLayout(); 17956 17957 // Create a ConstantArray of the two constants. 17958 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 17959 SDValue CPIdx = 17960 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 17961 TD.getPrefTypeAlignment(FPTy)); 17962 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 17963 17964 // Get the offsets to the 0 and 1 element of the array so that we can 17965 // select between them. 17966 SDValue Zero = DAG.getIntPtrConstant(0, DL); 17967 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 17968 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 17969 17970 SDValue Cond = DAG.getSetCC(DL, 17971 getSetCCResultType(N0.getValueType()), 17972 N0, N1, CC); 17973 AddToWorklist(Cond.getNode()); 17974 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 17975 Cond, One, Zero); 17976 AddToWorklist(CstOffset.getNode()); 17977 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 17978 CstOffset); 17979 AddToWorklist(CPIdx.getNode()); 17980 return DAG.getLoad( 17981 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 17982 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 17983 Alignment); 17984 } 17985 } 17986 17987 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 17988 return V; 17989 17990 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 17991 // where y is has a single bit set. 17992 // A plaintext description would be, we can turn the SELECT_CC into an AND 17993 // when the condition can be materialized as an all-ones register. Any 17994 // single bit-test can be materialized as an all-ones register with 17995 // shift-left and shift-right-arith. 17996 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 17997 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 17998 SDValue AndLHS = N0->getOperand(0); 17999 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 18000 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 18001 // Shift the tested bit over the sign bit. 18002 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 18003 SDValue ShlAmt = 18004 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 18005 getShiftAmountTy(AndLHS.getValueType())); 18006 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 18007 18008 // Now arithmetic right shift it all the way over, so the result is either 18009 // all-ones, or zero. 18010 SDValue ShrAmt = 18011 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 18012 getShiftAmountTy(Shl.getValueType())); 18013 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 18014 18015 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 18016 } 18017 } 18018 18019 // fold select C, 16, 0 -> shl C, 4 18020 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 18021 TLI.getBooleanContents(N0.getValueType()) == 18022 TargetLowering::ZeroOrOneBooleanContent) { 18023 18024 // If the caller doesn't want us to simplify this into a zext of a compare, 18025 // don't do it. 18026 if (NotExtCompare && N2C->isOne()) 18027 return SDValue(); 18028 18029 // Get a SetCC of the condition 18030 // NOTE: Don't create a SETCC if it's not legal on this target. 18031 if (!LegalOperations || 18032 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 18033 SDValue Temp, SCC; 18034 // cast from setcc result type to select result type 18035 if (LegalTypes) { 18036 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 18037 N0, N1, CC); 18038 if (N2.getValueType().bitsLT(SCC.getValueType())) 18039 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 18040 N2.getValueType()); 18041 else 18042 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 18043 N2.getValueType(), SCC); 18044 } else { 18045 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 18046 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 18047 N2.getValueType(), SCC); 18048 } 18049 18050 AddToWorklist(SCC.getNode()); 18051 AddToWorklist(Temp.getNode()); 18052 18053 if (N2C->isOne()) 18054 return Temp; 18055 18056 // shl setcc result by log2 n2c 18057 return DAG.getNode( 18058 ISD::SHL, DL, N2.getValueType(), Temp, 18059 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 18060 getShiftAmountTy(Temp.getValueType()))); 18061 } 18062 } 18063 18064 // Check to see if this is an integer abs. 18065 // select_cc setg[te] X, 0, X, -X -> 18066 // select_cc setgt X, -1, X, -X -> 18067 // select_cc setl[te] X, 0, -X, X -> 18068 // select_cc setlt X, 1, -X, X -> 18069 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 18070 if (N1C) { 18071 ConstantSDNode *SubC = nullptr; 18072 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 18073 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 18074 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 18075 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 18076 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 18077 (N1C->isOne() && CC == ISD::SETLT)) && 18078 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 18079 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 18080 18081 EVT XType = N0.getValueType(); 18082 if (SubC && SubC->isNullValue() && XType.isInteger()) { 18083 SDLoc DL(N0); 18084 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 18085 N0, 18086 DAG.getConstant(XType.getSizeInBits() - 1, DL, 18087 getShiftAmountTy(N0.getValueType()))); 18088 SDValue Add = DAG.getNode(ISD::ADD, DL, 18089 XType, N0, Shift); 18090 AddToWorklist(Shift.getNode()); 18091 AddToWorklist(Add.getNode()); 18092 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 18093 } 18094 } 18095 18096 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 18097 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 18098 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 18099 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 18100 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 18101 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 18102 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 18103 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 18104 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 18105 SDValue ValueOnZero = N2; 18106 SDValue Count = N3; 18107 // If the condition is NE instead of E, swap the operands. 18108 if (CC == ISD::SETNE) 18109 std::swap(ValueOnZero, Count); 18110 // Check if the value on zero is a constant equal to the bits in the type. 18111 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 18112 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 18113 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 18114 // legal, combine to just cttz. 18115 if ((Count.getOpcode() == ISD::CTTZ || 18116 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 18117 N0 == Count.getOperand(0) && 18118 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 18119 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 18120 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 18121 // legal, combine to just ctlz. 18122 if ((Count.getOpcode() == ISD::CTLZ || 18123 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 18124 N0 == Count.getOperand(0) && 18125 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 18126 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 18127 } 18128 } 18129 } 18130 18131 return SDValue(); 18132 } 18133 18134 /// This is a stub for TargetLowering::SimplifySetCC. 18135 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 18136 ISD::CondCode Cond, const SDLoc &DL, 18137 bool foldBooleans) { 18138 TargetLowering::DAGCombinerInfo 18139 DagCombineInfo(DAG, Level, false, this); 18140 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 18141 } 18142 18143 /// Given an ISD::SDIV node expressing a divide by constant, return 18144 /// a DAG expression to select that will generate the same value by multiplying 18145 /// by a magic number. 18146 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18147 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 18148 // when optimising for minimum size, we don't want to expand a div to a mul 18149 // and a shift. 18150 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18151 return SDValue(); 18152 18153 SmallVector<SDNode *, 8> Built; 18154 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { 18155 for (SDNode *N : Built) 18156 AddToWorklist(N); 18157 return S; 18158 } 18159 18160 return SDValue(); 18161 } 18162 18163 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 18164 /// DAG expression that will generate the same value by right shifting. 18165 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 18166 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 18167 if (!C) 18168 return SDValue(); 18169 18170 // Avoid division by zero. 18171 if (C->isNullValue()) 18172 return SDValue(); 18173 18174 SmallVector<SDNode *, 8> Built; 18175 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { 18176 for (SDNode *N : Built) 18177 AddToWorklist(N); 18178 return S; 18179 } 18180 18181 return SDValue(); 18182 } 18183 18184 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 18185 /// expression that will generate the same value by multiplying by a magic 18186 /// number. 18187 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18188 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 18189 // when optimising for minimum size, we don't want to expand a div to a mul 18190 // and a shift. 18191 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18192 return SDValue(); 18193 18194 SmallVector<SDNode *, 8> Built; 18195 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { 18196 for (SDNode *N : Built) 18197 AddToWorklist(N); 18198 return S; 18199 } 18200 18201 return SDValue(); 18202 } 18203 18204 /// Determines the LogBase2 value for a non-null input value using the 18205 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 18206 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 18207 EVT VT = V.getValueType(); 18208 unsigned EltBits = VT.getScalarSizeInBits(); 18209 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 18210 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 18211 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 18212 return LogBase2; 18213 } 18214 18215 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18216 /// For the reciprocal, we need to find the zero of the function: 18217 /// F(X) = A X - 1 [which has a zero at X = 1/A] 18218 /// => 18219 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 18220 /// does not require additional intermediate precision] 18221 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 18222 if (Level >= AfterLegalizeDAG) 18223 return SDValue(); 18224 18225 // TODO: Handle half and/or extended types? 18226 EVT VT = Op.getValueType(); 18227 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18228 return SDValue(); 18229 18230 // If estimates are explicitly disabled for this function, we're done. 18231 MachineFunction &MF = DAG.getMachineFunction(); 18232 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 18233 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18234 return SDValue(); 18235 18236 // Estimates may be explicitly enabled for this type with a custom number of 18237 // refinement steps. 18238 int Iterations = TLI.getDivRefinementSteps(VT, MF); 18239 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 18240 AddToWorklist(Est.getNode()); 18241 18242 if (Iterations) { 18243 EVT VT = Op.getValueType(); 18244 SDLoc DL(Op); 18245 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 18246 18247 // Newton iterations: Est = Est + Est (1 - Arg * Est) 18248 for (int i = 0; i < Iterations; ++i) { 18249 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 18250 AddToWorklist(NewEst.getNode()); 18251 18252 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 18253 AddToWorklist(NewEst.getNode()); 18254 18255 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18256 AddToWorklist(NewEst.getNode()); 18257 18258 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 18259 AddToWorklist(Est.getNode()); 18260 } 18261 } 18262 return Est; 18263 } 18264 18265 return SDValue(); 18266 } 18267 18268 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18269 /// For the reciprocal sqrt, we need to find the zero of the function: 18270 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18271 /// => 18272 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 18273 /// As a result, we precompute A/2 prior to the iteration loop. 18274 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 18275 unsigned Iterations, 18276 SDNodeFlags Flags, bool Reciprocal) { 18277 EVT VT = Arg.getValueType(); 18278 SDLoc DL(Arg); 18279 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 18280 18281 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 18282 // this entire sequence requires only one FP constant. 18283 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 18284 AddToWorklist(HalfArg.getNode()); 18285 18286 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 18287 AddToWorklist(HalfArg.getNode()); 18288 18289 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 18290 for (unsigned i = 0; i < Iterations; ++i) { 18291 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 18292 AddToWorklist(NewEst.getNode()); 18293 18294 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 18295 AddToWorklist(NewEst.getNode()); 18296 18297 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 18298 AddToWorklist(NewEst.getNode()); 18299 18300 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18301 AddToWorklist(Est.getNode()); 18302 } 18303 18304 // If non-reciprocal square root is requested, multiply the result by Arg. 18305 if (!Reciprocal) { 18306 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 18307 AddToWorklist(Est.getNode()); 18308 } 18309 18310 return Est; 18311 } 18312 18313 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18314 /// For the reciprocal sqrt, we need to find the zero of the function: 18315 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18316 /// => 18317 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 18318 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 18319 unsigned Iterations, 18320 SDNodeFlags Flags, bool Reciprocal) { 18321 EVT VT = Arg.getValueType(); 18322 SDLoc DL(Arg); 18323 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 18324 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 18325 18326 // This routine must enter the loop below to work correctly 18327 // when (Reciprocal == false). 18328 assert(Iterations > 0); 18329 18330 // Newton iterations for reciprocal square root: 18331 // E = (E * -0.5) * ((A * E) * E + -3.0) 18332 for (unsigned i = 0; i < Iterations; ++i) { 18333 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 18334 AddToWorklist(AE.getNode()); 18335 18336 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 18337 AddToWorklist(AEE.getNode()); 18338 18339 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 18340 AddToWorklist(RHS.getNode()); 18341 18342 // When calculating a square root at the last iteration build: 18343 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 18344 // (notice a common subexpression) 18345 SDValue LHS; 18346 if (Reciprocal || (i + 1) < Iterations) { 18347 // RSQRT: LHS = (E * -0.5) 18348 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 18349 } else { 18350 // SQRT: LHS = (A * E) * -0.5 18351 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 18352 } 18353 AddToWorklist(LHS.getNode()); 18354 18355 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 18356 AddToWorklist(Est.getNode()); 18357 } 18358 18359 return Est; 18360 } 18361 18362 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 18363 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 18364 /// Op can be zero. 18365 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 18366 bool Reciprocal) { 18367 if (Level >= AfterLegalizeDAG) 18368 return SDValue(); 18369 18370 // TODO: Handle half and/or extended types? 18371 EVT VT = Op.getValueType(); 18372 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18373 return SDValue(); 18374 18375 // If estimates are explicitly disabled for this function, we're done. 18376 MachineFunction &MF = DAG.getMachineFunction(); 18377 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 18378 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18379 return SDValue(); 18380 18381 // Estimates may be explicitly enabled for this type with a custom number of 18382 // refinement steps. 18383 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 18384 18385 bool UseOneConstNR = false; 18386 if (SDValue Est = 18387 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 18388 Reciprocal)) { 18389 AddToWorklist(Est.getNode()); 18390 18391 if (Iterations) { 18392 Est = UseOneConstNR 18393 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 18394 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 18395 18396 if (!Reciprocal) { 18397 // The estimate is now completely wrong if the input was exactly 0.0 or 18398 // possibly a denormal. Force the answer to 0.0 for those cases. 18399 EVT VT = Op.getValueType(); 18400 SDLoc DL(Op); 18401 EVT CCVT = getSetCCResultType(VT); 18402 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; 18403 const Function &F = DAG.getMachineFunction().getFunction(); 18404 Attribute Denorms = F.getFnAttribute("denormal-fp-math"); 18405 if (Denorms.getValueAsString().equals("ieee")) { 18406 // fabs(X) < SmallestNormal ? 0.0 : Est 18407 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 18408 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 18409 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 18410 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18411 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 18412 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 18413 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est); 18414 AddToWorklist(Fabs.getNode()); 18415 AddToWorklist(IsDenorm.getNode()); 18416 AddToWorklist(Est.getNode()); 18417 } else { 18418 // X == 0.0 ? 0.0 : Est 18419 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18420 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 18421 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est); 18422 AddToWorklist(IsZero.getNode()); 18423 AddToWorklist(Est.getNode()); 18424 } 18425 } 18426 } 18427 return Est; 18428 } 18429 18430 return SDValue(); 18431 } 18432 18433 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18434 return buildSqrtEstimateImpl(Op, Flags, true); 18435 } 18436 18437 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18438 return buildSqrtEstimateImpl(Op, Flags, false); 18439 } 18440 18441 /// Return true if there is any possibility that the two addresses overlap. 18442 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 18443 // If they are the same then they must be aliases. 18444 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 18445 18446 // If they are both volatile then they cannot be reordered. 18447 if (Op0->isVolatile() && Op1->isVolatile()) return true; 18448 18449 // If one operation reads from invariant memory, and the other may store, they 18450 // cannot alias. These should really be checking the equivalent of mayWrite, 18451 // but it only matters for memory nodes other than load /store. 18452 if (Op0->isInvariant() && Op1->writeMem()) 18453 return false; 18454 18455 if (Op1->isInvariant() && Op0->writeMem()) 18456 return false; 18457 18458 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 18459 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 18460 18461 // Check for BaseIndexOffset matching. 18462 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG); 18463 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG); 18464 int64_t PtrDiff; 18465 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) { 18466 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 18467 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 18468 18469 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 18470 // able to calculate their relative offset if at least one arises 18471 // from an alloca. However, these allocas cannot overlap and we 18472 // can infer there is no alias. 18473 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 18474 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 18475 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 18476 // If the base are the same frame index but the we couldn't find a 18477 // constant offset, (indices are different) be conservative. 18478 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 18479 !MFI.isFixedObjectIndex(B->getIndex()))) 18480 return false; 18481 } 18482 18483 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 18484 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 18485 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 18486 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 18487 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 18488 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 18489 18490 // If of mismatched base types or checkable indices we can check 18491 // they do not alias. 18492 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 18493 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 18494 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 18495 return false; 18496 } 18497 18498 // If we know required SrcValue1 and SrcValue2 have relatively large 18499 // alignment compared to the size and offset of the access, we may be able 18500 // to prove they do not alias. This check is conservative for now to catch 18501 // cases created by splitting vector types. 18502 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 18503 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 18504 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 18505 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 18506 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 18507 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 18508 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 18509 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 18510 18511 // There is no overlap between these relatively aligned accesses of 18512 // similar size. Return no alias. 18513 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 18514 (OffAlign1 + NumBytes1) <= OffAlign0) 18515 return false; 18516 } 18517 18518 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 18519 ? CombinerGlobalAA 18520 : DAG.getSubtarget().useAA(); 18521 #ifndef NDEBUG 18522 if (CombinerAAOnlyFunc.getNumOccurrences() && 18523 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 18524 UseAA = false; 18525 #endif 18526 18527 if (UseAA && AA && 18528 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 18529 // Use alias analysis information. 18530 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 18531 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 18532 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 18533 AliasResult AAResult = 18534 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 18535 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 18536 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 18537 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 18538 if (AAResult == NoAlias) 18539 return false; 18540 } 18541 18542 // Otherwise we have to assume they alias. 18543 return true; 18544 } 18545 18546 /// Walk up chain skipping non-aliasing memory nodes, 18547 /// looking for aliasing nodes and adding them to the Aliases vector. 18548 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 18549 SmallVectorImpl<SDValue> &Aliases) { 18550 SmallVector<SDValue, 8> Chains; // List of chains to visit. 18551 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 18552 18553 // Get alias information for node. 18554 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 18555 18556 // Starting off. 18557 Chains.push_back(OriginalChain); 18558 unsigned Depth = 0; 18559 18560 // Look at each chain and determine if it is an alias. If so, add it to the 18561 // aliases list. If not, then continue up the chain looking for the next 18562 // candidate. 18563 while (!Chains.empty()) { 18564 SDValue Chain = Chains.pop_back_val(); 18565 18566 // For TokenFactor nodes, look at each operand and only continue up the 18567 // chain until we reach the depth limit. 18568 // 18569 // FIXME: The depth check could be made to return the last non-aliasing 18570 // chain we found before we hit a tokenfactor rather than the original 18571 // chain. 18572 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 18573 Aliases.clear(); 18574 Aliases.push_back(OriginalChain); 18575 return; 18576 } 18577 18578 // Don't bother if we've been before. 18579 if (!Visited.insert(Chain.getNode()).second) 18580 continue; 18581 18582 switch (Chain.getOpcode()) { 18583 case ISD::EntryToken: 18584 // Entry token is ideal chain operand, but handled in FindBetterChain. 18585 break; 18586 18587 case ISD::LOAD: 18588 case ISD::STORE: { 18589 // Get alias information for Chain. 18590 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 18591 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 18592 18593 // If chain is alias then stop here. 18594 if (!(IsLoad && IsOpLoad) && 18595 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 18596 Aliases.push_back(Chain); 18597 } else { 18598 // Look further up the chain. 18599 Chains.push_back(Chain.getOperand(0)); 18600 ++Depth; 18601 } 18602 break; 18603 } 18604 18605 case ISD::TokenFactor: 18606 // We have to check each of the operands of the token factor for "small" 18607 // token factors, so we queue them up. Adding the operands to the queue 18608 // (stack) in reverse order maintains the original order and increases the 18609 // likelihood that getNode will find a matching token factor (CSE.) 18610 if (Chain.getNumOperands() > 16) { 18611 Aliases.push_back(Chain); 18612 break; 18613 } 18614 for (unsigned n = Chain.getNumOperands(); n;) 18615 Chains.push_back(Chain.getOperand(--n)); 18616 ++Depth; 18617 break; 18618 18619 case ISD::CopyFromReg: 18620 // Forward past CopyFromReg. 18621 Chains.push_back(Chain.getOperand(0)); 18622 ++Depth; 18623 break; 18624 18625 default: 18626 // For all other instructions we will just have to take what we can get. 18627 Aliases.push_back(Chain); 18628 break; 18629 } 18630 } 18631 } 18632 18633 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 18634 /// (aliasing node.) 18635 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 18636 if (OptLevel == CodeGenOpt::None) 18637 return OldChain; 18638 18639 // Ops for replacing token factor. 18640 SmallVector<SDValue, 8> Aliases; 18641 18642 // Accumulate all the aliases to this node. 18643 GatherAllAliases(N, OldChain, Aliases); 18644 18645 // If no operands then chain to entry token. 18646 if (Aliases.size() == 0) 18647 return DAG.getEntryNode(); 18648 18649 // If a single operand then chain to it. We don't need to revisit it. 18650 if (Aliases.size() == 1) 18651 return Aliases[0]; 18652 18653 // Construct a custom tailored token factor. 18654 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 18655 } 18656 18657 // This function tries to collect a bunch of potentially interesting 18658 // nodes to improve the chains of, all at once. This might seem 18659 // redundant, as this function gets called when visiting every store 18660 // node, so why not let the work be done on each store as it's visited? 18661 // 18662 // I believe this is mainly important because MergeConsecutiveStores 18663 // is unable to deal with merging stores of different sizes, so unless 18664 // we improve the chains of all the potential candidates up-front 18665 // before running MergeConsecutiveStores, it might only see some of 18666 // the nodes that will eventually be candidates, and then not be able 18667 // to go from a partially-merged state to the desired final 18668 // fully-merged state. 18669 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 18670 if (OptLevel == CodeGenOpt::None) 18671 return false; 18672 18673 // This holds the base pointer, index, and the offset in bytes from the base 18674 // pointer. 18675 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 18676 18677 // We must have a base and an offset. 18678 if (!BasePtr.getBase().getNode()) 18679 return false; 18680 18681 // Do not handle stores to undef base pointers. 18682 if (BasePtr.getBase().isUndef()) 18683 return false; 18684 18685 SmallVector<StoreSDNode *, 8> ChainedStores; 18686 ChainedStores.push_back(St); 18687 18688 // Walk up the chain and look for nodes with offsets from the same 18689 // base pointer. Stop when reaching an instruction with a different kind 18690 // or instruction which has a different base pointer. 18691 StoreSDNode *Index = St; 18692 while (Index) { 18693 // If the chain has more than one use, then we can't reorder the mem ops. 18694 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 18695 break; 18696 18697 if (Index->isVolatile() || Index->isIndexed()) 18698 break; 18699 18700 // Find the base pointer and offset for this memory node. 18701 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG); 18702 18703 // Check that the base pointer is the same as the original one. 18704 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 18705 break; 18706 18707 // Walk up the chain to find the next store node, ignoring any 18708 // intermediate loads. Any other kind of node will halt the loop. 18709 SDNode *NextInChain = Index->getChain().getNode(); 18710 while (true) { 18711 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 18712 // We found a store node. Use it for the next iteration. 18713 if (STn->isVolatile() || STn->isIndexed()) { 18714 Index = nullptr; 18715 break; 18716 } 18717 ChainedStores.push_back(STn); 18718 Index = STn; 18719 break; 18720 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 18721 NextInChain = Ldn->getChain().getNode(); 18722 continue; 18723 } else { 18724 Index = nullptr; 18725 break; 18726 } 18727 }// end while 18728 } 18729 18730 // At this point, ChainedStores lists all of the Store nodes 18731 // reachable by iterating up through chain nodes matching the above 18732 // conditions. For each such store identified, try to find an 18733 // earlier chain to attach the store to which won't violate the 18734 // required ordering. 18735 bool MadeChangeToSt = false; 18736 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 18737 18738 for (StoreSDNode *ChainedStore : ChainedStores) { 18739 SDValue Chain = ChainedStore->getChain(); 18740 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 18741 18742 if (Chain != BetterChain) { 18743 if (ChainedStore == St) 18744 MadeChangeToSt = true; 18745 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 18746 } 18747 } 18748 18749 // Do all replacements after finding the replacements to make to avoid making 18750 // the chains more complicated by introducing new TokenFactors. 18751 for (auto Replacement : BetterChains) 18752 replaceStoreChain(Replacement.first, Replacement.second); 18753 18754 return MadeChangeToSt; 18755 } 18756 18757 /// This is the entry point for the file. 18758 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 18759 CodeGenOpt::Level OptLevel) { 18760 /// This is the main entry point to this class. 18761 DAGCombiner(*this, AA, OptLevel).Run(Level); 18762 } 18763