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); 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) { 946 EVT VT = N0.getValueType(); 947 if (N0.getOpcode() == Opc) { 948 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 949 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 950 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 951 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 952 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 953 return SDValue(); 954 } 955 if (N0.hasOneUse()) { 956 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 957 // use 958 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 959 if (!OpNode.getNode()) 960 return SDValue(); 961 AddToWorklist(OpNode.getNode()); 962 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 963 } 964 } 965 } 966 967 if (N1.getOpcode() == Opc) { 968 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 969 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 970 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 971 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 972 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 973 return SDValue(); 974 } 975 if (N1.hasOneUse()) { 976 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 977 // use 978 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 979 if (!OpNode.getNode()) 980 return SDValue(); 981 AddToWorklist(OpNode.getNode()); 982 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 983 } 984 } 985 } 986 987 return SDValue(); 988 } 989 990 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 991 bool AddTo) { 992 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 993 ++NodesCombined; 994 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 995 To[0].getNode()->dump(&DAG); 996 dbgs() << " and " << NumTo - 1 << " other values\n"); 997 for (unsigned i = 0, e = NumTo; i != e; ++i) 998 assert((!To[i].getNode() || 999 N->getValueType(i) == To[i].getValueType()) && 1000 "Cannot combine value to value of different type!"); 1001 1002 WorklistRemover DeadNodes(*this); 1003 DAG.ReplaceAllUsesWith(N, To); 1004 if (AddTo) { 1005 // Push the new nodes and any users onto the worklist 1006 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1007 if (To[i].getNode()) { 1008 AddToWorklist(To[i].getNode()); 1009 AddUsersToWorklist(To[i].getNode()); 1010 } 1011 } 1012 } 1013 1014 // Finally, if the node is now dead, remove it from the graph. The node 1015 // may not be dead if the replacement process recursively simplified to 1016 // something else needing this node. 1017 if (N->use_empty()) 1018 deleteAndRecombine(N); 1019 return SDValue(N, 0); 1020 } 1021 1022 void DAGCombiner:: 1023 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1024 // Replace all uses. If any nodes become isomorphic to other nodes and 1025 // are deleted, make sure to remove them from our worklist. 1026 WorklistRemover DeadNodes(*this); 1027 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1028 1029 // Push the new node and any (possibly new) users onto the worklist. 1030 AddToWorklist(TLO.New.getNode()); 1031 AddUsersToWorklist(TLO.New.getNode()); 1032 1033 // Finally, if the node is now dead, remove it from the graph. The node 1034 // may not be dead if the replacement process recursively simplified to 1035 // something else needing this node. 1036 if (TLO.Old.getNode()->use_empty()) 1037 deleteAndRecombine(TLO.Old.getNode()); 1038 } 1039 1040 /// Check the specified integer node value to see if it can be simplified or if 1041 /// things it uses can be simplified by bit propagation. If so, return true. 1042 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1043 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1044 KnownBits Known; 1045 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1046 return false; 1047 1048 // Revisit the node. 1049 AddToWorklist(Op.getNode()); 1050 1051 // Replace the old value with the new one. 1052 ++NodesCombined; 1053 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1054 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1055 dbgs() << '\n'); 1056 1057 CommitTargetLoweringOpt(TLO); 1058 return true; 1059 } 1060 1061 /// Check the specified vector node value to see if it can be simplified or 1062 /// if things it uses can be simplified as it only uses some of the elements. 1063 /// If so, return true. 1064 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded, 1065 bool AssumeSingleUse) { 1066 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1067 APInt KnownUndef, KnownZero; 1068 if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO, 1069 0, AssumeSingleUse)) 1070 return false; 1071 1072 // Revisit the node. 1073 AddToWorklist(Op.getNode()); 1074 1075 // Replace the old value with the new one. 1076 ++NodesCombined; 1077 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1078 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1079 dbgs() << '\n'); 1080 1081 CommitTargetLoweringOpt(TLO); 1082 return true; 1083 } 1084 1085 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1086 SDLoc DL(Load); 1087 EVT VT = Load->getValueType(0); 1088 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1089 1090 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1091 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1092 WorklistRemover DeadNodes(*this); 1093 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1094 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1095 deleteAndRecombine(Load); 1096 AddToWorklist(Trunc.getNode()); 1097 } 1098 1099 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1100 Replace = false; 1101 SDLoc DL(Op); 1102 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1103 LoadSDNode *LD = cast<LoadSDNode>(Op); 1104 EVT MemVT = LD->getMemoryVT(); 1105 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1106 : LD->getExtensionType(); 1107 Replace = true; 1108 return DAG.getExtLoad(ExtType, DL, PVT, 1109 LD->getChain(), LD->getBasePtr(), 1110 MemVT, LD->getMemOperand()); 1111 } 1112 1113 unsigned Opc = Op.getOpcode(); 1114 switch (Opc) { 1115 default: break; 1116 case ISD::AssertSext: 1117 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1118 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1119 break; 1120 case ISD::AssertZext: 1121 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1122 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1123 break; 1124 case ISD::Constant: { 1125 unsigned ExtOpc = 1126 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1127 return DAG.getNode(ExtOpc, DL, PVT, Op); 1128 } 1129 } 1130 1131 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1132 return SDValue(); 1133 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1134 } 1135 1136 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1137 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1138 return SDValue(); 1139 EVT OldVT = Op.getValueType(); 1140 SDLoc DL(Op); 1141 bool Replace = false; 1142 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1143 if (!NewOp.getNode()) 1144 return SDValue(); 1145 AddToWorklist(NewOp.getNode()); 1146 1147 if (Replace) 1148 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1149 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1150 DAG.getValueType(OldVT)); 1151 } 1152 1153 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1154 EVT OldVT = Op.getValueType(); 1155 SDLoc DL(Op); 1156 bool Replace = false; 1157 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1158 if (!NewOp.getNode()) 1159 return SDValue(); 1160 AddToWorklist(NewOp.getNode()); 1161 1162 if (Replace) 1163 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1164 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1165 } 1166 1167 /// Promote the specified integer binary operation if the target indicates it is 1168 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1169 /// i32 since i16 instructions are longer. 1170 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1171 if (!LegalOperations) 1172 return SDValue(); 1173 1174 EVT VT = Op.getValueType(); 1175 if (VT.isVector() || !VT.isInteger()) 1176 return SDValue(); 1177 1178 // If operation type is 'undesirable', e.g. i16 on x86, consider 1179 // promoting it. 1180 unsigned Opc = Op.getOpcode(); 1181 if (TLI.isTypeDesirableForOp(Opc, VT)) 1182 return SDValue(); 1183 1184 EVT PVT = VT; 1185 // Consult target whether it is a good idea to promote this operation and 1186 // what's the right type to promote it to. 1187 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1188 assert(PVT != VT && "Don't know what type to promote to!"); 1189 1190 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1191 1192 bool Replace0 = false; 1193 SDValue N0 = Op.getOperand(0); 1194 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1195 1196 bool Replace1 = false; 1197 SDValue N1 = Op.getOperand(1); 1198 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1199 SDLoc DL(Op); 1200 1201 SDValue RV = 1202 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1203 1204 // We are always replacing N0/N1's use in N and only need 1205 // additional replacements if there are additional uses. 1206 Replace0 &= !N0->hasOneUse(); 1207 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1208 1209 // Combine Op here so it is preserved past replacements. 1210 CombineTo(Op.getNode(), RV); 1211 1212 // If operands have a use ordering, make sure we deal with 1213 // predecessor first. 1214 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1215 std::swap(N0, N1); 1216 std::swap(NN0, NN1); 1217 } 1218 1219 if (Replace0) { 1220 AddToWorklist(NN0.getNode()); 1221 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1222 } 1223 if (Replace1) { 1224 AddToWorklist(NN1.getNode()); 1225 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1226 } 1227 return Op; 1228 } 1229 return SDValue(); 1230 } 1231 1232 /// Promote the specified integer shift operation if the target indicates it is 1233 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1234 /// i32 since i16 instructions are longer. 1235 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1236 if (!LegalOperations) 1237 return SDValue(); 1238 1239 EVT VT = Op.getValueType(); 1240 if (VT.isVector() || !VT.isInteger()) 1241 return SDValue(); 1242 1243 // If operation type is 'undesirable', e.g. i16 on x86, consider 1244 // promoting it. 1245 unsigned Opc = Op.getOpcode(); 1246 if (TLI.isTypeDesirableForOp(Opc, VT)) 1247 return SDValue(); 1248 1249 EVT PVT = VT; 1250 // Consult target whether it is a good idea to promote this operation and 1251 // what's the right type to promote it to. 1252 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1253 assert(PVT != VT && "Don't know what type to promote to!"); 1254 1255 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1256 1257 bool Replace = false; 1258 SDValue N0 = Op.getOperand(0); 1259 SDValue N1 = Op.getOperand(1); 1260 if (Opc == ISD::SRA) 1261 N0 = SExtPromoteOperand(N0, PVT); 1262 else if (Opc == ISD::SRL) 1263 N0 = ZExtPromoteOperand(N0, PVT); 1264 else 1265 N0 = PromoteOperand(N0, PVT, Replace); 1266 1267 if (!N0.getNode()) 1268 return SDValue(); 1269 1270 SDLoc DL(Op); 1271 SDValue RV = 1272 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1273 1274 AddToWorklist(N0.getNode()); 1275 if (Replace) 1276 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1277 1278 // Deal with Op being deleted. 1279 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1280 return RV; 1281 } 1282 return SDValue(); 1283 } 1284 1285 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1286 if (!LegalOperations) 1287 return SDValue(); 1288 1289 EVT VT = Op.getValueType(); 1290 if (VT.isVector() || !VT.isInteger()) 1291 return SDValue(); 1292 1293 // If operation type is 'undesirable', e.g. i16 on x86, consider 1294 // promoting it. 1295 unsigned Opc = Op.getOpcode(); 1296 if (TLI.isTypeDesirableForOp(Opc, VT)) 1297 return SDValue(); 1298 1299 EVT PVT = VT; 1300 // Consult target whether it is a good idea to promote this operation and 1301 // what's the right type to promote it to. 1302 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1303 assert(PVT != VT && "Don't know what type to promote to!"); 1304 // fold (aext (aext x)) -> (aext x) 1305 // fold (aext (zext x)) -> (zext x) 1306 // fold (aext (sext x)) -> (sext x) 1307 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1308 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1309 } 1310 return SDValue(); 1311 } 1312 1313 bool DAGCombiner::PromoteLoad(SDValue Op) { 1314 if (!LegalOperations) 1315 return false; 1316 1317 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1318 return false; 1319 1320 EVT VT = Op.getValueType(); 1321 if (VT.isVector() || !VT.isInteger()) 1322 return false; 1323 1324 // If operation type is 'undesirable', e.g. i16 on x86, consider 1325 // promoting it. 1326 unsigned Opc = Op.getOpcode(); 1327 if (TLI.isTypeDesirableForOp(Opc, VT)) 1328 return false; 1329 1330 EVT PVT = VT; 1331 // Consult target whether it is a good idea to promote this operation and 1332 // what's the right type to promote it to. 1333 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1334 assert(PVT != VT && "Don't know what type to promote to!"); 1335 1336 SDLoc DL(Op); 1337 SDNode *N = Op.getNode(); 1338 LoadSDNode *LD = cast<LoadSDNode>(N); 1339 EVT MemVT = LD->getMemoryVT(); 1340 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1341 : LD->getExtensionType(); 1342 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1343 LD->getChain(), LD->getBasePtr(), 1344 MemVT, LD->getMemOperand()); 1345 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1346 1347 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1348 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1349 WorklistRemover DeadNodes(*this); 1350 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1351 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1352 deleteAndRecombine(N); 1353 AddToWorklist(Result.getNode()); 1354 return true; 1355 } 1356 return false; 1357 } 1358 1359 /// Recursively delete a node which has no uses and any operands for 1360 /// which it is the only use. 1361 /// 1362 /// Note that this both deletes the nodes and removes them from the worklist. 1363 /// It also adds any nodes who have had a user deleted to the worklist as they 1364 /// may now have only one use and subject to other combines. 1365 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1366 if (!N->use_empty()) 1367 return false; 1368 1369 SmallSetVector<SDNode *, 16> Nodes; 1370 Nodes.insert(N); 1371 do { 1372 N = Nodes.pop_back_val(); 1373 if (!N) 1374 continue; 1375 1376 if (N->use_empty()) { 1377 for (const SDValue &ChildN : N->op_values()) 1378 Nodes.insert(ChildN.getNode()); 1379 1380 removeFromWorklist(N); 1381 DAG.DeleteNode(N); 1382 } else { 1383 AddToWorklist(N); 1384 } 1385 } while (!Nodes.empty()); 1386 return true; 1387 } 1388 1389 //===----------------------------------------------------------------------===// 1390 // Main DAG Combiner implementation 1391 //===----------------------------------------------------------------------===// 1392 1393 void DAGCombiner::Run(CombineLevel AtLevel) { 1394 // set the instance variables, so that the various visit routines may use it. 1395 Level = AtLevel; 1396 LegalOperations = Level >= AfterLegalizeVectorOps; 1397 LegalTypes = Level >= AfterLegalizeTypes; 1398 1399 // Add all the dag nodes to the worklist. 1400 for (SDNode &Node : DAG.allnodes()) 1401 AddToWorklist(&Node); 1402 1403 // Create a dummy node (which is not added to allnodes), that adds a reference 1404 // to the root node, preventing it from being deleted, and tracking any 1405 // changes of the root. 1406 HandleSDNode Dummy(DAG.getRoot()); 1407 1408 // While the worklist isn't empty, find a node and try to combine it. 1409 while (!WorklistMap.empty()) { 1410 SDNode *N; 1411 // The Worklist holds the SDNodes in order, but it may contain null entries. 1412 do { 1413 N = Worklist.pop_back_val(); 1414 } while (!N); 1415 1416 bool GoodWorklistEntry = WorklistMap.erase(N); 1417 (void)GoodWorklistEntry; 1418 assert(GoodWorklistEntry && 1419 "Found a worklist entry without a corresponding map entry!"); 1420 1421 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1422 // N is deleted from the DAG, since they too may now be dead or may have a 1423 // reduced number of uses, allowing other xforms. 1424 if (recursivelyDeleteUnusedNodes(N)) 1425 continue; 1426 1427 WorklistRemover DeadNodes(*this); 1428 1429 // If this combine is running after legalizing the DAG, re-legalize any 1430 // nodes pulled off the worklist. 1431 if (Level == AfterLegalizeDAG) { 1432 SmallSetVector<SDNode *, 16> UpdatedNodes; 1433 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1434 1435 for (SDNode *LN : UpdatedNodes) { 1436 AddToWorklist(LN); 1437 AddUsersToWorklist(LN); 1438 } 1439 if (!NIsValid) 1440 continue; 1441 } 1442 1443 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1444 1445 // Add any operands of the new node which have not yet been combined to the 1446 // worklist as well. Because the worklist uniques things already, this 1447 // won't repeatedly process the same operand. 1448 CombinedNodes.insert(N); 1449 for (const SDValue &ChildN : N->op_values()) 1450 if (!CombinedNodes.count(ChildN.getNode())) 1451 AddToWorklist(ChildN.getNode()); 1452 1453 SDValue RV = combine(N); 1454 1455 if (!RV.getNode()) 1456 continue; 1457 1458 ++NodesCombined; 1459 1460 // If we get back the same node we passed in, rather than a new node or 1461 // zero, we know that the node must have defined multiple values and 1462 // CombineTo was used. Since CombineTo takes care of the worklist 1463 // mechanics for us, we have no work to do in this case. 1464 if (RV.getNode() == N) 1465 continue; 1466 1467 assert(N->getOpcode() != ISD::DELETED_NODE && 1468 RV.getOpcode() != ISD::DELETED_NODE && 1469 "Node was deleted but visit returned new node!"); 1470 1471 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1472 1473 if (N->getNumValues() == RV.getNode()->getNumValues()) 1474 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1475 else { 1476 assert(N->getValueType(0) == RV.getValueType() && 1477 N->getNumValues() == 1 && "Type mismatch"); 1478 DAG.ReplaceAllUsesWith(N, &RV); 1479 } 1480 1481 // Push the new node and any users onto the worklist 1482 AddToWorklist(RV.getNode()); 1483 AddUsersToWorklist(RV.getNode()); 1484 1485 // Finally, if the node is now dead, remove it from the graph. The node 1486 // may not be dead if the replacement process recursively simplified to 1487 // something else needing this node. This will also take care of adding any 1488 // operands which have lost a user to the worklist. 1489 recursivelyDeleteUnusedNodes(N); 1490 } 1491 1492 // If the root changed (e.g. it was a dead load, update the root). 1493 DAG.setRoot(Dummy.getValue()); 1494 DAG.RemoveDeadNodes(); 1495 } 1496 1497 SDValue DAGCombiner::visit(SDNode *N) { 1498 switch (N->getOpcode()) { 1499 default: break; 1500 case ISD::TokenFactor: return visitTokenFactor(N); 1501 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1502 case ISD::ADD: return visitADD(N); 1503 case ISD::SUB: return visitSUB(N); 1504 case ISD::ADDC: return visitADDC(N); 1505 case ISD::UADDO: return visitUADDO(N); 1506 case ISD::SUBC: return visitSUBC(N); 1507 case ISD::USUBO: return visitUSUBO(N); 1508 case ISD::ADDE: return visitADDE(N); 1509 case ISD::ADDCARRY: return visitADDCARRY(N); 1510 case ISD::SUBE: return visitSUBE(N); 1511 case ISD::SUBCARRY: return visitSUBCARRY(N); 1512 case ISD::MUL: return visitMUL(N); 1513 case ISD::SDIV: return visitSDIV(N); 1514 case ISD::UDIV: return visitUDIV(N); 1515 case ISD::SREM: 1516 case ISD::UREM: return visitREM(N); 1517 case ISD::MULHU: return visitMULHU(N); 1518 case ISD::MULHS: return visitMULHS(N); 1519 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1520 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1521 case ISD::SMULO: return visitSMULO(N); 1522 case ISD::UMULO: return visitUMULO(N); 1523 case ISD::SMIN: 1524 case ISD::SMAX: 1525 case ISD::UMIN: 1526 case ISD::UMAX: return visitIMINMAX(N); 1527 case ISD::AND: return visitAND(N); 1528 case ISD::OR: return visitOR(N); 1529 case ISD::XOR: return visitXOR(N); 1530 case ISD::SHL: return visitSHL(N); 1531 case ISD::SRA: return visitSRA(N); 1532 case ISD::SRL: return visitSRL(N); 1533 case ISD::ROTR: 1534 case ISD::ROTL: return visitRotate(N); 1535 case ISD::ABS: return visitABS(N); 1536 case ISD::BSWAP: return visitBSWAP(N); 1537 case ISD::BITREVERSE: return visitBITREVERSE(N); 1538 case ISD::CTLZ: return visitCTLZ(N); 1539 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1540 case ISD::CTTZ: return visitCTTZ(N); 1541 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1542 case ISD::CTPOP: return visitCTPOP(N); 1543 case ISD::SELECT: return visitSELECT(N); 1544 case ISD::VSELECT: return visitVSELECT(N); 1545 case ISD::SELECT_CC: return visitSELECT_CC(N); 1546 case ISD::SETCC: return visitSETCC(N); 1547 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1548 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1549 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1550 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1551 case ISD::AssertSext: 1552 case ISD::AssertZext: return visitAssertExt(N); 1553 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1554 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1555 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1556 case ISD::TRUNCATE: return visitTRUNCATE(N); 1557 case ISD::BITCAST: return visitBITCAST(N); 1558 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1559 case ISD::FADD: return visitFADD(N); 1560 case ISD::FSUB: return visitFSUB(N); 1561 case ISD::FMUL: return visitFMUL(N); 1562 case ISD::FMA: return visitFMA(N); 1563 case ISD::FDIV: return visitFDIV(N); 1564 case ISD::FREM: return visitFREM(N); 1565 case ISD::FSQRT: return visitFSQRT(N); 1566 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1567 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1568 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1569 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1570 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1571 case ISD::FP_ROUND: return visitFP_ROUND(N); 1572 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1573 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1574 case ISD::FNEG: return visitFNEG(N); 1575 case ISD::FABS: return visitFABS(N); 1576 case ISD::FFLOOR: return visitFFLOOR(N); 1577 case ISD::FMINNUM: return visitFMINNUM(N); 1578 case ISD::FMAXNUM: return visitFMAXNUM(N); 1579 case ISD::FCEIL: return visitFCEIL(N); 1580 case ISD::FTRUNC: return visitFTRUNC(N); 1581 case ISD::BRCOND: return visitBRCOND(N); 1582 case ISD::BR_CC: return visitBR_CC(N); 1583 case ISD::LOAD: return visitLOAD(N); 1584 case ISD::STORE: return visitSTORE(N); 1585 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1586 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1587 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1588 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1589 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1590 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1591 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1592 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1593 case ISD::MGATHER: return visitMGATHER(N); 1594 case ISD::MLOAD: return visitMLOAD(N); 1595 case ISD::MSCATTER: return visitMSCATTER(N); 1596 case ISD::MSTORE: return visitMSTORE(N); 1597 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1598 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1599 } 1600 return SDValue(); 1601 } 1602 1603 SDValue DAGCombiner::combine(SDNode *N) { 1604 SDValue RV = visit(N); 1605 1606 // If nothing happened, try a target-specific DAG combine. 1607 if (!RV.getNode()) { 1608 assert(N->getOpcode() != ISD::DELETED_NODE && 1609 "Node was deleted but visit returned NULL!"); 1610 1611 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1612 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1613 1614 // Expose the DAG combiner to the target combiner impls. 1615 TargetLowering::DAGCombinerInfo 1616 DagCombineInfo(DAG, Level, false, this); 1617 1618 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1619 } 1620 } 1621 1622 // If nothing happened still, try promoting the operation. 1623 if (!RV.getNode()) { 1624 switch (N->getOpcode()) { 1625 default: break; 1626 case ISD::ADD: 1627 case ISD::SUB: 1628 case ISD::MUL: 1629 case ISD::AND: 1630 case ISD::OR: 1631 case ISD::XOR: 1632 RV = PromoteIntBinOp(SDValue(N, 0)); 1633 break; 1634 case ISD::SHL: 1635 case ISD::SRA: 1636 case ISD::SRL: 1637 RV = PromoteIntShiftOp(SDValue(N, 0)); 1638 break; 1639 case ISD::SIGN_EXTEND: 1640 case ISD::ZERO_EXTEND: 1641 case ISD::ANY_EXTEND: 1642 RV = PromoteExtend(SDValue(N, 0)); 1643 break; 1644 case ISD::LOAD: 1645 if (PromoteLoad(SDValue(N, 0))) 1646 RV = SDValue(N, 0); 1647 break; 1648 } 1649 } 1650 1651 // If N is a commutative binary node, try eliminate it if the commuted 1652 // version is already present in the DAG. 1653 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1654 N->getNumValues() == 1) { 1655 SDValue N0 = N->getOperand(0); 1656 SDValue N1 = N->getOperand(1); 1657 1658 // Constant operands are canonicalized to RHS. 1659 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1660 SDValue Ops[] = {N1, N0}; 1661 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1662 N->getFlags()); 1663 if (CSENode) 1664 return SDValue(CSENode, 0); 1665 } 1666 } 1667 1668 return RV; 1669 } 1670 1671 /// Given a node, return its input chain if it has one, otherwise return a null 1672 /// sd operand. 1673 static SDValue getInputChainForNode(SDNode *N) { 1674 if (unsigned NumOps = N->getNumOperands()) { 1675 if (N->getOperand(0).getValueType() == MVT::Other) 1676 return N->getOperand(0); 1677 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1678 return N->getOperand(NumOps-1); 1679 for (unsigned i = 1; i < NumOps-1; ++i) 1680 if (N->getOperand(i).getValueType() == MVT::Other) 1681 return N->getOperand(i); 1682 } 1683 return SDValue(); 1684 } 1685 1686 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1687 // If N has two operands, where one has an input chain equal to the other, 1688 // the 'other' chain is redundant. 1689 if (N->getNumOperands() == 2) { 1690 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1691 return N->getOperand(0); 1692 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1693 return N->getOperand(1); 1694 } 1695 1696 // Don't simplify token factors if optnone. 1697 if (OptLevel == CodeGenOpt::None) 1698 return SDValue(); 1699 1700 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1701 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1702 SmallPtrSet<SDNode*, 16> SeenOps; 1703 bool Changed = false; // If we should replace this token factor. 1704 1705 // Start out with this token factor. 1706 TFs.push_back(N); 1707 1708 // Iterate through token factors. The TFs grows when new token factors are 1709 // encountered. 1710 for (unsigned i = 0; i < TFs.size(); ++i) { 1711 SDNode *TF = TFs[i]; 1712 1713 // Check each of the operands. 1714 for (const SDValue &Op : TF->op_values()) { 1715 switch (Op.getOpcode()) { 1716 case ISD::EntryToken: 1717 // Entry tokens don't need to be added to the list. They are 1718 // redundant. 1719 Changed = true; 1720 break; 1721 1722 case ISD::TokenFactor: 1723 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1724 // Queue up for processing. 1725 TFs.push_back(Op.getNode()); 1726 // Clean up in case the token factor is removed. 1727 AddToWorklist(Op.getNode()); 1728 Changed = true; 1729 break; 1730 } 1731 LLVM_FALLTHROUGH; 1732 1733 default: 1734 // Only add if it isn't already in the list. 1735 if (SeenOps.insert(Op.getNode()).second) 1736 Ops.push_back(Op); 1737 else 1738 Changed = true; 1739 break; 1740 } 1741 } 1742 } 1743 1744 // Remove Nodes that are chained to another node in the list. Do so 1745 // by walking up chains breath-first stopping when we've seen 1746 // another operand. In general we must climb to the EntryNode, but we can exit 1747 // early if we find all remaining work is associated with just one operand as 1748 // no further pruning is possible. 1749 1750 // List of nodes to search through and original Ops from which they originate. 1751 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1752 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1753 SmallPtrSet<SDNode *, 16> SeenChains; 1754 bool DidPruneOps = false; 1755 1756 unsigned NumLeftToConsider = 0; 1757 for (const SDValue &Op : Ops) { 1758 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1759 OpWorkCount.push_back(1); 1760 } 1761 1762 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1763 // If this is an Op, we can remove the op from the list. Remark any 1764 // search associated with it as from the current OpNumber. 1765 if (SeenOps.count(Op) != 0) { 1766 Changed = true; 1767 DidPruneOps = true; 1768 unsigned OrigOpNumber = 0; 1769 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1770 OrigOpNumber++; 1771 assert((OrigOpNumber != Ops.size()) && 1772 "expected to find TokenFactor Operand"); 1773 // Re-mark worklist from OrigOpNumber to OpNumber 1774 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1775 if (Worklist[i].second == OrigOpNumber) { 1776 Worklist[i].second = OpNumber; 1777 } 1778 } 1779 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1780 OpWorkCount[OrigOpNumber] = 0; 1781 NumLeftToConsider--; 1782 } 1783 // Add if it's a new chain 1784 if (SeenChains.insert(Op).second) { 1785 OpWorkCount[OpNumber]++; 1786 Worklist.push_back(std::make_pair(Op, OpNumber)); 1787 } 1788 }; 1789 1790 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1791 // We need at least be consider at least 2 Ops to prune. 1792 if (NumLeftToConsider <= 1) 1793 break; 1794 auto CurNode = Worklist[i].first; 1795 auto CurOpNumber = Worklist[i].second; 1796 assert((OpWorkCount[CurOpNumber] > 0) && 1797 "Node should not appear in worklist"); 1798 switch (CurNode->getOpcode()) { 1799 case ISD::EntryToken: 1800 // Hitting EntryToken is the only way for the search to terminate without 1801 // hitting 1802 // another operand's search. Prevent us from marking this operand 1803 // considered. 1804 NumLeftToConsider++; 1805 break; 1806 case ISD::TokenFactor: 1807 for (const SDValue &Op : CurNode->op_values()) 1808 AddToWorklist(i, Op.getNode(), CurOpNumber); 1809 break; 1810 case ISD::CopyFromReg: 1811 case ISD::CopyToReg: 1812 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1813 break; 1814 default: 1815 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1816 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1817 break; 1818 } 1819 OpWorkCount[CurOpNumber]--; 1820 if (OpWorkCount[CurOpNumber] == 0) 1821 NumLeftToConsider--; 1822 } 1823 1824 // If we've changed things around then replace token factor. 1825 if (Changed) { 1826 SDValue Result; 1827 if (Ops.empty()) { 1828 // The entry token is the only possible outcome. 1829 Result = DAG.getEntryNode(); 1830 } else { 1831 if (DidPruneOps) { 1832 SmallVector<SDValue, 8> PrunedOps; 1833 // 1834 for (const SDValue &Op : Ops) { 1835 if (SeenChains.count(Op.getNode()) == 0) 1836 PrunedOps.push_back(Op); 1837 } 1838 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1839 } else { 1840 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1841 } 1842 } 1843 return Result; 1844 } 1845 return SDValue(); 1846 } 1847 1848 /// MERGE_VALUES can always be eliminated. 1849 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1850 WorklistRemover DeadNodes(*this); 1851 // Replacing results may cause a different MERGE_VALUES to suddenly 1852 // be CSE'd with N, and carry its uses with it. Iterate until no 1853 // uses remain, to ensure that the node can be safely deleted. 1854 // First add the users of this node to the work list so that they 1855 // can be tried again once they have new operands. 1856 AddUsersToWorklist(N); 1857 do { 1858 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1859 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1860 } while (!N->use_empty()); 1861 deleteAndRecombine(N); 1862 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1863 } 1864 1865 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1866 /// ConstantSDNode pointer else nullptr. 1867 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1868 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1869 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1870 } 1871 1872 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1873 auto BinOpcode = BO->getOpcode(); 1874 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1875 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1876 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1877 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1878 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1879 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1880 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1881 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1882 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1883 "Unexpected binary operator"); 1884 1885 // Don't do this unless the old select is going away. We want to eliminate the 1886 // binary operator, not replace a binop with a select. 1887 // TODO: Handle ISD::SELECT_CC. 1888 unsigned SelOpNo = 0; 1889 SDValue Sel = BO->getOperand(0); 1890 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 1891 SelOpNo = 1; 1892 Sel = BO->getOperand(1); 1893 } 1894 1895 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1896 return SDValue(); 1897 1898 SDValue CT = Sel.getOperand(1); 1899 if (!isConstantOrConstantVector(CT, true) && 1900 !isConstantFPBuildVectorOrConstantFP(CT)) 1901 return SDValue(); 1902 1903 SDValue CF = Sel.getOperand(2); 1904 if (!isConstantOrConstantVector(CF, true) && 1905 !isConstantFPBuildVectorOrConstantFP(CF)) 1906 return SDValue(); 1907 1908 // Bail out if any constants are opaque because we can't constant fold those. 1909 // The exception is "and" and "or" with either 0 or -1 in which case we can 1910 // propagate non constant operands into select. I.e.: 1911 // and (select Cond, 0, -1), X --> select Cond, 0, X 1912 // or X, (select Cond, -1, 0) --> select Cond, -1, X 1913 bool CanFoldNonConst = (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 1914 (isNullConstantOrNullSplatConstant(CT) || 1915 isAllOnesConstantOrAllOnesSplatConstant(CT)) && 1916 (isNullConstantOrNullSplatConstant(CF) || 1917 isAllOnesConstantOrAllOnesSplatConstant(CF)); 1918 1919 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 1920 if (!CanFoldNonConst && 1921 !isConstantOrConstantVector(CBO, true) && 1922 !isConstantFPBuildVectorOrConstantFP(CBO)) 1923 return SDValue(); 1924 1925 EVT VT = Sel.getValueType(); 1926 1927 // In case of shift value and shift amount may have different VT. For instance 1928 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have 1929 // swapped operands and value types do not match. NB: x86 is fine if operands 1930 // are not swapped with shift amount VT being not bigger than shifted value. 1931 // TODO: that is possible to check for a shift operation, correct VTs and 1932 // still perform optimization on x86 if needed. 1933 if (SelOpNo && VT != CBO.getValueType()) 1934 return SDValue(); 1935 1936 // We have a select-of-constants followed by a binary operator with a 1937 // constant. Eliminate the binop by pulling the constant math into the select. 1938 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 1939 SDLoc DL(Sel); 1940 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 1941 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 1942 if (!CanFoldNonConst && !NewCT.isUndef() && 1943 !isConstantOrConstantVector(NewCT, true) && 1944 !isConstantFPBuildVectorOrConstantFP(NewCT)) 1945 return SDValue(); 1946 1947 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 1948 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 1949 if (!CanFoldNonConst && !NewCF.isUndef() && 1950 !isConstantOrConstantVector(NewCF, true) && 1951 !isConstantFPBuildVectorOrConstantFP(NewCF)) 1952 return SDValue(); 1953 1954 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1955 } 1956 1957 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 1958 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 1959 "Expecting add or sub"); 1960 1961 // Match a constant operand and a zext operand for the math instruction: 1962 // add Z, C 1963 // sub C, Z 1964 bool IsAdd = N->getOpcode() == ISD::ADD; 1965 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 1966 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 1967 auto *CN = dyn_cast<ConstantSDNode>(C); 1968 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 1969 return SDValue(); 1970 1971 // Match the zext operand as a setcc of a boolean. 1972 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 1973 Z.getOperand(0).getValueType() != MVT::i1) 1974 return SDValue(); 1975 1976 // Match the compare as: setcc (X & 1), 0, eq. 1977 SDValue SetCC = Z.getOperand(0); 1978 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 1979 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 1980 SetCC.getOperand(0).getOpcode() != ISD::AND || 1981 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 1982 return SDValue(); 1983 1984 // We are adding/subtracting a constant and an inverted low bit. Turn that 1985 // into a subtract/add of the low bit with incremented/decremented constant: 1986 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 1987 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 1988 EVT VT = C.getValueType(); 1989 SDLoc DL(N); 1990 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 1991 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 1992 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 1993 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 1994 } 1995 1996 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 1997 /// a shift and add with a different constant. 1998 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 1999 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2000 "Expecting add or sub"); 2001 2002 // We need a constant operand for the add/sub, and the other operand is a 2003 // logical shift right: add (srl), C or sub C, (srl). 2004 bool IsAdd = N->getOpcode() == ISD::ADD; 2005 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2006 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2007 ConstantSDNode *C = isConstOrConstSplat(ConstantOp); 2008 if (!C || ShiftOp.getOpcode() != ISD::SRL) 2009 return SDValue(); 2010 2011 // The shift must be of a 'not' value. 2012 // TODO: Use isBitwiseNot() if it works with vectors. 2013 SDValue Not = ShiftOp.getOperand(0); 2014 if (!Not.hasOneUse() || Not.getOpcode() != ISD::XOR || 2015 !isAllOnesConstantOrAllOnesSplatConstant(Not.getOperand(1))) 2016 return SDValue(); 2017 2018 // The shift must be moving the sign bit to the least-significant-bit. 2019 EVT VT = ShiftOp.getValueType(); 2020 SDValue ShAmt = ShiftOp.getOperand(1); 2021 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2022 if (!ShAmtC || ShAmtC->getZExtValue() != VT.getScalarSizeInBits() - 1) 2023 return SDValue(); 2024 2025 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2026 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2027 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2028 SDLoc DL(N); 2029 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2030 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2031 APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1; 2032 return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT)); 2033 } 2034 2035 SDValue DAGCombiner::visitADD(SDNode *N) { 2036 SDValue N0 = N->getOperand(0); 2037 SDValue N1 = N->getOperand(1); 2038 EVT VT = N0.getValueType(); 2039 SDLoc DL(N); 2040 2041 // fold vector ops 2042 if (VT.isVector()) { 2043 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2044 return FoldedVOp; 2045 2046 // fold (add x, 0) -> x, vector edition 2047 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2048 return N0; 2049 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2050 return N1; 2051 } 2052 2053 // fold (add x, undef) -> undef 2054 if (N0.isUndef()) 2055 return N0; 2056 2057 if (N1.isUndef()) 2058 return N1; 2059 2060 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2061 // canonicalize constant to RHS 2062 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2063 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2064 // fold (add c1, c2) -> c1+c2 2065 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 2066 N1.getNode()); 2067 } 2068 2069 // fold (add x, 0) -> x 2070 if (isNullConstant(N1)) 2071 return N0; 2072 2073 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2074 // fold ((c1-A)+c2) -> (c1+c2)-A 2075 if (N0.getOpcode() == ISD::SUB && 2076 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2077 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 2078 return DAG.getNode(ISD::SUB, DL, VT, 2079 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 2080 N0.getOperand(1)); 2081 } 2082 2083 // add (sext i1 X), 1 -> zext (not i1 X) 2084 // We don't transform this pattern: 2085 // add (zext i1 X), -1 -> sext (not i1 X) 2086 // because most (?) targets generate better code for the zext form. 2087 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2088 isOneConstantOrOneSplatConstant(N1)) { 2089 SDValue X = N0.getOperand(0); 2090 if ((!LegalOperations || 2091 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2092 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2093 X.getScalarValueSizeInBits() == 1) { 2094 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2095 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2096 } 2097 } 2098 2099 // Undo the add -> or combine to merge constant offsets from a frame index. 2100 if (N0.getOpcode() == ISD::OR && 2101 isa<FrameIndexSDNode>(N0.getOperand(0)) && 2102 isa<ConstantSDNode>(N0.getOperand(1)) && 2103 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2104 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 2105 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2106 } 2107 } 2108 2109 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2110 return NewSel; 2111 2112 // reassociate add 2113 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 2114 return RADD; 2115 2116 // fold ((0-A) + B) -> B-A 2117 if (N0.getOpcode() == ISD::SUB && 2118 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2119 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2120 2121 // fold (A + (0-B)) -> A-B 2122 if (N1.getOpcode() == ISD::SUB && 2123 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2124 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2125 2126 // fold (A+(B-A)) -> B 2127 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2128 return N1.getOperand(0); 2129 2130 // fold ((B-A)+A) -> B 2131 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2132 return N0.getOperand(0); 2133 2134 // fold (A+(B-(A+C))) to (B-C) 2135 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2136 N0 == N1.getOperand(1).getOperand(0)) 2137 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2138 N1.getOperand(1).getOperand(1)); 2139 2140 // fold (A+(B-(C+A))) to (B-C) 2141 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2142 N0 == N1.getOperand(1).getOperand(1)) 2143 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2144 N1.getOperand(1).getOperand(0)); 2145 2146 // fold (A+((B-A)+or-C)) to (B+or-C) 2147 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2148 N1.getOperand(0).getOpcode() == ISD::SUB && 2149 N0 == N1.getOperand(0).getOperand(1)) 2150 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2151 N1.getOperand(1)); 2152 2153 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2154 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2155 SDValue N00 = N0.getOperand(0); 2156 SDValue N01 = N0.getOperand(1); 2157 SDValue N10 = N1.getOperand(0); 2158 SDValue N11 = N1.getOperand(1); 2159 2160 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2161 return DAG.getNode(ISD::SUB, DL, VT, 2162 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2163 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2164 } 2165 2166 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2167 return V; 2168 2169 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2170 return V; 2171 2172 if (SimplifyDemandedBits(SDValue(N, 0))) 2173 return SDValue(N, 0); 2174 2175 // fold (a+b) -> (a|b) iff a and b share no bits. 2176 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2177 DAG.haveNoCommonBitsSet(N0, N1)) 2178 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2179 2180 // fold (add (xor a, -1), 1) -> (sub 0, a) 2181 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) 2182 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2183 N0.getOperand(0)); 2184 2185 if (SDValue Combined = visitADDLike(N0, N1, N)) 2186 return Combined; 2187 2188 if (SDValue Combined = visitADDLike(N1, N0, N)) 2189 return Combined; 2190 2191 return SDValue(); 2192 } 2193 2194 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2195 bool Masked = false; 2196 2197 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2198 while (true) { 2199 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2200 V = V.getOperand(0); 2201 continue; 2202 } 2203 2204 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2205 Masked = true; 2206 V = V.getOperand(0); 2207 continue; 2208 } 2209 2210 break; 2211 } 2212 2213 // If this is not a carry, return. 2214 if (V.getResNo() != 1) 2215 return SDValue(); 2216 2217 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2218 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2219 return SDValue(); 2220 2221 // If the result is masked, then no matter what kind of bool it is we can 2222 // return. If it isn't, then we need to make sure the bool type is either 0 or 2223 // 1 and not other values. 2224 if (Masked || 2225 TLI.getBooleanContents(V.getValueType()) == 2226 TargetLoweringBase::ZeroOrOneBooleanContent) 2227 return V; 2228 2229 return SDValue(); 2230 } 2231 2232 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2233 EVT VT = N0.getValueType(); 2234 SDLoc DL(LocReference); 2235 2236 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2237 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2238 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2239 return DAG.getNode(ISD::SUB, DL, VT, N0, 2240 DAG.getNode(ISD::SHL, DL, VT, 2241 N1.getOperand(0).getOperand(1), 2242 N1.getOperand(1))); 2243 2244 if (N1.getOpcode() == ISD::AND) { 2245 SDValue AndOp0 = N1.getOperand(0); 2246 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2247 unsigned DestBits = VT.getScalarSizeInBits(); 2248 2249 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2250 // and similar xforms where the inner op is either ~0 or 0. 2251 if (NumSignBits == DestBits && 2252 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2253 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2254 } 2255 2256 // add (sext i1), X -> sub X, (zext i1) 2257 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2258 N0.getOperand(0).getValueType() == MVT::i1 && 2259 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2260 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2261 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2262 } 2263 2264 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2265 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2266 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2267 if (TN->getVT() == MVT::i1) { 2268 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2269 DAG.getConstant(1, DL, VT)); 2270 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2271 } 2272 } 2273 2274 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2275 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2276 N1.getResNo() == 0) 2277 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2278 N0, N1.getOperand(0), N1.getOperand(2)); 2279 2280 // (add X, Carry) -> (addcarry X, 0, Carry) 2281 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2282 if (SDValue Carry = getAsCarry(TLI, N1)) 2283 return DAG.getNode(ISD::ADDCARRY, DL, 2284 DAG.getVTList(VT, Carry.getValueType()), N0, 2285 DAG.getConstant(0, DL, VT), Carry); 2286 2287 return SDValue(); 2288 } 2289 2290 SDValue DAGCombiner::visitADDC(SDNode *N) { 2291 SDValue N0 = N->getOperand(0); 2292 SDValue N1 = N->getOperand(1); 2293 EVT VT = N0.getValueType(); 2294 SDLoc DL(N); 2295 2296 // If the flag result is dead, turn this into an ADD. 2297 if (!N->hasAnyUseOfValue(1)) 2298 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2299 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2300 2301 // canonicalize constant to RHS. 2302 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2303 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2304 if (N0C && !N1C) 2305 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2306 2307 // fold (addc x, 0) -> x + no carry out 2308 if (isNullConstant(N1)) 2309 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2310 DL, MVT::Glue)); 2311 2312 // If it cannot overflow, transform into an add. 2313 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2314 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2315 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2316 2317 return SDValue(); 2318 } 2319 2320 static SDValue flipBoolean(SDValue V, const SDLoc &DL, EVT VT, 2321 SelectionDAG &DAG, const TargetLowering &TLI) { 2322 SDValue Cst; 2323 switch (TLI.getBooleanContents(VT)) { 2324 case TargetLowering::ZeroOrOneBooleanContent: 2325 case TargetLowering::UndefinedBooleanContent: 2326 Cst = DAG.getConstant(1, DL, VT); 2327 break; 2328 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2329 Cst = DAG.getConstant(-1, DL, VT); 2330 break; 2331 } 2332 2333 return DAG.getNode(ISD::XOR, DL, VT, V, Cst); 2334 } 2335 2336 static bool isBooleanFlip(SDValue V, EVT VT, const TargetLowering &TLI) { 2337 if (V.getOpcode() != ISD::XOR) return false; 2338 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V.getOperand(1)); 2339 if (!Const) return false; 2340 2341 switch(TLI.getBooleanContents(VT)) { 2342 case TargetLowering::ZeroOrOneBooleanContent: 2343 return Const->isOne(); 2344 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2345 return Const->isAllOnesValue(); 2346 case TargetLowering::UndefinedBooleanContent: 2347 return (Const->getAPIntValue() & 0x01) == 1; 2348 } 2349 llvm_unreachable("Unsupported boolean content"); 2350 } 2351 2352 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2353 SDValue N0 = N->getOperand(0); 2354 SDValue N1 = N->getOperand(1); 2355 EVT VT = N0.getValueType(); 2356 if (VT.isVector()) 2357 return SDValue(); 2358 2359 EVT CarryVT = N->getValueType(1); 2360 SDLoc DL(N); 2361 2362 // If the flag result is dead, turn this into an ADD. 2363 if (!N->hasAnyUseOfValue(1)) 2364 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2365 DAG.getUNDEF(CarryVT)); 2366 2367 // canonicalize constant to RHS. 2368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2370 if (N0C && !N1C) 2371 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2372 2373 // fold (uaddo x, 0) -> x + no carry out 2374 if (isNullConstant(N1)) 2375 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2376 2377 // If it cannot overflow, transform into an add. 2378 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2379 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2380 DAG.getConstant(0, DL, CarryVT)); 2381 2382 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2383 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) { 2384 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2385 DAG.getConstant(0, DL, VT), 2386 N0.getOperand(0)); 2387 return CombineTo(N, Sub, 2388 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2389 } 2390 2391 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2392 return Combined; 2393 2394 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2395 return Combined; 2396 2397 return SDValue(); 2398 } 2399 2400 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2401 auto VT = N0.getValueType(); 2402 2403 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2404 // If Y + 1 cannot overflow. 2405 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2406 SDValue Y = N1.getOperand(0); 2407 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2408 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2409 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2410 N1.getOperand(2)); 2411 } 2412 2413 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2414 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2415 if (SDValue Carry = getAsCarry(TLI, N1)) 2416 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2417 DAG.getConstant(0, SDLoc(N), VT), Carry); 2418 2419 return SDValue(); 2420 } 2421 2422 SDValue DAGCombiner::visitADDE(SDNode *N) { 2423 SDValue N0 = N->getOperand(0); 2424 SDValue N1 = N->getOperand(1); 2425 SDValue CarryIn = N->getOperand(2); 2426 2427 // canonicalize constant to RHS 2428 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2429 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2430 if (N0C && !N1C) 2431 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2432 N1, N0, CarryIn); 2433 2434 // fold (adde x, y, false) -> (addc x, y) 2435 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2436 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2437 2438 return SDValue(); 2439 } 2440 2441 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2442 SDValue N0 = N->getOperand(0); 2443 SDValue N1 = N->getOperand(1); 2444 SDValue CarryIn = N->getOperand(2); 2445 SDLoc DL(N); 2446 2447 // canonicalize constant to RHS 2448 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2449 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2450 if (N0C && !N1C) 2451 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2452 2453 // fold (addcarry x, y, false) -> (uaddo x, y) 2454 if (isNullConstant(CarryIn)) { 2455 if (!LegalOperations || 2456 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2457 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2458 } 2459 2460 EVT CarryVT = CarryIn.getValueType(); 2461 2462 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2463 if (isNullConstant(N0) && isNullConstant(N1)) { 2464 EVT VT = N0.getValueType(); 2465 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2466 AddToWorklist(CarryExt.getNode()); 2467 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2468 DAG.getConstant(1, DL, VT)), 2469 DAG.getConstant(0, DL, CarryVT)); 2470 } 2471 2472 // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry. 2473 if (isBitwiseNot(N0) && isNullConstant(N1) && 2474 isBooleanFlip(CarryIn, CarryVT, TLI)) { 2475 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), 2476 DAG.getConstant(0, DL, N0.getValueType()), 2477 N0.getOperand(0), CarryIn.getOperand(0)); 2478 return CombineTo(N, Sub, 2479 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2480 } 2481 2482 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2483 return Combined; 2484 2485 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2486 return Combined; 2487 2488 return SDValue(); 2489 } 2490 2491 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2492 SDNode *N) { 2493 // Iff the flag result is dead: 2494 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2495 if ((N0.getOpcode() == ISD::ADD || 2496 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2497 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2498 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2499 N0.getOperand(0), N0.getOperand(1), CarryIn); 2500 2501 /** 2502 * When one of the addcarry argument is itself a carry, we may be facing 2503 * a diamond carry propagation. In which case we try to transform the DAG 2504 * to ensure linear carry propagation if that is possible. 2505 * 2506 * We are trying to get: 2507 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2508 */ 2509 if (auto Y = getAsCarry(TLI, N1)) { 2510 /** 2511 * (uaddo A, B) 2512 * / \ 2513 * Carry Sum 2514 * | \ 2515 * | (addcarry *, 0, Z) 2516 * | / 2517 * \ Carry 2518 * | / 2519 * (addcarry X, *, *) 2520 */ 2521 if (Y.getOpcode() == ISD::UADDO && 2522 CarryIn.getResNo() == 1 && 2523 CarryIn.getOpcode() == ISD::ADDCARRY && 2524 isNullConstant(CarryIn.getOperand(1)) && 2525 CarryIn.getOperand(0) == Y.getValue(0)) { 2526 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2527 Y.getOperand(0), Y.getOperand(1), 2528 CarryIn.getOperand(2)); 2529 AddToWorklist(NewY.getNode()); 2530 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2531 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2532 NewY.getValue(1)); 2533 } 2534 } 2535 2536 return SDValue(); 2537 } 2538 2539 // Since it may not be valid to emit a fold to zero for vector initializers 2540 // check if we can before folding. 2541 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2542 SelectionDAG &DAG, bool LegalOperations, 2543 bool LegalTypes) { 2544 if (!VT.isVector()) 2545 return DAG.getConstant(0, DL, VT); 2546 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2547 return DAG.getConstant(0, DL, VT); 2548 return SDValue(); 2549 } 2550 2551 SDValue DAGCombiner::visitSUB(SDNode *N) { 2552 SDValue N0 = N->getOperand(0); 2553 SDValue N1 = N->getOperand(1); 2554 EVT VT = N0.getValueType(); 2555 SDLoc DL(N); 2556 2557 // fold vector ops 2558 if (VT.isVector()) { 2559 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2560 return FoldedVOp; 2561 2562 // fold (sub x, 0) -> x, vector edition 2563 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2564 return N0; 2565 } 2566 2567 // fold (sub x, x) -> 0 2568 // FIXME: Refactor this and xor and other similar operations together. 2569 if (N0 == N1) 2570 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2571 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2572 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2573 // fold (sub c1, c2) -> c1-c2 2574 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2575 N1.getNode()); 2576 } 2577 2578 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2579 return NewSel; 2580 2581 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2582 2583 // fold (sub x, c) -> (add x, -c) 2584 if (N1C) { 2585 return DAG.getNode(ISD::ADD, DL, VT, N0, 2586 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2587 } 2588 2589 if (isNullConstantOrNullSplatConstant(N0)) { 2590 unsigned BitWidth = VT.getScalarSizeInBits(); 2591 // Right-shifting everything out but the sign bit followed by negation is 2592 // the same as flipping arithmetic/logical shift type without the negation: 2593 // -(X >>u 31) -> (X >>s 31) 2594 // -(X >>s 31) -> (X >>u 31) 2595 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2596 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2597 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2598 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2599 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2600 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2601 } 2602 } 2603 2604 // 0 - X --> 0 if the sub is NUW. 2605 if (N->getFlags().hasNoUnsignedWrap()) 2606 return N0; 2607 2608 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2609 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2610 // N1 must be 0 because negating the minimum signed value is undefined. 2611 if (N->getFlags().hasNoSignedWrap()) 2612 return N0; 2613 2614 // 0 - X --> X if X is 0 or the minimum signed value. 2615 return N1; 2616 } 2617 } 2618 2619 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2620 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2621 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2622 2623 // fold (A - (0-B)) -> A+B 2624 if (N1.getOpcode() == ISD::SUB && 2625 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2626 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 2627 2628 // fold A-(A-B) -> B 2629 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2630 return N1.getOperand(1); 2631 2632 // fold (A+B)-A -> B 2633 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2634 return N0.getOperand(1); 2635 2636 // fold (A+B)-B -> A 2637 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2638 return N0.getOperand(0); 2639 2640 // fold C2-(A+C1) -> (C2-C1)-A 2641 if (N1.getOpcode() == ISD::ADD) { 2642 SDValue N11 = N1.getOperand(1); 2643 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2644 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2645 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2646 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2647 } 2648 } 2649 2650 // fold ((A+(B+or-C))-B) -> A+or-C 2651 if (N0.getOpcode() == ISD::ADD && 2652 (N0.getOperand(1).getOpcode() == ISD::SUB || 2653 N0.getOperand(1).getOpcode() == ISD::ADD) && 2654 N0.getOperand(1).getOperand(0) == N1) 2655 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2656 N0.getOperand(1).getOperand(1)); 2657 2658 // fold ((A+(C+B))-B) -> A+C 2659 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2660 N0.getOperand(1).getOperand(1) == N1) 2661 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2662 N0.getOperand(1).getOperand(0)); 2663 2664 // fold ((A-(B-C))-C) -> A-B 2665 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2666 N0.getOperand(1).getOperand(1) == N1) 2667 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2668 N0.getOperand(1).getOperand(0)); 2669 2670 // fold (A-(B-C)) -> A+(C-B) 2671 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 2672 return DAG.getNode(ISD::ADD, DL, VT, N0, 2673 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 2674 N1.getOperand(0))); 2675 2676 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 2677 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 2678 if (N1.getOperand(0).getOpcode() == ISD::SUB && 2679 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) { 2680 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2681 N1.getOperand(0).getOperand(1), 2682 N1.getOperand(1)); 2683 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2684 } 2685 if (N1.getOperand(1).getOpcode() == ISD::SUB && 2686 isNullConstantOrNullSplatConstant(N1.getOperand(1).getOperand(0))) { 2687 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2688 N1.getOperand(0), 2689 N1.getOperand(1).getOperand(1)); 2690 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2691 } 2692 } 2693 2694 // If either operand of a sub is undef, the result is undef 2695 if (N0.isUndef()) 2696 return N0; 2697 if (N1.isUndef()) 2698 return N1; 2699 2700 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2701 return V; 2702 2703 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2704 return V; 2705 2706 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 2707 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 2708 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 2709 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 2710 SDValue S0 = N1.getOperand(0); 2711 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) { 2712 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 2713 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 2714 if (C->getAPIntValue() == (OpSizeInBits - 1)) 2715 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 2716 } 2717 } 2718 } 2719 2720 // If the relocation model supports it, consider symbol offsets. 2721 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2722 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2723 // fold (sub Sym, c) -> Sym-c 2724 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2725 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2726 GA->getOffset() - 2727 (uint64_t)N1C->getSExtValue()); 2728 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2729 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2730 if (GA->getGlobal() == GB->getGlobal()) 2731 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2732 DL, VT); 2733 } 2734 2735 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2736 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2737 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2738 if (TN->getVT() == MVT::i1) { 2739 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2740 DAG.getConstant(1, DL, VT)); 2741 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2742 } 2743 } 2744 2745 // Prefer an add for more folding potential and possibly better codegen: 2746 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 2747 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 2748 SDValue ShAmt = N1.getOperand(1); 2749 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2750 if (ShAmtC && ShAmtC->getZExtValue() == N1.getScalarValueSizeInBits() - 1) { 2751 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 2752 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 2753 } 2754 } 2755 2756 return SDValue(); 2757 } 2758 2759 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2760 SDValue N0 = N->getOperand(0); 2761 SDValue N1 = N->getOperand(1); 2762 EVT VT = N0.getValueType(); 2763 SDLoc DL(N); 2764 2765 // If the flag result is dead, turn this into an SUB. 2766 if (!N->hasAnyUseOfValue(1)) 2767 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2768 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2769 2770 // fold (subc x, x) -> 0 + no borrow 2771 if (N0 == N1) 2772 return CombineTo(N, DAG.getConstant(0, DL, VT), 2773 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2774 2775 // fold (subc x, 0) -> x + no borrow 2776 if (isNullConstant(N1)) 2777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2778 2779 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2780 if (isAllOnesConstant(N0)) 2781 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2782 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2783 2784 return SDValue(); 2785 } 2786 2787 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2788 SDValue N0 = N->getOperand(0); 2789 SDValue N1 = N->getOperand(1); 2790 EVT VT = N0.getValueType(); 2791 if (VT.isVector()) 2792 return SDValue(); 2793 2794 EVT CarryVT = N->getValueType(1); 2795 SDLoc DL(N); 2796 2797 // If the flag result is dead, turn this into an SUB. 2798 if (!N->hasAnyUseOfValue(1)) 2799 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2800 DAG.getUNDEF(CarryVT)); 2801 2802 // fold (usubo x, x) -> 0 + no borrow 2803 if (N0 == N1) 2804 return CombineTo(N, DAG.getConstant(0, DL, VT), 2805 DAG.getConstant(0, DL, CarryVT)); 2806 2807 // fold (usubo x, 0) -> x + no borrow 2808 if (isNullConstant(N1)) 2809 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2810 2811 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2812 if (isAllOnesConstant(N0)) 2813 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2814 DAG.getConstant(0, DL, CarryVT)); 2815 2816 return SDValue(); 2817 } 2818 2819 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2820 SDValue N0 = N->getOperand(0); 2821 SDValue N1 = N->getOperand(1); 2822 SDValue CarryIn = N->getOperand(2); 2823 2824 // fold (sube x, y, false) -> (subc x, y) 2825 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2826 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2827 2828 return SDValue(); 2829 } 2830 2831 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2832 SDValue N0 = N->getOperand(0); 2833 SDValue N1 = N->getOperand(1); 2834 SDValue CarryIn = N->getOperand(2); 2835 2836 // fold (subcarry x, y, false) -> (usubo x, y) 2837 if (isNullConstant(CarryIn)) { 2838 if (!LegalOperations || 2839 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 2840 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2841 } 2842 2843 return SDValue(); 2844 } 2845 2846 SDValue DAGCombiner::visitMUL(SDNode *N) { 2847 SDValue N0 = N->getOperand(0); 2848 SDValue N1 = N->getOperand(1); 2849 EVT VT = N0.getValueType(); 2850 2851 // fold (mul x, undef) -> 0 2852 if (N0.isUndef() || N1.isUndef()) 2853 return DAG.getConstant(0, SDLoc(N), VT); 2854 2855 bool N0IsConst = false; 2856 bool N1IsConst = false; 2857 bool N1IsOpaqueConst = false; 2858 bool N0IsOpaqueConst = false; 2859 APInt ConstValue0, ConstValue1; 2860 // fold vector ops 2861 if (VT.isVector()) { 2862 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2863 return FoldedVOp; 2864 2865 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2866 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2867 assert((!N0IsConst || 2868 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2869 "Splat APInt should be element width"); 2870 assert((!N1IsConst || 2871 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2872 "Splat APInt should be element width"); 2873 } else { 2874 N0IsConst = isa<ConstantSDNode>(N0); 2875 if (N0IsConst) { 2876 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2877 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2878 } 2879 N1IsConst = isa<ConstantSDNode>(N1); 2880 if (N1IsConst) { 2881 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2882 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2883 } 2884 } 2885 2886 // fold (mul c1, c2) -> c1*c2 2887 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2888 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2889 N0.getNode(), N1.getNode()); 2890 2891 // canonicalize constant to RHS (vector doesn't have to splat) 2892 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2893 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2894 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2895 // fold (mul x, 0) -> 0 2896 if (N1IsConst && ConstValue1.isNullValue()) 2897 return N1; 2898 // fold (mul x, 1) -> x 2899 if (N1IsConst && ConstValue1.isOneValue()) 2900 return N0; 2901 2902 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2903 return NewSel; 2904 2905 // fold (mul x, -1) -> 0-x 2906 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2907 SDLoc DL(N); 2908 return DAG.getNode(ISD::SUB, DL, VT, 2909 DAG.getConstant(0, DL, VT), N0); 2910 } 2911 // fold (mul x, (1 << c)) -> x << c 2912 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2913 DAG.isKnownToBeAPowerOfTwo(N1) && 2914 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 2915 SDLoc DL(N); 2916 SDValue LogBase2 = BuildLogBase2(N1, DL); 2917 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2918 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2919 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2920 } 2921 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2922 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2923 unsigned Log2Val = (-ConstValue1).logBase2(); 2924 SDLoc DL(N); 2925 // FIXME: If the input is something that is easily negated (e.g. a 2926 // single-use add), we should put the negate there. 2927 return DAG.getNode(ISD::SUB, DL, VT, 2928 DAG.getConstant(0, DL, VT), 2929 DAG.getNode(ISD::SHL, DL, VT, N0, 2930 DAG.getConstant(Log2Val, DL, 2931 getShiftAmountTy(N0.getValueType())))); 2932 } 2933 2934 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2935 if (N0.getOpcode() == ISD::SHL && 2936 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2937 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2938 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2939 if (isConstantOrConstantVector(C3)) 2940 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2941 } 2942 2943 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2944 // use. 2945 { 2946 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2947 2948 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2949 if (N0.getOpcode() == ISD::SHL && 2950 isConstantOrConstantVector(N0.getOperand(1)) && 2951 N0.getNode()->hasOneUse()) { 2952 Sh = N0; Y = N1; 2953 } else if (N1.getOpcode() == ISD::SHL && 2954 isConstantOrConstantVector(N1.getOperand(1)) && 2955 N1.getNode()->hasOneUse()) { 2956 Sh = N1; Y = N0; 2957 } 2958 2959 if (Sh.getNode()) { 2960 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2961 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2962 } 2963 } 2964 2965 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2966 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2967 N0.getOpcode() == ISD::ADD && 2968 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2969 isMulAddWithConstProfitable(N, N0, N1)) 2970 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2971 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2972 N0.getOperand(0), N1), 2973 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2974 N0.getOperand(1), N1)); 2975 2976 // reassociate mul 2977 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2978 return RMUL; 2979 2980 return SDValue(); 2981 } 2982 2983 /// Return true if divmod libcall is available. 2984 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2985 const TargetLowering &TLI) { 2986 RTLIB::Libcall LC; 2987 EVT NodeType = Node->getValueType(0); 2988 if (!NodeType.isSimple()) 2989 return false; 2990 switch (NodeType.getSimpleVT().SimpleTy) { 2991 default: return false; // No libcall for vector types. 2992 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2993 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2994 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2995 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2996 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2997 } 2998 2999 return TLI.getLibcallName(LC) != nullptr; 3000 } 3001 3002 /// Issue divrem if both quotient and remainder are needed. 3003 SDValue DAGCombiner::useDivRem(SDNode *Node) { 3004 if (Node->use_empty()) 3005 return SDValue(); // This is a dead node, leave it alone. 3006 3007 unsigned Opcode = Node->getOpcode(); 3008 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 3009 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3010 3011 // DivMod lib calls can still work on non-legal types if using lib-calls. 3012 EVT VT = Node->getValueType(0); 3013 if (VT.isVector() || !VT.isInteger()) 3014 return SDValue(); 3015 3016 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 3017 return SDValue(); 3018 3019 // If DIVREM is going to get expanded into a libcall, 3020 // but there is no libcall available, then don't combine. 3021 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 3022 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 3023 return SDValue(); 3024 3025 // If div is legal, it's better to do the normal expansion 3026 unsigned OtherOpcode = 0; 3027 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 3028 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 3029 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 3030 return SDValue(); 3031 } else { 3032 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3033 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 3034 return SDValue(); 3035 } 3036 3037 SDValue Op0 = Node->getOperand(0); 3038 SDValue Op1 = Node->getOperand(1); 3039 SDValue combined; 3040 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 3041 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 3042 SDNode *User = *UI; 3043 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 3044 User->use_empty()) 3045 continue; 3046 // Convert the other matching node(s), too; 3047 // otherwise, the DIVREM may get target-legalized into something 3048 // target-specific that we won't be able to recognize. 3049 unsigned UserOpc = User->getOpcode(); 3050 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 3051 User->getOperand(0) == Op0 && 3052 User->getOperand(1) == Op1) { 3053 if (!combined) { 3054 if (UserOpc == OtherOpcode) { 3055 SDVTList VTs = DAG.getVTList(VT, VT); 3056 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 3057 } else if (UserOpc == DivRemOpc) { 3058 combined = SDValue(User, 0); 3059 } else { 3060 assert(UserOpc == Opcode); 3061 continue; 3062 } 3063 } 3064 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 3065 CombineTo(User, combined); 3066 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 3067 CombineTo(User, combined.getValue(1)); 3068 } 3069 } 3070 return combined; 3071 } 3072 3073 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 3074 SDValue N0 = N->getOperand(0); 3075 SDValue N1 = N->getOperand(1); 3076 EVT VT = N->getValueType(0); 3077 SDLoc DL(N); 3078 3079 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 3080 return DAG.getUNDEF(VT); 3081 3082 // undef / X -> 0 3083 // undef % X -> 0 3084 if (N0.isUndef()) 3085 return DAG.getConstant(0, DL, VT); 3086 3087 return SDValue(); 3088 } 3089 3090 SDValue DAGCombiner::visitSDIV(SDNode *N) { 3091 SDValue N0 = N->getOperand(0); 3092 SDValue N1 = N->getOperand(1); 3093 EVT VT = N->getValueType(0); 3094 EVT CCVT = getSetCCResultType(VT); 3095 3096 // fold vector ops 3097 if (VT.isVector()) 3098 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3099 return FoldedVOp; 3100 3101 SDLoc DL(N); 3102 3103 // fold (sdiv c1, c2) -> c1/c2 3104 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3105 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3106 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 3107 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 3108 // fold (sdiv X, 1) -> X 3109 if (N1C && N1C->isOne()) 3110 return N0; 3111 // fold (sdiv X, -1) -> 0-X 3112 if (N1C && N1C->isAllOnesValue()) 3113 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 3114 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 3115 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 3116 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3117 DAG.getConstant(1, DL, VT), 3118 DAG.getConstant(0, DL, VT)); 3119 3120 if (SDValue V = simplifyDivRem(N, DAG)) 3121 return V; 3122 3123 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3124 return NewSel; 3125 3126 // If we know the sign bits of both operands are zero, strength reduce to a 3127 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 3128 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3129 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 3130 3131 if (SDValue V = visitSDIVLike(N0, N1, N)) 3132 return V; 3133 3134 // sdiv, srem -> sdivrem 3135 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3136 // true. Otherwise, we break the simplification logic in visitREM(). 3137 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3138 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3139 if (SDValue DivRem = useDivRem(N)) 3140 return DivRem; 3141 3142 return SDValue(); 3143 } 3144 3145 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3146 SDLoc DL(N); 3147 EVT VT = N->getValueType(0); 3148 EVT CCVT = getSetCCResultType(VT); 3149 unsigned BitWidth = VT.getScalarSizeInBits(); 3150 3151 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3152 3153 // Helper for determining whether a value is a power-2 constant scalar or a 3154 // vector of such elements. 3155 auto IsPowerOfTwo = [](ConstantSDNode *C) { 3156 if (C->isNullValue() || C->isOpaque()) 3157 return false; 3158 if (C->getAPIntValue().isPowerOf2()) 3159 return true; 3160 if ((-C->getAPIntValue()).isPowerOf2()) 3161 return true; 3162 return false; 3163 }; 3164 3165 // fold (sdiv X, pow2) -> simple ops after legalize 3166 // FIXME: We check for the exact bit here because the generic lowering gives 3167 // better results in that case. The target-specific lowering should learn how 3168 // to handle exact sdivs efficiently. 3169 if (!N->getFlags().hasExact() && 3170 ISD::matchUnaryPredicate(N1C ? SDValue(N1C, 0) : N1, IsPowerOfTwo)) { 3171 // Target-specific implementation of sdiv x, pow2. 3172 if (SDValue Res = BuildSDIVPow2(N)) 3173 return Res; 3174 3175 // Create constants that are functions of the shift amount value. 3176 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 3177 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 3178 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 3179 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 3180 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 3181 if (!isConstantOrConstantVector(Inexact)) 3182 return SDValue(); 3183 3184 // Splat the sign bit into the register 3185 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 3186 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 3187 AddToWorklist(Sign.getNode()); 3188 3189 // Add (N0 < 0) ? abs2 - 1 : 0; 3190 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 3191 AddToWorklist(Srl.getNode()); 3192 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 3193 AddToWorklist(Add.getNode()); 3194 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 3195 AddToWorklist(Sra.getNode()); 3196 3197 // Special case: (sdiv X, 1) -> X 3198 // Special Case: (sdiv X, -1) -> 0-X 3199 SDValue One = DAG.getConstant(1, DL, VT); 3200 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 3201 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 3202 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 3203 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 3204 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 3205 3206 // If dividing by a positive value, we're done. Otherwise, the result must 3207 // be negated. 3208 SDValue Zero = DAG.getConstant(0, DL, VT); 3209 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 3210 3211 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 3212 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 3213 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 3214 return Res; 3215 } 3216 3217 // If integer divide is expensive and we satisfy the requirements, emit an 3218 // alternate sequence. Targets may check function attributes for size/speed 3219 // trade-offs. 3220 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3221 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3222 if (SDValue Op = BuildSDIV(N)) 3223 return Op; 3224 3225 return SDValue(); 3226 } 3227 3228 SDValue DAGCombiner::visitUDIV(SDNode *N) { 3229 SDValue N0 = N->getOperand(0); 3230 SDValue N1 = N->getOperand(1); 3231 EVT VT = N->getValueType(0); 3232 EVT CCVT = getSetCCResultType(VT); 3233 3234 // fold vector ops 3235 if (VT.isVector()) 3236 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3237 return FoldedVOp; 3238 3239 SDLoc DL(N); 3240 3241 // fold (udiv c1, c2) -> c1/c2 3242 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3243 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3244 if (N0C && N1C) 3245 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 3246 N0C, N1C)) 3247 return Folded; 3248 // fold (udiv X, 1) -> X 3249 if (N1C && N1C->isOne()) 3250 return N0; 3251 // fold (udiv X, -1) -> select(X == -1, 1, 0) 3252 if (N1C && N1C->getAPIntValue().isAllOnesValue()) 3253 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3254 DAG.getConstant(1, DL, VT), 3255 DAG.getConstant(0, DL, VT)); 3256 3257 if (SDValue V = simplifyDivRem(N, DAG)) 3258 return V; 3259 3260 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3261 return NewSel; 3262 3263 if (SDValue V = visitUDIVLike(N0, N1, N)) 3264 return V; 3265 3266 // sdiv, srem -> sdivrem 3267 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3268 // true. Otherwise, we break the simplification logic in visitREM(). 3269 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3270 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3271 if (SDValue DivRem = useDivRem(N)) 3272 return DivRem; 3273 3274 return SDValue(); 3275 } 3276 3277 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3278 SDLoc DL(N); 3279 EVT VT = N->getValueType(0); 3280 3281 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3282 3283 // fold (udiv x, (1 << c)) -> x >>u c 3284 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3285 DAG.isKnownToBeAPowerOfTwo(N1)) { 3286 SDValue LogBase2 = BuildLogBase2(N1, DL); 3287 AddToWorklist(LogBase2.getNode()); 3288 3289 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3290 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3291 AddToWorklist(Trunc.getNode()); 3292 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3293 } 3294 3295 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 3296 if (N1.getOpcode() == ISD::SHL) { 3297 SDValue N10 = N1.getOperand(0); 3298 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 3299 DAG.isKnownToBeAPowerOfTwo(N10)) { 3300 SDValue LogBase2 = BuildLogBase2(N10, DL); 3301 AddToWorklist(LogBase2.getNode()); 3302 3303 EVT ADDVT = N1.getOperand(1).getValueType(); 3304 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 3305 AddToWorklist(Trunc.getNode()); 3306 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 3307 AddToWorklist(Add.getNode()); 3308 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 3309 } 3310 } 3311 3312 // fold (udiv x, c) -> alternate 3313 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3314 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3315 if (SDValue Op = BuildUDIV(N)) 3316 return Op; 3317 3318 return SDValue(); 3319 } 3320 3321 // handles ISD::SREM and ISD::UREM 3322 SDValue DAGCombiner::visitREM(SDNode *N) { 3323 unsigned Opcode = N->getOpcode(); 3324 SDValue N0 = N->getOperand(0); 3325 SDValue N1 = N->getOperand(1); 3326 EVT VT = N->getValueType(0); 3327 EVT CCVT = getSetCCResultType(VT); 3328 3329 bool isSigned = (Opcode == ISD::SREM); 3330 SDLoc DL(N); 3331 3332 // fold (rem c1, c2) -> c1%c2 3333 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3334 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3335 if (N0C && N1C) 3336 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3337 return Folded; 3338 // fold (urem X, -1) -> select(X == -1, 0, x) 3339 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) 3340 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3341 DAG.getConstant(0, DL, VT), N0); 3342 3343 if (SDValue V = simplifyDivRem(N, DAG)) 3344 return V; 3345 3346 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3347 return NewSel; 3348 3349 if (isSigned) { 3350 // If we know the sign bits of both operands are zero, strength reduce to a 3351 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3352 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3353 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3354 } else { 3355 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3356 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3357 // fold (urem x, pow2) -> (and x, pow2-1) 3358 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3359 AddToWorklist(Add.getNode()); 3360 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3361 } 3362 if (N1.getOpcode() == ISD::SHL && 3363 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3364 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3365 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3366 AddToWorklist(Add.getNode()); 3367 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3368 } 3369 } 3370 3371 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3372 3373 // If X/C can be simplified by the division-by-constant logic, lower 3374 // X%C to the equivalent of X-X/C*C. 3375 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 3376 // speculative DIV must not cause a DIVREM conversion. We guard against this 3377 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 3378 // combine will not return a DIVREM. Regardless, checking cheapness here 3379 // makes sense since the simplification results in fatter code. 3380 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 3381 SDValue OptimizedDiv = 3382 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 3383 if (OptimizedDiv.getNode() && OptimizedDiv.getOpcode() != ISD::UDIVREM && 3384 OptimizedDiv.getOpcode() != ISD::SDIVREM) { 3385 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3386 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3387 AddToWorklist(OptimizedDiv.getNode()); 3388 AddToWorklist(Mul.getNode()); 3389 return Sub; 3390 } 3391 } 3392 3393 // sdiv, srem -> sdivrem 3394 if (SDValue DivRem = useDivRem(N)) 3395 return DivRem.getValue(1); 3396 3397 return SDValue(); 3398 } 3399 3400 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3401 SDValue N0 = N->getOperand(0); 3402 SDValue N1 = N->getOperand(1); 3403 EVT VT = N->getValueType(0); 3404 SDLoc DL(N); 3405 3406 if (VT.isVector()) { 3407 // fold (mulhs x, 0) -> 0 3408 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3409 return N1; 3410 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3411 return N0; 3412 } 3413 3414 // fold (mulhs x, 0) -> 0 3415 if (isNullConstant(N1)) 3416 return N1; 3417 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3418 if (isOneConstant(N1)) 3419 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3420 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3421 getShiftAmountTy(N0.getValueType()))); 3422 3423 // fold (mulhs x, undef) -> 0 3424 if (N0.isUndef() || N1.isUndef()) 3425 return DAG.getConstant(0, DL, VT); 3426 3427 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3428 // plus a shift. 3429 if (VT.isSimple() && !VT.isVector()) { 3430 MVT Simple = VT.getSimpleVT(); 3431 unsigned SimpleSize = Simple.getSizeInBits(); 3432 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3433 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3434 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3435 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3436 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3437 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3438 DAG.getConstant(SimpleSize, DL, 3439 getShiftAmountTy(N1.getValueType()))); 3440 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3441 } 3442 } 3443 3444 return SDValue(); 3445 } 3446 3447 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3448 SDValue N0 = N->getOperand(0); 3449 SDValue N1 = N->getOperand(1); 3450 EVT VT = N->getValueType(0); 3451 SDLoc DL(N); 3452 3453 if (VT.isVector()) { 3454 // fold (mulhu x, 0) -> 0 3455 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3456 return N1; 3457 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3458 return N0; 3459 } 3460 3461 // fold (mulhu x, 0) -> 0 3462 if (isNullConstant(N1)) 3463 return N1; 3464 // fold (mulhu x, 1) -> 0 3465 if (isOneConstant(N1)) 3466 return DAG.getConstant(0, DL, N0.getValueType()); 3467 // fold (mulhu x, undef) -> 0 3468 if (N0.isUndef() || N1.isUndef()) 3469 return DAG.getConstant(0, DL, VT); 3470 3471 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3472 // plus a shift. 3473 if (VT.isSimple() && !VT.isVector()) { 3474 MVT Simple = VT.getSimpleVT(); 3475 unsigned SimpleSize = Simple.getSizeInBits(); 3476 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3477 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3478 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3479 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3480 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3481 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3482 DAG.getConstant(SimpleSize, DL, 3483 getShiftAmountTy(N1.getValueType()))); 3484 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3485 } 3486 } 3487 3488 return SDValue(); 3489 } 3490 3491 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3492 /// give the opcodes for the two computations that are being performed. Return 3493 /// true if a simplification was made. 3494 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3495 unsigned HiOp) { 3496 // If the high half is not needed, just compute the low half. 3497 bool HiExists = N->hasAnyUseOfValue(1); 3498 if (!HiExists && 3499 (!LegalOperations || 3500 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3501 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3502 return CombineTo(N, Res, Res); 3503 } 3504 3505 // If the low half is not needed, just compute the high half. 3506 bool LoExists = N->hasAnyUseOfValue(0); 3507 if (!LoExists && 3508 (!LegalOperations || 3509 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3510 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3511 return CombineTo(N, Res, Res); 3512 } 3513 3514 // If both halves are used, return as it is. 3515 if (LoExists && HiExists) 3516 return SDValue(); 3517 3518 // If the two computed results can be simplified separately, separate them. 3519 if (LoExists) { 3520 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3521 AddToWorklist(Lo.getNode()); 3522 SDValue LoOpt = combine(Lo.getNode()); 3523 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3524 (!LegalOperations || 3525 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3526 return CombineTo(N, LoOpt, LoOpt); 3527 } 3528 3529 if (HiExists) { 3530 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3531 AddToWorklist(Hi.getNode()); 3532 SDValue HiOpt = combine(Hi.getNode()); 3533 if (HiOpt.getNode() && HiOpt != Hi && 3534 (!LegalOperations || 3535 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3536 return CombineTo(N, HiOpt, HiOpt); 3537 } 3538 3539 return SDValue(); 3540 } 3541 3542 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3543 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3544 return Res; 3545 3546 EVT VT = N->getValueType(0); 3547 SDLoc DL(N); 3548 3549 // If the type is twice as wide is legal, transform the mulhu to a wider 3550 // multiply plus a shift. 3551 if (VT.isSimple() && !VT.isVector()) { 3552 MVT Simple = VT.getSimpleVT(); 3553 unsigned SimpleSize = Simple.getSizeInBits(); 3554 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3555 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3556 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3557 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3558 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3559 // Compute the high part as N1. 3560 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3561 DAG.getConstant(SimpleSize, DL, 3562 getShiftAmountTy(Lo.getValueType()))); 3563 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3564 // Compute the low part as N0. 3565 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3566 return CombineTo(N, Lo, Hi); 3567 } 3568 } 3569 3570 return SDValue(); 3571 } 3572 3573 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3574 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3575 return Res; 3576 3577 EVT VT = N->getValueType(0); 3578 SDLoc DL(N); 3579 3580 // If the type is twice as wide is legal, transform the mulhu to a wider 3581 // multiply plus a shift. 3582 if (VT.isSimple() && !VT.isVector()) { 3583 MVT Simple = VT.getSimpleVT(); 3584 unsigned SimpleSize = Simple.getSizeInBits(); 3585 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3586 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3587 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3588 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3589 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3590 // Compute the high part as N1. 3591 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3592 DAG.getConstant(SimpleSize, DL, 3593 getShiftAmountTy(Lo.getValueType()))); 3594 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3595 // Compute the low part as N0. 3596 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3597 return CombineTo(N, Lo, Hi); 3598 } 3599 } 3600 3601 return SDValue(); 3602 } 3603 3604 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3605 // (smulo x, 2) -> (saddo x, x) 3606 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3607 if (C2->getAPIntValue() == 2) 3608 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3609 N->getOperand(0), N->getOperand(0)); 3610 3611 return SDValue(); 3612 } 3613 3614 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3615 // (umulo x, 2) -> (uaddo x, x) 3616 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3617 if (C2->getAPIntValue() == 2) 3618 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3619 N->getOperand(0), N->getOperand(0)); 3620 3621 return SDValue(); 3622 } 3623 3624 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3625 SDValue N0 = N->getOperand(0); 3626 SDValue N1 = N->getOperand(1); 3627 EVT VT = N0.getValueType(); 3628 3629 // fold vector ops 3630 if (VT.isVector()) 3631 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3632 return FoldedVOp; 3633 3634 // fold operation with constant operands. 3635 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3636 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3637 if (N0C && N1C) 3638 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3639 3640 // canonicalize constant to RHS 3641 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3642 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3643 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3644 3645 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 3646 // Only do this if the current op isn't legal and the flipped is. 3647 unsigned Opcode = N->getOpcode(); 3648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3649 if (!TLI.isOperationLegal(Opcode, VT) && 3650 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 3651 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 3652 unsigned AltOpcode; 3653 switch (Opcode) { 3654 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 3655 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 3656 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 3657 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 3658 default: llvm_unreachable("Unknown MINMAX opcode"); 3659 } 3660 if (TLI.isOperationLegal(AltOpcode, VT)) 3661 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 3662 } 3663 3664 return SDValue(); 3665 } 3666 3667 /// If this is a binary operator with two operands of the same opcode, try to 3668 /// simplify it. 3669 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3670 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3671 EVT VT = N0.getValueType(); 3672 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3673 3674 // Bail early if none of these transforms apply. 3675 if (N0.getNumOperands() == 0) return SDValue(); 3676 3677 // For each of OP in AND/OR/XOR: 3678 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3679 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3680 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3681 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3682 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3683 // 3684 // do not sink logical op inside of a vector extend, since it may combine 3685 // into a vsetcc. 3686 EVT Op0VT = N0.getOperand(0).getValueType(); 3687 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3688 N0.getOpcode() == ISD::SIGN_EXTEND || 3689 N0.getOpcode() == ISD::BSWAP || 3690 // Avoid infinite looping with PromoteIntBinOp. 3691 (N0.getOpcode() == ISD::ANY_EXTEND && 3692 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3693 (N0.getOpcode() == ISD::TRUNCATE && 3694 (!TLI.isZExtFree(VT, Op0VT) || 3695 !TLI.isTruncateFree(Op0VT, VT)) && 3696 TLI.isTypeLegal(Op0VT))) && 3697 !VT.isVector() && 3698 Op0VT == N1.getOperand(0).getValueType() && 3699 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3700 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3701 N0.getOperand(0).getValueType(), 3702 N0.getOperand(0), N1.getOperand(0)); 3703 AddToWorklist(ORNode.getNode()); 3704 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3705 } 3706 3707 // For each of OP in SHL/SRL/SRA/AND... 3708 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3709 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3710 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3711 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3712 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3713 N0.getOperand(1) == N1.getOperand(1)) { 3714 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3715 N0.getOperand(0).getValueType(), 3716 N0.getOperand(0), N1.getOperand(0)); 3717 AddToWorklist(ORNode.getNode()); 3718 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3719 ORNode, N0.getOperand(1)); 3720 } 3721 3722 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3723 // Only perform this optimization up until type legalization, before 3724 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3725 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3726 // we don't want to undo this promotion. 3727 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3728 // on scalars. 3729 if ((N0.getOpcode() == ISD::BITCAST || 3730 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3731 Level <= AfterLegalizeTypes) { 3732 SDValue In0 = N0.getOperand(0); 3733 SDValue In1 = N1.getOperand(0); 3734 EVT In0Ty = In0.getValueType(); 3735 EVT In1Ty = In1.getValueType(); 3736 SDLoc DL(N); 3737 // If both incoming values are integers, and the original types are the 3738 // same. 3739 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3740 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3741 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3742 AddToWorklist(Op.getNode()); 3743 return BC; 3744 } 3745 } 3746 3747 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3748 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3749 // If both shuffles use the same mask, and both shuffle within a single 3750 // vector, then it is worthwhile to move the swizzle after the operation. 3751 // The type-legalizer generates this pattern when loading illegal 3752 // vector types from memory. In many cases this allows additional shuffle 3753 // optimizations. 3754 // There are other cases where moving the shuffle after the xor/and/or 3755 // is profitable even if shuffles don't perform a swizzle. 3756 // If both shuffles use the same mask, and both shuffles have the same first 3757 // or second operand, then it might still be profitable to move the shuffle 3758 // after the xor/and/or operation. 3759 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3760 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3761 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3762 3763 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3764 "Inputs to shuffles are not the same type"); 3765 3766 // Check that both shuffles use the same mask. The masks are known to be of 3767 // the same length because the result vector type is the same. 3768 // Check also that shuffles have only one use to avoid introducing extra 3769 // instructions. 3770 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3771 SVN0->getMask().equals(SVN1->getMask())) { 3772 SDValue ShOp = N0->getOperand(1); 3773 3774 // Don't try to fold this node if it requires introducing a 3775 // build vector of all zeros that might be illegal at this stage. 3776 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3777 if (!LegalTypes) 3778 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3779 else 3780 ShOp = SDValue(); 3781 } 3782 3783 // (AND (shuf (A, C), shuf (B, C))) -> shuf (AND (A, B), C) 3784 // (OR (shuf (A, C), shuf (B, C))) -> shuf (OR (A, B), C) 3785 // (XOR (shuf (A, C), shuf (B, C))) -> shuf (XOR (A, B), V_0) 3786 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3787 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3788 N0->getOperand(0), N1->getOperand(0)); 3789 AddToWorklist(NewNode.getNode()); 3790 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3791 SVN0->getMask()); 3792 } 3793 3794 // Don't try to fold this node if it requires introducing a 3795 // build vector of all zeros that might be illegal at this stage. 3796 ShOp = N0->getOperand(0); 3797 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3798 if (!LegalTypes) 3799 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3800 else 3801 ShOp = SDValue(); 3802 } 3803 3804 // (AND (shuf (C, A), shuf (C, B))) -> shuf (C, AND (A, B)) 3805 // (OR (shuf (C, A), shuf (C, B))) -> shuf (C, OR (A, B)) 3806 // (XOR (shuf (C, A), shuf (C, B))) -> shuf (V_0, XOR (A, B)) 3807 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3808 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3809 N0->getOperand(1), N1->getOperand(1)); 3810 AddToWorklist(NewNode.getNode()); 3811 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3812 SVN0->getMask()); 3813 } 3814 } 3815 } 3816 3817 return SDValue(); 3818 } 3819 3820 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3821 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3822 const SDLoc &DL) { 3823 SDValue LL, LR, RL, RR, N0CC, N1CC; 3824 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3825 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3826 return SDValue(); 3827 3828 assert(N0.getValueType() == N1.getValueType() && 3829 "Unexpected operand types for bitwise logic op"); 3830 assert(LL.getValueType() == LR.getValueType() && 3831 RL.getValueType() == RR.getValueType() && 3832 "Unexpected operand types for setcc"); 3833 3834 // If we're here post-legalization or the logic op type is not i1, the logic 3835 // op type must match a setcc result type. Also, all folds require new 3836 // operations on the left and right operands, so those types must match. 3837 EVT VT = N0.getValueType(); 3838 EVT OpVT = LL.getValueType(); 3839 if (LegalOperations || VT.getScalarType() != MVT::i1) 3840 if (VT != getSetCCResultType(OpVT)) 3841 return SDValue(); 3842 if (OpVT != RL.getValueType()) 3843 return SDValue(); 3844 3845 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3846 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3847 bool IsInteger = OpVT.isInteger(); 3848 if (LR == RR && CC0 == CC1 && IsInteger) { 3849 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3850 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3851 3852 // All bits clear? 3853 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3854 // All sign bits clear? 3855 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3856 // Any bits set? 3857 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3858 // Any sign bits set? 3859 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3860 3861 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3862 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3863 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3864 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3865 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3866 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3867 AddToWorklist(Or.getNode()); 3868 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3869 } 3870 3871 // All bits set? 3872 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3873 // All sign bits set? 3874 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3875 // Any bits clear? 3876 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3877 // Any sign bits clear? 3878 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3879 3880 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3881 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3882 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3883 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3884 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3885 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3886 AddToWorklist(And.getNode()); 3887 return DAG.getSetCC(DL, VT, And, LR, CC1); 3888 } 3889 } 3890 3891 // TODO: What is the 'or' equivalent of this fold? 3892 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3893 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 3894 IsInteger && CC0 == ISD::SETNE && 3895 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3896 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3897 SDValue One = DAG.getConstant(1, DL, OpVT); 3898 SDValue Two = DAG.getConstant(2, DL, OpVT); 3899 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3900 AddToWorklist(Add.getNode()); 3901 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3902 } 3903 3904 // Try more general transforms if the predicates match and the only user of 3905 // the compares is the 'and' or 'or'. 3906 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3907 N0.hasOneUse() && N1.hasOneUse()) { 3908 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3909 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3910 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3911 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3912 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3913 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3914 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3915 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3916 } 3917 } 3918 3919 // Canonicalize equivalent operands to LL == RL. 3920 if (LL == RR && LR == RL) { 3921 CC1 = ISD::getSetCCSwappedOperands(CC1); 3922 std::swap(RL, RR); 3923 } 3924 3925 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3926 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3927 if (LL == RL && LR == RR) { 3928 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3929 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3930 if (NewCC != ISD::SETCC_INVALID && 3931 (!LegalOperations || 3932 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3933 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3934 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3935 } 3936 3937 return SDValue(); 3938 } 3939 3940 /// This contains all DAGCombine rules which reduce two values combined by 3941 /// an And operation to a single value. This makes them reusable in the context 3942 /// of visitSELECT(). Rules involving constants are not included as 3943 /// visitSELECT() already handles those cases. 3944 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3945 EVT VT = N1.getValueType(); 3946 SDLoc DL(N); 3947 3948 // fold (and x, undef) -> 0 3949 if (N0.isUndef() || N1.isUndef()) 3950 return DAG.getConstant(0, DL, VT); 3951 3952 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3953 return V; 3954 3955 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3956 VT.getSizeInBits() <= 64) { 3957 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3958 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3959 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3960 // immediate for an add, but it is legal if its top c2 bits are set, 3961 // transform the ADD so the immediate doesn't need to be materialized 3962 // in a register. 3963 APInt ADDC = ADDI->getAPIntValue(); 3964 APInt SRLC = SRLI->getAPIntValue(); 3965 if (ADDC.getMinSignedBits() <= 64 && 3966 SRLC.ult(VT.getSizeInBits()) && 3967 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3968 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3969 SRLC.getZExtValue()); 3970 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3971 ADDC |= Mask; 3972 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3973 SDLoc DL0(N0); 3974 SDValue NewAdd = 3975 DAG.getNode(ISD::ADD, DL0, VT, 3976 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3977 CombineTo(N0.getNode(), NewAdd); 3978 // Return N so it doesn't get rechecked! 3979 return SDValue(N, 0); 3980 } 3981 } 3982 } 3983 } 3984 } 3985 } 3986 3987 // Reduce bit extract of low half of an integer to the narrower type. 3988 // (and (srl i64:x, K), KMask) -> 3989 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3990 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3991 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3992 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3993 unsigned Size = VT.getSizeInBits(); 3994 const APInt &AndMask = CAnd->getAPIntValue(); 3995 unsigned ShiftBits = CShift->getZExtValue(); 3996 3997 // Bail out, this node will probably disappear anyway. 3998 if (ShiftBits == 0) 3999 return SDValue(); 4000 4001 unsigned MaskBits = AndMask.countTrailingOnes(); 4002 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 4003 4004 if (AndMask.isMask() && 4005 // Required bits must not span the two halves of the integer and 4006 // must fit in the half size type. 4007 (ShiftBits + MaskBits <= Size / 2) && 4008 TLI.isNarrowingProfitable(VT, HalfVT) && 4009 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 4010 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 4011 TLI.isTruncateFree(VT, HalfVT) && 4012 TLI.isZExtFree(HalfVT, VT)) { 4013 // The isNarrowingProfitable is to avoid regressions on PPC and 4014 // AArch64 which match a few 64-bit bit insert / bit extract patterns 4015 // on downstream users of this. Those patterns could probably be 4016 // extended to handle extensions mixed in. 4017 4018 SDValue SL(N0); 4019 assert(MaskBits <= Size); 4020 4021 // Extracting the highest bit of the low half. 4022 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 4023 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 4024 N0.getOperand(0)); 4025 4026 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 4027 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 4028 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 4029 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 4030 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 4031 } 4032 } 4033 } 4034 } 4035 4036 return SDValue(); 4037 } 4038 4039 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 4040 EVT LoadResultTy, EVT &ExtVT) { 4041 if (!AndC->getAPIntValue().isMask()) 4042 return false; 4043 4044 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 4045 4046 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4047 EVT LoadedVT = LoadN->getMemoryVT(); 4048 4049 if (ExtVT == LoadedVT && 4050 (!LegalOperations || 4051 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 4052 // ZEXTLOAD will match without needing to change the size of the value being 4053 // loaded. 4054 return true; 4055 } 4056 4057 // Do not change the width of a volatile load. 4058 if (LoadN->isVolatile()) 4059 return false; 4060 4061 // Do not generate loads of non-round integer types since these can 4062 // be expensive (and would be wrong if the type is not byte sized). 4063 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 4064 return false; 4065 4066 if (LegalOperations && 4067 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 4068 return false; 4069 4070 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 4071 return false; 4072 4073 return true; 4074 } 4075 4076 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 4077 ISD::LoadExtType ExtType, EVT &MemVT, 4078 unsigned ShAmt) { 4079 if (!LDST) 4080 return false; 4081 // Only allow byte offsets. 4082 if (ShAmt % 8) 4083 return false; 4084 4085 // Do not generate loads of non-round integer types since these can 4086 // be expensive (and would be wrong if the type is not byte sized). 4087 if (!MemVT.isRound()) 4088 return false; 4089 4090 // Don't change the width of a volatile load. 4091 if (LDST->isVolatile()) 4092 return false; 4093 4094 // Verify that we are actually reducing a load width here. 4095 if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits()) 4096 return false; 4097 4098 // Ensure that this isn't going to produce an unsupported unaligned access. 4099 if (ShAmt && 4100 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4101 LDST->getAddressSpace(), ShAmt / 8)) 4102 return false; 4103 4104 // It's not possible to generate a constant of extended or untyped type. 4105 EVT PtrType = LDST->getBasePtr().getValueType(); 4106 if (PtrType == MVT::Untyped || PtrType.isExtended()) 4107 return false; 4108 4109 if (isa<LoadSDNode>(LDST)) { 4110 LoadSDNode *Load = cast<LoadSDNode>(LDST); 4111 // Don't transform one with multiple uses, this would require adding a new 4112 // load. 4113 if (!SDValue(Load, 0).hasOneUse()) 4114 return false; 4115 4116 if (LegalOperations && 4117 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 4118 return false; 4119 4120 // For the transform to be legal, the load must produce only two values 4121 // (the value loaded and the chain). Don't transform a pre-increment 4122 // load, for example, which produces an extra value. Otherwise the 4123 // transformation is not equivalent, and the downstream logic to replace 4124 // uses gets things wrong. 4125 if (Load->getNumValues() > 2) 4126 return false; 4127 4128 // If the load that we're shrinking is an extload and we're not just 4129 // discarding the extension we can't simply shrink the load. Bail. 4130 // TODO: It would be possible to merge the extensions in some cases. 4131 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 4132 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4133 return false; 4134 4135 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 4136 return false; 4137 } else { 4138 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 4139 StoreSDNode *Store = cast<StoreSDNode>(LDST); 4140 // Can't write outside the original store 4141 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4142 return false; 4143 4144 if (LegalOperations && 4145 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 4146 return false; 4147 } 4148 return true; 4149 } 4150 4151 bool DAGCombiner::SearchForAndLoads(SDNode *N, 4152 SmallPtrSetImpl<LoadSDNode*> &Loads, 4153 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 4154 ConstantSDNode *Mask, 4155 SDNode *&NodeToMask) { 4156 // Recursively search for the operands, looking for loads which can be 4157 // narrowed. 4158 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 4159 SDValue Op = N->getOperand(i); 4160 4161 if (Op.getValueType().isVector()) 4162 return false; 4163 4164 // Some constants may need fixing up later if they are too large. 4165 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4166 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 4167 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 4168 NodesWithConsts.insert(N); 4169 continue; 4170 } 4171 4172 if (!Op.hasOneUse()) 4173 return false; 4174 4175 switch(Op.getOpcode()) { 4176 case ISD::LOAD: { 4177 auto *Load = cast<LoadSDNode>(Op); 4178 EVT ExtVT; 4179 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 4180 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 4181 4182 // ZEXTLOAD is already small enough. 4183 if (Load->getExtensionType() == ISD::ZEXTLOAD && 4184 ExtVT.bitsGE(Load->getMemoryVT())) 4185 continue; 4186 4187 // Use LE to convert equal sized loads to zext. 4188 if (ExtVT.bitsLE(Load->getMemoryVT())) 4189 Loads.insert(Load); 4190 4191 continue; 4192 } 4193 return false; 4194 } 4195 case ISD::ZERO_EXTEND: 4196 case ISD::AssertZext: { 4197 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 4198 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4199 EVT VT = Op.getOpcode() == ISD::AssertZext ? 4200 cast<VTSDNode>(Op.getOperand(1))->getVT() : 4201 Op.getOperand(0).getValueType(); 4202 4203 // We can accept extending nodes if the mask is wider or an equal 4204 // width to the original type. 4205 if (ExtVT.bitsGE(VT)) 4206 continue; 4207 break; 4208 } 4209 case ISD::OR: 4210 case ISD::XOR: 4211 case ISD::AND: 4212 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 4213 NodeToMask)) 4214 return false; 4215 continue; 4216 } 4217 4218 // Allow one node which will masked along with any loads found. 4219 if (NodeToMask) 4220 return false; 4221 4222 // Also ensure that the node to be masked only produces one data result. 4223 NodeToMask = Op.getNode(); 4224 if (NodeToMask->getNumValues() > 1) { 4225 bool HasValue = false; 4226 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 4227 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 4228 if (VT != MVT::Glue && VT != MVT::Other) { 4229 if (HasValue) { 4230 NodeToMask = nullptr; 4231 return false; 4232 } 4233 HasValue = true; 4234 } 4235 } 4236 assert(HasValue && "Node to be masked has no data result?"); 4237 } 4238 } 4239 return true; 4240 } 4241 4242 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 4243 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4244 if (!Mask) 4245 return false; 4246 4247 if (!Mask->getAPIntValue().isMask()) 4248 return false; 4249 4250 // No need to do anything if the and directly uses a load. 4251 if (isa<LoadSDNode>(N->getOperand(0))) 4252 return false; 4253 4254 SmallPtrSet<LoadSDNode*, 8> Loads; 4255 SmallPtrSet<SDNode*, 2> NodesWithConsts; 4256 SDNode *FixupNode = nullptr; 4257 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 4258 if (Loads.size() == 0) 4259 return false; 4260 4261 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 4262 SDValue MaskOp = N->getOperand(1); 4263 4264 // If it exists, fixup the single node we allow in the tree that needs 4265 // masking. 4266 if (FixupNode) { 4267 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 4268 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 4269 FixupNode->getValueType(0), 4270 SDValue(FixupNode, 0), MaskOp); 4271 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 4272 if (And.getOpcode() == ISD ::AND) 4273 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 4274 } 4275 4276 // Narrow any constants that need it. 4277 for (auto *LogicN : NodesWithConsts) { 4278 SDValue Op0 = LogicN->getOperand(0); 4279 SDValue Op1 = LogicN->getOperand(1); 4280 4281 if (isa<ConstantSDNode>(Op0)) 4282 std::swap(Op0, Op1); 4283 4284 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 4285 Op1, MaskOp); 4286 4287 DAG.UpdateNodeOperands(LogicN, Op0, And); 4288 } 4289 4290 // Create narrow loads. 4291 for (auto *Load : Loads) { 4292 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 4293 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 4294 SDValue(Load, 0), MaskOp); 4295 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 4296 if (And.getOpcode() == ISD ::AND) 4297 And = SDValue( 4298 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 4299 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 4300 assert(NewLoad && 4301 "Shouldn't be masking the load if it can't be narrowed"); 4302 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 4303 } 4304 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 4305 return true; 4306 } 4307 return false; 4308 } 4309 4310 // Unfold 4311 // x & (-1 'logical shift' y) 4312 // To 4313 // (x 'opposite logical shift' y) 'logical shift' y 4314 // if it is better for performance. 4315 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 4316 assert(N->getOpcode() == ISD::AND); 4317 4318 SDValue N0 = N->getOperand(0); 4319 SDValue N1 = N->getOperand(1); 4320 4321 // Do we actually prefer shifts over mask? 4322 if (!TLI.preferShiftsToClearExtremeBits(N0)) 4323 return SDValue(); 4324 4325 // Try to match (-1 '[outer] logical shift' y) 4326 unsigned OuterShift; 4327 unsigned InnerShift; // The opposite direction to the OuterShift. 4328 SDValue Y; // Shift amount. 4329 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 4330 if (!M.hasOneUse()) 4331 return false; 4332 OuterShift = M->getOpcode(); 4333 if (OuterShift == ISD::SHL) 4334 InnerShift = ISD::SRL; 4335 else if (OuterShift == ISD::SRL) 4336 InnerShift = ISD::SHL; 4337 else 4338 return false; 4339 if (!isAllOnesConstant(M->getOperand(0))) 4340 return false; 4341 Y = M->getOperand(1); 4342 return true; 4343 }; 4344 4345 SDValue X; 4346 if (matchMask(N1)) 4347 X = N0; 4348 else if (matchMask(N0)) 4349 X = N1; 4350 else 4351 return SDValue(); 4352 4353 SDLoc DL(N); 4354 EVT VT = N->getValueType(0); 4355 4356 // tmp = x 'opposite logical shift' y 4357 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 4358 // ret = tmp 'logical shift' y 4359 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 4360 4361 return T1; 4362 } 4363 4364 SDValue DAGCombiner::visitAND(SDNode *N) { 4365 SDValue N0 = N->getOperand(0); 4366 SDValue N1 = N->getOperand(1); 4367 EVT VT = N1.getValueType(); 4368 4369 // x & x --> x 4370 if (N0 == N1) 4371 return N0; 4372 4373 // fold vector ops 4374 if (VT.isVector()) { 4375 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4376 return FoldedVOp; 4377 4378 // fold (and x, 0) -> 0, vector edition 4379 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4380 // do not return N0, because undef node may exist in N0 4381 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 4382 SDLoc(N), N0.getValueType()); 4383 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4384 // do not return N1, because undef node may exist in N1 4385 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 4386 SDLoc(N), N1.getValueType()); 4387 4388 // fold (and x, -1) -> x, vector edition 4389 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4390 return N1; 4391 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4392 return N0; 4393 } 4394 4395 // fold (and c1, c2) -> c1&c2 4396 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4397 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4398 if (N0C && N1C && !N1C->isOpaque()) 4399 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 4400 // canonicalize constant to RHS 4401 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4402 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4403 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 4404 // fold (and x, -1) -> x 4405 if (isAllOnesConstant(N1)) 4406 return N0; 4407 // if (and x, c) is known to be zero, return 0 4408 unsigned BitWidth = VT.getScalarSizeInBits(); 4409 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4410 APInt::getAllOnesValue(BitWidth))) 4411 return DAG.getConstant(0, SDLoc(N), VT); 4412 4413 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4414 return NewSel; 4415 4416 // reassociate and 4417 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 4418 return RAND; 4419 4420 // Try to convert a constant mask AND into a shuffle clear mask. 4421 if (VT.isVector()) 4422 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4423 return Shuffle; 4424 4425 // fold (and (or x, C), D) -> D if (C & D) == D 4426 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4427 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4428 }; 4429 if (N0.getOpcode() == ISD::OR && 4430 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4431 return N1; 4432 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4433 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4434 SDValue N0Op0 = N0.getOperand(0); 4435 APInt Mask = ~N1C->getAPIntValue(); 4436 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4437 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4438 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4439 N0.getValueType(), N0Op0); 4440 4441 // Replace uses of the AND with uses of the Zero extend node. 4442 CombineTo(N, Zext); 4443 4444 // We actually want to replace all uses of the any_extend with the 4445 // zero_extend, to avoid duplicating things. This will later cause this 4446 // AND to be folded. 4447 CombineTo(N0.getNode(), Zext); 4448 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4449 } 4450 } 4451 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4452 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4453 // already be zero by virtue of the width of the base type of the load. 4454 // 4455 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4456 // more cases. 4457 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4458 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4459 N0.getOperand(0).getOpcode() == ISD::LOAD && 4460 N0.getOperand(0).getResNo() == 0) || 4461 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4462 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4463 N0 : N0.getOperand(0) ); 4464 4465 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4466 // This can be a pure constant or a vector splat, in which case we treat the 4467 // vector as a scalar and use the splat value. 4468 APInt Constant = APInt::getNullValue(1); 4469 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4470 Constant = C->getAPIntValue(); 4471 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4472 APInt SplatValue, SplatUndef; 4473 unsigned SplatBitSize; 4474 bool HasAnyUndefs; 4475 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4476 SplatBitSize, HasAnyUndefs); 4477 if (IsSplat) { 4478 // Undef bits can contribute to a possible optimisation if set, so 4479 // set them. 4480 SplatValue |= SplatUndef; 4481 4482 // The splat value may be something like "0x00FFFFFF", which means 0 for 4483 // the first vector value and FF for the rest, repeating. We need a mask 4484 // that will apply equally to all members of the vector, so AND all the 4485 // lanes of the constant together. 4486 EVT VT = Vector->getValueType(0); 4487 unsigned BitWidth = VT.getScalarSizeInBits(); 4488 4489 // If the splat value has been compressed to a bitlength lower 4490 // than the size of the vector lane, we need to re-expand it to 4491 // the lane size. 4492 if (BitWidth > SplatBitSize) 4493 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4494 SplatBitSize < BitWidth; 4495 SplatBitSize = SplatBitSize * 2) 4496 SplatValue |= SplatValue.shl(SplatBitSize); 4497 4498 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4499 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4500 if (SplatBitSize % BitWidth == 0) { 4501 Constant = APInt::getAllOnesValue(BitWidth); 4502 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4503 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4504 } 4505 } 4506 } 4507 4508 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4509 // actually legal and isn't going to get expanded, else this is a false 4510 // optimisation. 4511 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4512 Load->getValueType(0), 4513 Load->getMemoryVT()); 4514 4515 // Resize the constant to the same size as the original memory access before 4516 // extension. If it is still the AllOnesValue then this AND is completely 4517 // unneeded. 4518 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4519 4520 bool B; 4521 switch (Load->getExtensionType()) { 4522 default: B = false; break; 4523 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4524 case ISD::ZEXTLOAD: 4525 case ISD::NON_EXTLOAD: B = true; break; 4526 } 4527 4528 if (B && Constant.isAllOnesValue()) { 4529 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4530 // preserve semantics once we get rid of the AND. 4531 SDValue NewLoad(Load, 0); 4532 4533 // Fold the AND away. NewLoad may get replaced immediately. 4534 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4535 4536 if (Load->getExtensionType() == ISD::EXTLOAD) { 4537 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4538 Load->getValueType(0), SDLoc(Load), 4539 Load->getChain(), Load->getBasePtr(), 4540 Load->getOffset(), Load->getMemoryVT(), 4541 Load->getMemOperand()); 4542 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4543 if (Load->getNumValues() == 3) { 4544 // PRE/POST_INC loads have 3 values. 4545 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4546 NewLoad.getValue(2) }; 4547 CombineTo(Load, To, 3, true); 4548 } else { 4549 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4550 } 4551 } 4552 4553 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4554 } 4555 } 4556 4557 // fold (and (load x), 255) -> (zextload x, i8) 4558 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4559 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4560 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4561 (N0.getOpcode() == ISD::ANY_EXTEND && 4562 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4563 if (SDValue Res = ReduceLoadWidth(N)) { 4564 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4565 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4566 4567 AddToWorklist(N); 4568 CombineTo(LN0, Res, Res.getValue(1)); 4569 return SDValue(N, 0); 4570 } 4571 } 4572 4573 if (Level >= AfterLegalizeTypes) { 4574 // Attempt to propagate the AND back up to the leaves which, if they're 4575 // loads, can be combined to narrow loads and the AND node can be removed. 4576 // Perform after legalization so that extend nodes will already be 4577 // combined into the loads. 4578 if (BackwardsPropagateMask(N, DAG)) { 4579 return SDValue(N, 0); 4580 } 4581 } 4582 4583 if (SDValue Combined = visitANDLike(N0, N1, N)) 4584 return Combined; 4585 4586 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4587 if (N0.getOpcode() == N1.getOpcode()) 4588 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4589 return Tmp; 4590 4591 // Masking the negated extension of a boolean is just the zero-extended 4592 // boolean: 4593 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4594 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4595 // 4596 // Note: the SimplifyDemandedBits fold below can make an information-losing 4597 // transform, and then we have no way to find this better fold. 4598 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4599 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4600 SDValue SubRHS = N0.getOperand(1); 4601 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4602 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4603 return SubRHS; 4604 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4605 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4606 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4607 } 4608 } 4609 4610 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4611 // fold (and (sra)) -> (and (srl)) when possible. 4612 if (SimplifyDemandedBits(SDValue(N, 0))) 4613 return SDValue(N, 0); 4614 4615 // fold (zext_inreg (extload x)) -> (zextload x) 4616 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4617 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4618 EVT MemVT = LN0->getMemoryVT(); 4619 // If we zero all the possible extended bits, then we can turn this into 4620 // a zextload if we are running before legalize or the operation is legal. 4621 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4622 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4623 BitWidth - MemVT.getScalarSizeInBits())) && 4624 ((!LegalOperations && !LN0->isVolatile()) || 4625 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4626 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4627 LN0->getChain(), LN0->getBasePtr(), 4628 MemVT, LN0->getMemOperand()); 4629 AddToWorklist(N); 4630 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4631 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4632 } 4633 } 4634 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4635 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4636 N0.hasOneUse()) { 4637 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4638 EVT MemVT = LN0->getMemoryVT(); 4639 // If we zero all the possible extended bits, then we can turn this into 4640 // a zextload if we are running before legalize or the operation is legal. 4641 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4642 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4643 BitWidth - MemVT.getScalarSizeInBits())) && 4644 ((!LegalOperations && !LN0->isVolatile()) || 4645 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4646 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4647 LN0->getChain(), LN0->getBasePtr(), 4648 MemVT, LN0->getMemOperand()); 4649 AddToWorklist(N); 4650 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4651 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4652 } 4653 } 4654 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4655 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4656 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4657 N0.getOperand(1), false)) 4658 return BSwap; 4659 } 4660 4661 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 4662 return Shifts; 4663 4664 return SDValue(); 4665 } 4666 4667 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4668 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4669 bool DemandHighBits) { 4670 if (!LegalOperations) 4671 return SDValue(); 4672 4673 EVT VT = N->getValueType(0); 4674 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4675 return SDValue(); 4676 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4677 return SDValue(); 4678 4679 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4680 bool LookPassAnd0 = false; 4681 bool LookPassAnd1 = false; 4682 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4683 std::swap(N0, N1); 4684 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4685 std::swap(N0, N1); 4686 if (N0.getOpcode() == ISD::AND) { 4687 if (!N0.getNode()->hasOneUse()) 4688 return SDValue(); 4689 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4690 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 4691 // This is needed for X86. 4692 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 4693 N01C->getZExtValue() != 0xFFFF)) 4694 return SDValue(); 4695 N0 = N0.getOperand(0); 4696 LookPassAnd0 = true; 4697 } 4698 4699 if (N1.getOpcode() == ISD::AND) { 4700 if (!N1.getNode()->hasOneUse()) 4701 return SDValue(); 4702 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4703 if (!N11C || N11C->getZExtValue() != 0xFF) 4704 return SDValue(); 4705 N1 = N1.getOperand(0); 4706 LookPassAnd1 = true; 4707 } 4708 4709 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4710 std::swap(N0, N1); 4711 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4712 return SDValue(); 4713 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4714 return SDValue(); 4715 4716 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4717 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4718 if (!N01C || !N11C) 4719 return SDValue(); 4720 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4721 return SDValue(); 4722 4723 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4724 SDValue N00 = N0->getOperand(0); 4725 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4726 if (!N00.getNode()->hasOneUse()) 4727 return SDValue(); 4728 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4729 if (!N001C || N001C->getZExtValue() != 0xFF) 4730 return SDValue(); 4731 N00 = N00.getOperand(0); 4732 LookPassAnd0 = true; 4733 } 4734 4735 SDValue N10 = N1->getOperand(0); 4736 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4737 if (!N10.getNode()->hasOneUse()) 4738 return SDValue(); 4739 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4740 // Also allow 0xFFFF since the bits will be shifted out. This is needed 4741 // for X86. 4742 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 4743 N101C->getZExtValue() != 0xFFFF)) 4744 return SDValue(); 4745 N10 = N10.getOperand(0); 4746 LookPassAnd1 = true; 4747 } 4748 4749 if (N00 != N10) 4750 return SDValue(); 4751 4752 // Make sure everything beyond the low halfword gets set to zero since the SRL 4753 // 16 will clear the top bits. 4754 unsigned OpSizeInBits = VT.getSizeInBits(); 4755 if (DemandHighBits && OpSizeInBits > 16) { 4756 // If the left-shift isn't masked out then the only way this is a bswap is 4757 // if all bits beyond the low 8 are 0. In that case the entire pattern 4758 // reduces to a left shift anyway: leave it for other parts of the combiner. 4759 if (!LookPassAnd0) 4760 return SDValue(); 4761 4762 // However, if the right shift isn't masked out then it might be because 4763 // it's not needed. See if we can spot that too. 4764 if (!LookPassAnd1 && 4765 !DAG.MaskedValueIsZero( 4766 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4767 return SDValue(); 4768 } 4769 4770 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4771 if (OpSizeInBits > 16) { 4772 SDLoc DL(N); 4773 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4774 DAG.getConstant(OpSizeInBits - 16, DL, 4775 getShiftAmountTy(VT))); 4776 } 4777 return Res; 4778 } 4779 4780 /// Return true if the specified node is an element that makes up a 32-bit 4781 /// packed halfword byteswap. 4782 /// ((x & 0x000000ff) << 8) | 4783 /// ((x & 0x0000ff00) >> 8) | 4784 /// ((x & 0x00ff0000) << 8) | 4785 /// ((x & 0xff000000) >> 8) 4786 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4787 if (!N.getNode()->hasOneUse()) 4788 return false; 4789 4790 unsigned Opc = N.getOpcode(); 4791 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4792 return false; 4793 4794 SDValue N0 = N.getOperand(0); 4795 unsigned Opc0 = N0.getOpcode(); 4796 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4797 return false; 4798 4799 ConstantSDNode *N1C = nullptr; 4800 // SHL or SRL: look upstream for AND mask operand 4801 if (Opc == ISD::AND) 4802 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4803 else if (Opc0 == ISD::AND) 4804 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4805 if (!N1C) 4806 return false; 4807 4808 unsigned MaskByteOffset; 4809 switch (N1C->getZExtValue()) { 4810 default: 4811 return false; 4812 case 0xFF: MaskByteOffset = 0; break; 4813 case 0xFF00: MaskByteOffset = 1; break; 4814 case 0xFFFF: 4815 // In case demanded bits didn't clear the bits that will be shifted out. 4816 // This is needed for X86. 4817 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 4818 MaskByteOffset = 1; 4819 break; 4820 } 4821 return false; 4822 case 0xFF0000: MaskByteOffset = 2; break; 4823 case 0xFF000000: MaskByteOffset = 3; break; 4824 } 4825 4826 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4827 if (Opc == ISD::AND) { 4828 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4829 // (x >> 8) & 0xff 4830 // (x >> 8) & 0xff0000 4831 if (Opc0 != ISD::SRL) 4832 return false; 4833 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4834 if (!C || C->getZExtValue() != 8) 4835 return false; 4836 } else { 4837 // (x << 8) & 0xff00 4838 // (x << 8) & 0xff000000 4839 if (Opc0 != ISD::SHL) 4840 return false; 4841 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4842 if (!C || C->getZExtValue() != 8) 4843 return false; 4844 } 4845 } else if (Opc == ISD::SHL) { 4846 // (x & 0xff) << 8 4847 // (x & 0xff0000) << 8 4848 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4849 return false; 4850 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4851 if (!C || C->getZExtValue() != 8) 4852 return false; 4853 } else { // Opc == ISD::SRL 4854 // (x & 0xff00) >> 8 4855 // (x & 0xff000000) >> 8 4856 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4857 return false; 4858 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4859 if (!C || C->getZExtValue() != 8) 4860 return false; 4861 } 4862 4863 if (Parts[MaskByteOffset]) 4864 return false; 4865 4866 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4867 return true; 4868 } 4869 4870 /// Match a 32-bit packed halfword bswap. That is 4871 /// ((x & 0x000000ff) << 8) | 4872 /// ((x & 0x0000ff00) >> 8) | 4873 /// ((x & 0x00ff0000) << 8) | 4874 /// ((x & 0xff000000) >> 8) 4875 /// => (rotl (bswap x), 16) 4876 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4877 if (!LegalOperations) 4878 return SDValue(); 4879 4880 EVT VT = N->getValueType(0); 4881 if (VT != MVT::i32) 4882 return SDValue(); 4883 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4884 return SDValue(); 4885 4886 // Look for either 4887 // (or (or (and), (and)), (or (and), (and))) 4888 // (or (or (or (and), (and)), (and)), (and)) 4889 if (N0.getOpcode() != ISD::OR) 4890 return SDValue(); 4891 SDValue N00 = N0.getOperand(0); 4892 SDValue N01 = N0.getOperand(1); 4893 SDNode *Parts[4] = {}; 4894 4895 if (N1.getOpcode() == ISD::OR && 4896 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4897 // (or (or (and), (and)), (or (and), (and))) 4898 if (!isBSwapHWordElement(N00, Parts)) 4899 return SDValue(); 4900 4901 if (!isBSwapHWordElement(N01, Parts)) 4902 return SDValue(); 4903 SDValue N10 = N1.getOperand(0); 4904 if (!isBSwapHWordElement(N10, Parts)) 4905 return SDValue(); 4906 SDValue N11 = N1.getOperand(1); 4907 if (!isBSwapHWordElement(N11, Parts)) 4908 return SDValue(); 4909 } else { 4910 // (or (or (or (and), (and)), (and)), (and)) 4911 if (!isBSwapHWordElement(N1, Parts)) 4912 return SDValue(); 4913 if (!isBSwapHWordElement(N01, Parts)) 4914 return SDValue(); 4915 if (N00.getOpcode() != ISD::OR) 4916 return SDValue(); 4917 SDValue N000 = N00.getOperand(0); 4918 if (!isBSwapHWordElement(N000, Parts)) 4919 return SDValue(); 4920 SDValue N001 = N00.getOperand(1); 4921 if (!isBSwapHWordElement(N001, Parts)) 4922 return SDValue(); 4923 } 4924 4925 // Make sure the parts are all coming from the same node. 4926 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4927 return SDValue(); 4928 4929 SDLoc DL(N); 4930 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4931 SDValue(Parts[0], 0)); 4932 4933 // Result of the bswap should be rotated by 16. If it's not legal, then 4934 // do (x << 16) | (x >> 16). 4935 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4936 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4937 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4938 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4939 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4940 return DAG.getNode(ISD::OR, DL, VT, 4941 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4942 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4943 } 4944 4945 /// This contains all DAGCombine rules which reduce two values combined by 4946 /// an Or operation to a single value \see visitANDLike(). 4947 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4948 EVT VT = N1.getValueType(); 4949 SDLoc DL(N); 4950 4951 // fold (or x, undef) -> -1 4952 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4953 return DAG.getAllOnesConstant(DL, VT); 4954 4955 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4956 return V; 4957 4958 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4959 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4960 // Don't increase # computations. 4961 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4962 // We can only do this xform if we know that bits from X that are set in C2 4963 // but not in C1 are already zero. Likewise for Y. 4964 if (const ConstantSDNode *N0O1C = 4965 getAsNonOpaqueConstant(N0.getOperand(1))) { 4966 if (const ConstantSDNode *N1O1C = 4967 getAsNonOpaqueConstant(N1.getOperand(1))) { 4968 // We can only do this xform if we know that bits from X that are set in 4969 // C2 but not in C1 are already zero. Likewise for Y. 4970 const APInt &LHSMask = N0O1C->getAPIntValue(); 4971 const APInt &RHSMask = N1O1C->getAPIntValue(); 4972 4973 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4974 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4975 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4976 N0.getOperand(0), N1.getOperand(0)); 4977 return DAG.getNode(ISD::AND, DL, VT, X, 4978 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4979 } 4980 } 4981 } 4982 } 4983 4984 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4985 if (N0.getOpcode() == ISD::AND && 4986 N1.getOpcode() == ISD::AND && 4987 N0.getOperand(0) == N1.getOperand(0) && 4988 // Don't increase # computations. 4989 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4990 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4991 N0.getOperand(1), N1.getOperand(1)); 4992 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4993 } 4994 4995 return SDValue(); 4996 } 4997 4998 SDValue DAGCombiner::visitOR(SDNode *N) { 4999 SDValue N0 = N->getOperand(0); 5000 SDValue N1 = N->getOperand(1); 5001 EVT VT = N1.getValueType(); 5002 5003 // x | x --> x 5004 if (N0 == N1) 5005 return N0; 5006 5007 // fold vector ops 5008 if (VT.isVector()) { 5009 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5010 return FoldedVOp; 5011 5012 // fold (or x, 0) -> x, vector edition 5013 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5014 return N1; 5015 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5016 return N0; 5017 5018 // fold (or x, -1) -> -1, vector edition 5019 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5020 // do not return N0, because undef node may exist in N0 5021 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 5022 if (ISD::isBuildVectorAllOnes(N1.getNode())) 5023 // do not return N1, because undef node may exist in N1 5024 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 5025 5026 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 5027 // Do this only if the resulting shuffle is legal. 5028 if (isa<ShuffleVectorSDNode>(N0) && 5029 isa<ShuffleVectorSDNode>(N1) && 5030 // Avoid folding a node with illegal type. 5031 TLI.isTypeLegal(VT)) { 5032 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 5033 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 5034 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5035 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 5036 // Ensure both shuffles have a zero input. 5037 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 5038 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 5039 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 5040 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 5041 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 5042 bool CanFold = true; 5043 int NumElts = VT.getVectorNumElements(); 5044 SmallVector<int, 4> Mask(NumElts); 5045 5046 for (int i = 0; i != NumElts; ++i) { 5047 int M0 = SV0->getMaskElt(i); 5048 int M1 = SV1->getMaskElt(i); 5049 5050 // Determine if either index is pointing to a zero vector. 5051 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 5052 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 5053 5054 // If one element is zero and the otherside is undef, keep undef. 5055 // This also handles the case that both are undef. 5056 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 5057 Mask[i] = -1; 5058 continue; 5059 } 5060 5061 // Make sure only one of the elements is zero. 5062 if (M0Zero == M1Zero) { 5063 CanFold = false; 5064 break; 5065 } 5066 5067 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 5068 5069 // We have a zero and non-zero element. If the non-zero came from 5070 // SV0 make the index a LHS index. If it came from SV1, make it 5071 // a RHS index. We need to mod by NumElts because we don't care 5072 // which operand it came from in the original shuffles. 5073 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 5074 } 5075 5076 if (CanFold) { 5077 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 5078 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 5079 5080 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5081 if (!LegalMask) { 5082 std::swap(NewLHS, NewRHS); 5083 ShuffleVectorSDNode::commuteMask(Mask); 5084 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5085 } 5086 5087 if (LegalMask) 5088 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 5089 } 5090 } 5091 } 5092 } 5093 5094 // fold (or c1, c2) -> c1|c2 5095 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5097 if (N0C && N1C && !N1C->isOpaque()) 5098 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 5099 // canonicalize constant to RHS 5100 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5101 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5102 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 5103 // fold (or x, 0) -> x 5104 if (isNullConstant(N1)) 5105 return N0; 5106 // fold (or x, -1) -> -1 5107 if (isAllOnesConstant(N1)) 5108 return N1; 5109 5110 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5111 return NewSel; 5112 5113 // fold (or x, c) -> c iff (x & ~c) == 0 5114 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 5115 return N1; 5116 5117 if (SDValue Combined = visitORLike(N0, N1, N)) 5118 return Combined; 5119 5120 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 5121 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 5122 return BSwap; 5123 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 5124 return BSwap; 5125 5126 // reassociate or 5127 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 5128 return ROR; 5129 5130 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 5131 // iff (c1 & c2) != 0. 5132 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 5133 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 5134 }; 5135 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5136 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 5137 if (SDValue COR = DAG.FoldConstantArithmetic( 5138 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 5139 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 5140 AddToWorklist(IOR.getNode()); 5141 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 5142 } 5143 } 5144 5145 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 5146 if (N0.getOpcode() == N1.getOpcode()) 5147 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5148 return Tmp; 5149 5150 // See if this is some rotate idiom. 5151 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 5152 return SDValue(Rot, 0); 5153 5154 if (SDValue Load = MatchLoadCombine(N)) 5155 return Load; 5156 5157 // Simplify the operands using demanded-bits information. 5158 if (SimplifyDemandedBits(SDValue(N, 0))) 5159 return SDValue(N, 0); 5160 5161 return SDValue(); 5162 } 5163 5164 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 5165 if (Op.getOpcode() == ISD::AND && 5166 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 5167 Mask = Op.getOperand(1); 5168 return Op.getOperand(0); 5169 } 5170 return Op; 5171 } 5172 5173 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 5174 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 5175 SDValue &Mask) { 5176 Op = stripConstantMask(DAG, Op, Mask); 5177 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 5178 Shift = Op; 5179 return true; 5180 } 5181 return false; 5182 } 5183 5184 /// Helper function for visitOR to extract the needed side of a rotate idiom 5185 /// from a shl/srl/mul/udiv. This is meant to handle cases where 5186 /// InstCombine merged some outside op with one of the shifts from 5187 /// the rotate pattern. 5188 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 5189 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 5190 /// patterns: 5191 /// 5192 /// (or (mul v c0) (shrl (mul v c1) c2)): 5193 /// expands (mul v c0) -> (shl (mul v c1) c3) 5194 /// 5195 /// (or (udiv v c0) (shl (udiv v c1) c2)): 5196 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 5197 /// 5198 /// (or (shl v c0) (shrl (shl v c1) c2)): 5199 /// expands (shl v c0) -> (shl (shl v c1) c3) 5200 /// 5201 /// (or (shrl v c0) (shl (shrl v c1) c2)): 5202 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 5203 /// 5204 /// Such that in all cases, c3+c2==bitwidth(op v c1). 5205 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 5206 SDValue ExtractFrom, SDValue &Mask, 5207 const SDLoc &DL) { 5208 assert(OppShift && ExtractFrom && "Empty SDValue"); 5209 assert( 5210 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 5211 "Existing shift must be valid as a rotate half"); 5212 5213 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 5214 // Preconditions: 5215 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 5216 // 5217 // Find opcode of the needed shift to be extracted from (op0 v c0). 5218 unsigned Opcode = ISD::DELETED_NODE; 5219 bool IsMulOrDiv = false; 5220 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 5221 // opcode or its arithmetic (mul or udiv) variant. 5222 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 5223 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 5224 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 5225 return false; 5226 Opcode = NeededShift; 5227 return true; 5228 }; 5229 // op0 must be either the needed shift opcode or the mul/udiv equivalent 5230 // that the needed shift can be extracted from. 5231 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 5232 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 5233 return SDValue(); 5234 5235 // op0 must be the same opcode on both sides, have the same LHS argument, 5236 // and produce the same value type. 5237 SDValue OppShiftLHS = OppShift.getOperand(0); 5238 EVT ShiftedVT = OppShiftLHS.getValueType(); 5239 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 5240 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 5241 ShiftedVT != ExtractFrom.getValueType()) 5242 return SDValue(); 5243 5244 // Amount of the existing shift. 5245 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 5246 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 5247 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 5248 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 5249 ConstantSDNode *ExtractFromCst = 5250 isConstOrConstSplat(ExtractFrom.getOperand(1)); 5251 // TODO: We should be able to handle non-uniform constant vectors for these values 5252 // Check that we have constant values. 5253 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 5254 !OppLHSCst || !OppLHSCst->getAPIntValue() || 5255 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 5256 return SDValue(); 5257 5258 // Compute the shift amount we need to extract to complete the rotate. 5259 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 5260 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 5261 if (NeededShiftAmt.isNegative()) 5262 return SDValue(); 5263 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 5264 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 5265 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 5266 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 5267 5268 // Now try extract the needed shift from the ExtractFrom op and see if the 5269 // result matches up with the existing shift's LHS op. 5270 if (IsMulOrDiv) { 5271 // Op to extract from is a mul or udiv by a constant. 5272 // Check: 5273 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 5274 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 5275 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 5276 NeededShiftAmt.getZExtValue()); 5277 APInt ResultAmt; 5278 APInt Rem; 5279 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 5280 if (Rem != 0 || ResultAmt != OppLHSAmt) 5281 return SDValue(); 5282 } else { 5283 // Op to extract from is a shift by a constant. 5284 // Check: 5285 // c2 - (bitwidth(op0 v c0) - c1) == c0 5286 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 5287 ExtractFromAmt.getBitWidth())) 5288 return SDValue(); 5289 } 5290 5291 // Return the expanded shift op that should allow a rotate to be formed. 5292 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 5293 EVT ResVT = ExtractFrom.getValueType(); 5294 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 5295 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 5296 } 5297 5298 // Return true if we can prove that, whenever Neg and Pos are both in the 5299 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 5300 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 5301 // 5302 // (or (shift1 X, Neg), (shift2 X, Pos)) 5303 // 5304 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 5305 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 5306 // to consider shift amounts with defined behavior. 5307 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 5308 SelectionDAG &DAG) { 5309 // If EltSize is a power of 2 then: 5310 // 5311 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 5312 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 5313 // 5314 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 5315 // for the stronger condition: 5316 // 5317 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 5318 // 5319 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 5320 // we can just replace Neg with Neg' for the rest of the function. 5321 // 5322 // In other cases we check for the even stronger condition: 5323 // 5324 // Neg == EltSize - Pos [B] 5325 // 5326 // for all Neg and Pos. Note that the (or ...) then invokes undefined 5327 // behavior if Pos == 0 (and consequently Neg == EltSize). 5328 // 5329 // We could actually use [A] whenever EltSize is a power of 2, but the 5330 // only extra cases that it would match are those uninteresting ones 5331 // where Neg and Pos are never in range at the same time. E.g. for 5332 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 5333 // as well as (sub 32, Pos), but: 5334 // 5335 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 5336 // 5337 // always invokes undefined behavior for 32-bit X. 5338 // 5339 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 5340 unsigned MaskLoBits = 0; 5341 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 5342 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 5343 KnownBits Known; 5344 DAG.computeKnownBits(Neg.getOperand(0), Known); 5345 unsigned Bits = Log2_64(EltSize); 5346 if (NegC->getAPIntValue().getActiveBits() <= Bits && 5347 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 5348 Neg = Neg.getOperand(0); 5349 MaskLoBits = Bits; 5350 } 5351 } 5352 } 5353 5354 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 5355 if (Neg.getOpcode() != ISD::SUB) 5356 return false; 5357 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 5358 if (!NegC) 5359 return false; 5360 SDValue NegOp1 = Neg.getOperand(1); 5361 5362 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 5363 // Pos'. The truncation is redundant for the purpose of the equality. 5364 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 5365 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 5366 KnownBits Known; 5367 DAG.computeKnownBits(Pos.getOperand(0), Known); 5368 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 5369 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 5370 MaskLoBits)) 5371 Pos = Pos.getOperand(0); 5372 } 5373 } 5374 5375 // The condition we need is now: 5376 // 5377 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 5378 // 5379 // If NegOp1 == Pos then we need: 5380 // 5381 // EltSize & Mask == NegC & Mask 5382 // 5383 // (because "x & Mask" is a truncation and distributes through subtraction). 5384 APInt Width; 5385 if (Pos == NegOp1) 5386 Width = NegC->getAPIntValue(); 5387 5388 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 5389 // Then the condition we want to prove becomes: 5390 // 5391 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 5392 // 5393 // which, again because "x & Mask" is a truncation, becomes: 5394 // 5395 // NegC & Mask == (EltSize - PosC) & Mask 5396 // EltSize & Mask == (NegC + PosC) & Mask 5397 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 5398 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 5399 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 5400 else 5401 return false; 5402 } else 5403 return false; 5404 5405 // Now we just need to check that EltSize & Mask == Width & Mask. 5406 if (MaskLoBits) 5407 // EltSize & Mask is 0 since Mask is EltSize - 1. 5408 return Width.getLoBits(MaskLoBits) == 0; 5409 return Width == EltSize; 5410 } 5411 5412 // A subroutine of MatchRotate used once we have found an OR of two opposite 5413 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 5414 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 5415 // former being preferred if supported. InnerPos and InnerNeg are Pos and 5416 // Neg with outer conversions stripped away. 5417 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 5418 SDValue Neg, SDValue InnerPos, 5419 SDValue InnerNeg, unsigned PosOpcode, 5420 unsigned NegOpcode, const SDLoc &DL) { 5421 // fold (or (shl x, (*ext y)), 5422 // (srl x, (*ext (sub 32, y)))) -> 5423 // (rotl x, y) or (rotr x, (sub 32, y)) 5424 // 5425 // fold (or (shl x, (*ext (sub 32, y))), 5426 // (srl x, (*ext y))) -> 5427 // (rotr x, y) or (rotl x, (sub 32, y)) 5428 EVT VT = Shifted.getValueType(); 5429 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) { 5430 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 5431 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 5432 HasPos ? Pos : Neg).getNode(); 5433 } 5434 5435 return nullptr; 5436 } 5437 5438 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 5439 // idioms for rotate, and if the target supports rotation instructions, generate 5440 // a rot[lr]. 5441 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 5442 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 5443 EVT VT = LHS.getValueType(); 5444 if (!TLI.isTypeLegal(VT)) return nullptr; 5445 5446 // The target must have at least one rotate flavor. 5447 bool HasROTL = hasOperation(ISD::ROTL, VT); 5448 bool HasROTR = hasOperation(ISD::ROTR, VT); 5449 if (!HasROTL && !HasROTR) return nullptr; 5450 5451 // Check for truncated rotate. 5452 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 5453 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 5454 assert(LHS.getValueType() == RHS.getValueType()); 5455 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 5456 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 5457 SDValue(Rot, 0)).getNode(); 5458 } 5459 } 5460 5461 // Match "(X shl/srl V1) & V2" where V2 may not be present. 5462 SDValue LHSShift; // The shift. 5463 SDValue LHSMask; // AND value if any. 5464 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 5465 5466 SDValue RHSShift; // The shift. 5467 SDValue RHSMask; // AND value if any. 5468 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 5469 5470 // If neither side matched a rotate half, bail 5471 if (!LHSShift && !RHSShift) 5472 return nullptr; 5473 5474 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 5475 // side of the rotate, so try to handle that here. In all cases we need to 5476 // pass the matched shift from the opposite side to compute the opcode and 5477 // needed shift amount to extract. We still want to do this if both sides 5478 // matched a rotate half because one half may be a potential overshift that 5479 // can be broken down (ie if InstCombine merged two shl or srl ops into a 5480 // single one). 5481 5482 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 5483 if (LHSShift) 5484 if (SDValue NewRHSShift = 5485 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 5486 RHSShift = NewRHSShift; 5487 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 5488 if (RHSShift) 5489 if (SDValue NewLHSShift = 5490 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 5491 LHSShift = NewLHSShift; 5492 5493 // If a side is still missing, nothing else we can do. 5494 if (!RHSShift || !LHSShift) 5495 return nullptr; 5496 5497 // At this point we've matched or extracted a shift op on each side. 5498 5499 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 5500 return nullptr; // Not shifting the same value. 5501 5502 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 5503 return nullptr; // Shifts must disagree. 5504 5505 // Canonicalize shl to left side in a shl/srl pair. 5506 if (RHSShift.getOpcode() == ISD::SHL) { 5507 std::swap(LHS, RHS); 5508 std::swap(LHSShift, RHSShift); 5509 std::swap(LHSMask, RHSMask); 5510 } 5511 5512 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5513 SDValue LHSShiftArg = LHSShift.getOperand(0); 5514 SDValue LHSShiftAmt = LHSShift.getOperand(1); 5515 SDValue RHSShiftArg = RHSShift.getOperand(0); 5516 SDValue RHSShiftAmt = RHSShift.getOperand(1); 5517 5518 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 5519 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 5520 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 5521 ConstantSDNode *RHS) { 5522 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 5523 }; 5524 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 5525 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 5526 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 5527 5528 // If there is an AND of either shifted operand, apply it to the result. 5529 if (LHSMask.getNode() || RHSMask.getNode()) { 5530 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 5531 SDValue Mask = AllOnes; 5532 5533 if (LHSMask.getNode()) { 5534 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 5535 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5536 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 5537 } 5538 if (RHSMask.getNode()) { 5539 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 5540 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5541 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 5542 } 5543 5544 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 5545 } 5546 5547 return Rot.getNode(); 5548 } 5549 5550 // If there is a mask here, and we have a variable shift, we can't be sure 5551 // that we're masking out the right stuff. 5552 if (LHSMask.getNode() || RHSMask.getNode()) 5553 return nullptr; 5554 5555 // If the shift amount is sign/zext/any-extended just peel it off. 5556 SDValue LExtOp0 = LHSShiftAmt; 5557 SDValue RExtOp0 = RHSShiftAmt; 5558 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5559 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5560 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5561 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 5562 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5563 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5564 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5565 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 5566 LExtOp0 = LHSShiftAmt.getOperand(0); 5567 RExtOp0 = RHSShiftAmt.getOperand(0); 5568 } 5569 5570 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 5571 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 5572 if (TryL) 5573 return TryL; 5574 5575 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 5576 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 5577 if (TryR) 5578 return TryR; 5579 5580 return nullptr; 5581 } 5582 5583 namespace { 5584 5585 /// Represents known origin of an individual byte in load combine pattern. The 5586 /// value of the byte is either constant zero or comes from memory. 5587 struct ByteProvider { 5588 // For constant zero providers Load is set to nullptr. For memory providers 5589 // Load represents the node which loads the byte from memory. 5590 // ByteOffset is the offset of the byte in the value produced by the load. 5591 LoadSDNode *Load = nullptr; 5592 unsigned ByteOffset = 0; 5593 5594 ByteProvider() = default; 5595 5596 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5597 return ByteProvider(Load, ByteOffset); 5598 } 5599 5600 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5601 5602 bool isConstantZero() const { return !Load; } 5603 bool isMemory() const { return Load; } 5604 5605 bool operator==(const ByteProvider &Other) const { 5606 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5607 } 5608 5609 private: 5610 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5611 : Load(Load), ByteOffset(ByteOffset) {} 5612 }; 5613 5614 } // end anonymous namespace 5615 5616 /// Recursively traverses the expression calculating the origin of the requested 5617 /// byte of the given value. Returns None if the provider can't be calculated. 5618 /// 5619 /// For all the values except the root of the expression verifies that the value 5620 /// has exactly one use and if it's not true return None. This way if the origin 5621 /// of the byte is returned it's guaranteed that the values which contribute to 5622 /// the byte are not used outside of this expression. 5623 /// 5624 /// Because the parts of the expression are not allowed to have more than one 5625 /// use this function iterates over trees, not DAGs. So it never visits the same 5626 /// node more than once. 5627 static const Optional<ByteProvider> 5628 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5629 bool Root = false) { 5630 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5631 if (Depth == 10) 5632 return None; 5633 5634 if (!Root && !Op.hasOneUse()) 5635 return None; 5636 5637 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5638 unsigned BitWidth = Op.getValueSizeInBits(); 5639 if (BitWidth % 8 != 0) 5640 return None; 5641 unsigned ByteWidth = BitWidth / 8; 5642 assert(Index < ByteWidth && "invalid index requested"); 5643 (void) ByteWidth; 5644 5645 switch (Op.getOpcode()) { 5646 case ISD::OR: { 5647 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5648 if (!LHS) 5649 return None; 5650 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5651 if (!RHS) 5652 return None; 5653 5654 if (LHS->isConstantZero()) 5655 return RHS; 5656 if (RHS->isConstantZero()) 5657 return LHS; 5658 return None; 5659 } 5660 case ISD::SHL: { 5661 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5662 if (!ShiftOp) 5663 return None; 5664 5665 uint64_t BitShift = ShiftOp->getZExtValue(); 5666 if (BitShift % 8 != 0) 5667 return None; 5668 uint64_t ByteShift = BitShift / 8; 5669 5670 return Index < ByteShift 5671 ? ByteProvider::getConstantZero() 5672 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5673 Depth + 1); 5674 } 5675 case ISD::ANY_EXTEND: 5676 case ISD::SIGN_EXTEND: 5677 case ISD::ZERO_EXTEND: { 5678 SDValue NarrowOp = Op->getOperand(0); 5679 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5680 if (NarrowBitWidth % 8 != 0) 5681 return None; 5682 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5683 5684 if (Index >= NarrowByteWidth) 5685 return Op.getOpcode() == ISD::ZERO_EXTEND 5686 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5687 : None; 5688 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5689 } 5690 case ISD::BSWAP: 5691 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5692 Depth + 1); 5693 case ISD::LOAD: { 5694 auto L = cast<LoadSDNode>(Op.getNode()); 5695 if (L->isVolatile() || L->isIndexed()) 5696 return None; 5697 5698 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5699 if (NarrowBitWidth % 8 != 0) 5700 return None; 5701 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5702 5703 if (Index >= NarrowByteWidth) 5704 return L->getExtensionType() == ISD::ZEXTLOAD 5705 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5706 : None; 5707 return ByteProvider::getMemory(L, Index); 5708 } 5709 } 5710 5711 return None; 5712 } 5713 5714 /// Match a pattern where a wide type scalar value is loaded by several narrow 5715 /// loads and combined by shifts and ors. Fold it into a single load or a load 5716 /// and a BSWAP if the targets supports it. 5717 /// 5718 /// Assuming little endian target: 5719 /// i8 *a = ... 5720 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5721 /// => 5722 /// i32 val = *((i32)a) 5723 /// 5724 /// i8 *a = ... 5725 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5726 /// => 5727 /// i32 val = BSWAP(*((i32)a)) 5728 /// 5729 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5730 /// interact well with the worklist mechanism. When a part of the pattern is 5731 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5732 /// but the root node of the pattern which triggers the load combine is not 5733 /// necessarily a direct user of the changed node. For example, once the address 5734 /// of t28 load is reassociated load combine won't be triggered: 5735 /// t25: i32 = add t4, Constant:i32<2> 5736 /// t26: i64 = sign_extend t25 5737 /// t27: i64 = add t2, t26 5738 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5739 /// t29: i32 = zero_extend t28 5740 /// t32: i32 = shl t29, Constant:i8<8> 5741 /// t33: i32 = or t23, t32 5742 /// As a possible fix visitLoad can check if the load can be a part of a load 5743 /// combine pattern and add corresponding OR roots to the worklist. 5744 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5745 assert(N->getOpcode() == ISD::OR && 5746 "Can only match load combining against OR nodes"); 5747 5748 // Handles simple types only 5749 EVT VT = N->getValueType(0); 5750 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5751 return SDValue(); 5752 unsigned ByteWidth = VT.getSizeInBits() / 8; 5753 5754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5755 // Before legalize we can introduce too wide illegal loads which will be later 5756 // split into legal sized loads. This enables us to combine i64 load by i8 5757 // patterns to a couple of i32 loads on 32 bit targets. 5758 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5759 return SDValue(); 5760 5761 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5762 unsigned BW, unsigned i) { return i; }; 5763 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5764 unsigned BW, unsigned i) { return BW - i - 1; }; 5765 5766 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5767 auto MemoryByteOffset = [&] (ByteProvider P) { 5768 assert(P.isMemory() && "Must be a memory byte provider"); 5769 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5770 assert(LoadBitWidth % 8 == 0 && 5771 "can only analyze providers for individual bytes not bit"); 5772 unsigned LoadByteWidth = LoadBitWidth / 8; 5773 return IsBigEndianTarget 5774 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5775 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5776 }; 5777 5778 Optional<BaseIndexOffset> Base; 5779 SDValue Chain; 5780 5781 SmallPtrSet<LoadSDNode *, 8> Loads; 5782 Optional<ByteProvider> FirstByteProvider; 5783 int64_t FirstOffset = INT64_MAX; 5784 5785 // Check if all the bytes of the OR we are looking at are loaded from the same 5786 // base address. Collect bytes offsets from Base address in ByteOffsets. 5787 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5788 for (unsigned i = 0; i < ByteWidth; i++) { 5789 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5790 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5791 return SDValue(); 5792 5793 LoadSDNode *L = P->Load; 5794 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5795 "Must be enforced by calculateByteProvider"); 5796 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5797 5798 // All loads must share the same chain 5799 SDValue LChain = L->getChain(); 5800 if (!Chain) 5801 Chain = LChain; 5802 else if (Chain != LChain) 5803 return SDValue(); 5804 5805 // Loads must share the same base address 5806 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 5807 int64_t ByteOffsetFromBase = 0; 5808 if (!Base) 5809 Base = Ptr; 5810 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5811 return SDValue(); 5812 5813 // Calculate the offset of the current byte from the base address 5814 ByteOffsetFromBase += MemoryByteOffset(*P); 5815 ByteOffsets[i] = ByteOffsetFromBase; 5816 5817 // Remember the first byte load 5818 if (ByteOffsetFromBase < FirstOffset) { 5819 FirstByteProvider = P; 5820 FirstOffset = ByteOffsetFromBase; 5821 } 5822 5823 Loads.insert(L); 5824 } 5825 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5826 "memory, so there must be at least one load which produces the value"); 5827 assert(Base && "Base address of the accessed memory location must be set"); 5828 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5829 5830 // Check if the bytes of the OR we are looking at match with either big or 5831 // little endian value load 5832 bool BigEndian = true, LittleEndian = true; 5833 for (unsigned i = 0; i < ByteWidth; i++) { 5834 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5835 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5836 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5837 if (!BigEndian && !LittleEndian) 5838 return SDValue(); 5839 } 5840 assert((BigEndian != LittleEndian) && "should be either or"); 5841 assert(FirstByteProvider && "must be set"); 5842 5843 // Ensure that the first byte is loaded from zero offset of the first load. 5844 // So the combined value can be loaded from the first load address. 5845 if (MemoryByteOffset(*FirstByteProvider) != 0) 5846 return SDValue(); 5847 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5848 5849 // The node we are looking at matches with the pattern, check if we can 5850 // replace it with a single load and bswap if needed. 5851 5852 // If the load needs byte swap check if the target supports it 5853 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5854 5855 // Before legalize we can introduce illegal bswaps which will be later 5856 // converted to an explicit bswap sequence. This way we end up with a single 5857 // load and byte shuffling instead of several loads and byte shuffling. 5858 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5859 return SDValue(); 5860 5861 // Check that a load of the wide type is both allowed and fast on the target 5862 bool Fast = false; 5863 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5864 VT, FirstLoad->getAddressSpace(), 5865 FirstLoad->getAlignment(), &Fast); 5866 if (!Allowed || !Fast) 5867 return SDValue(); 5868 5869 SDValue NewLoad = 5870 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5871 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5872 5873 // Transfer chain users from old loads to the new load. 5874 for (LoadSDNode *L : Loads) 5875 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5876 5877 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5878 } 5879 5880 // If the target has andn, bsl, or a similar bit-select instruction, 5881 // we want to unfold masked merge, with canonical pattern of: 5882 // | A | |B| 5883 // ((x ^ y) & m) ^ y 5884 // | D | 5885 // Into: 5886 // (x & m) | (y & ~m) 5887 // If y is a constant, and the 'andn' does not work with immediates, 5888 // we unfold into a different pattern: 5889 // ~(~x & m) & (m | y) 5890 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 5891 // the very least that breaks andnpd / andnps patterns, and because those 5892 // patterns are simplified in IR and shouldn't be created in the DAG 5893 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 5894 assert(N->getOpcode() == ISD::XOR); 5895 5896 // Don't touch 'not' (i.e. where y = -1). 5897 if (isAllOnesConstantOrAllOnesSplatConstant(N->getOperand(1))) 5898 return SDValue(); 5899 5900 EVT VT = N->getValueType(0); 5901 5902 // There are 3 commutable operators in the pattern, 5903 // so we have to deal with 8 possible variants of the basic pattern. 5904 SDValue X, Y, M; 5905 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 5906 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 5907 return false; 5908 SDValue Xor = And.getOperand(XorIdx); 5909 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 5910 return false; 5911 SDValue Xor0 = Xor.getOperand(0); 5912 SDValue Xor1 = Xor.getOperand(1); 5913 // Don't touch 'not' (i.e. where y = -1). 5914 if (isAllOnesConstantOrAllOnesSplatConstant(Xor1)) 5915 return false; 5916 if (Other == Xor0) 5917 std::swap(Xor0, Xor1); 5918 if (Other != Xor1) 5919 return false; 5920 X = Xor0; 5921 Y = Xor1; 5922 M = And.getOperand(XorIdx ? 0 : 1); 5923 return true; 5924 }; 5925 5926 SDValue N0 = N->getOperand(0); 5927 SDValue N1 = N->getOperand(1); 5928 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 5929 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 5930 return SDValue(); 5931 5932 // Don't do anything if the mask is constant. This should not be reachable. 5933 // InstCombine should have already unfolded this pattern, and DAGCombiner 5934 // probably shouldn't produce it, too. 5935 if (isa<ConstantSDNode>(M.getNode())) 5936 return SDValue(); 5937 5938 // We can transform if the target has AndNot 5939 if (!TLI.hasAndNot(M)) 5940 return SDValue(); 5941 5942 SDLoc DL(N); 5943 5944 // If Y is a constant, check that 'andn' works with immediates. 5945 if (!TLI.hasAndNot(Y)) { 5946 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 5947 // If not, we need to do a bit more work to make sure andn is still used. 5948 SDValue NotX = DAG.getNOT(DL, X, VT); 5949 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 5950 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 5951 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 5952 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 5953 } 5954 5955 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 5956 SDValue NotM = DAG.getNOT(DL, M, VT); 5957 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 5958 5959 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 5960 } 5961 5962 SDValue DAGCombiner::visitXOR(SDNode *N) { 5963 SDValue N0 = N->getOperand(0); 5964 SDValue N1 = N->getOperand(1); 5965 EVT VT = N0.getValueType(); 5966 5967 // fold vector ops 5968 if (VT.isVector()) { 5969 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5970 return FoldedVOp; 5971 5972 // fold (xor x, 0) -> x, vector edition 5973 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5974 return N1; 5975 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5976 return N0; 5977 } 5978 5979 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5980 if (N0.isUndef() && N1.isUndef()) 5981 return DAG.getConstant(0, SDLoc(N), VT); 5982 // fold (xor x, undef) -> undef 5983 if (N0.isUndef()) 5984 return N0; 5985 if (N1.isUndef()) 5986 return N1; 5987 // fold (xor c1, c2) -> c1^c2 5988 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5989 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5990 if (N0C && N1C) 5991 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5992 // canonicalize constant to RHS 5993 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5994 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5995 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5996 // fold (xor x, 0) -> x 5997 if (isNullConstant(N1)) 5998 return N0; 5999 6000 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6001 return NewSel; 6002 6003 // reassociate xor 6004 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 6005 return RXOR; 6006 6007 // fold !(x cc y) -> (x !cc y) 6008 SDValue LHS, RHS, CC; 6009 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 6010 bool isInt = LHS.getValueType().isInteger(); 6011 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 6012 isInt); 6013 6014 if (!LegalOperations || 6015 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 6016 switch (N0.getOpcode()) { 6017 default: 6018 llvm_unreachable("Unhandled SetCC Equivalent!"); 6019 case ISD::SETCC: 6020 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 6021 case ISD::SELECT_CC: 6022 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 6023 N0.getOperand(3), NotCC); 6024 } 6025 } 6026 } 6027 6028 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 6029 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 6030 N0.getNode()->hasOneUse() && 6031 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 6032 SDValue V = N0.getOperand(0); 6033 SDLoc DL(N0); 6034 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 6035 DAG.getConstant(1, DL, V.getValueType())); 6036 AddToWorklist(V.getNode()); 6037 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 6038 } 6039 6040 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 6041 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 6042 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6043 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6044 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 6045 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6046 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6047 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6048 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6049 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6050 } 6051 } 6052 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 6053 if (isAllOnesConstant(N1) && N0.hasOneUse() && 6054 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6055 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6056 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 6057 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6058 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6059 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6060 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6061 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6062 } 6063 } 6064 // fold (xor (and x, y), y) -> (and (not x), y) 6065 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 6066 N0->getOperand(1) == N1) { 6067 SDValue X = N0->getOperand(0); 6068 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 6069 AddToWorklist(NotX.getNode()); 6070 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 6071 } 6072 6073 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 6074 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 6075 SDValue A = N0.getOpcode() == ISD::ADD ? N0 : N1; 6076 SDValue S = N0.getOpcode() == ISD::SRA ? N0 : N1; 6077 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 6078 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 6079 SDValue S0 = S.getOperand(0); 6080 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) { 6081 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6082 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 6083 if (C->getAPIntValue() == (OpSizeInBits - 1)) 6084 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 6085 } 6086 } 6087 } 6088 6089 // fold (xor x, x) -> 0 6090 if (N0 == N1) 6091 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 6092 6093 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 6094 // Here is a concrete example of this equivalence: 6095 // i16 x == 14 6096 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 6097 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 6098 // 6099 // => 6100 // 6101 // i16 ~1 == 0b1111111111111110 6102 // i16 rol(~1, 14) == 0b1011111111111111 6103 // 6104 // Some additional tips to help conceptualize this transform: 6105 // - Try to see the operation as placing a single zero in a value of all ones. 6106 // - There exists no value for x which would allow the result to contain zero. 6107 // - Values of x larger than the bitwidth are undefined and do not require a 6108 // consistent result. 6109 // - Pushing the zero left requires shifting one bits in from the right. 6110 // A rotate left of ~1 is a nice way of achieving the desired result. 6111 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 6112 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 6113 SDLoc DL(N); 6114 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 6115 N0.getOperand(1)); 6116 } 6117 6118 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 6119 if (N0.getOpcode() == N1.getOpcode()) 6120 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 6121 return Tmp; 6122 6123 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 6124 if (SDValue MM = unfoldMaskedMerge(N)) 6125 return MM; 6126 6127 // Simplify the expression using non-local knowledge. 6128 if (SimplifyDemandedBits(SDValue(N, 0))) 6129 return SDValue(N, 0); 6130 6131 return SDValue(); 6132 } 6133 6134 /// Handle transforms common to the three shifts, when the shift amount is a 6135 /// constant. 6136 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 6137 SDNode *LHS = N->getOperand(0).getNode(); 6138 if (!LHS->hasOneUse()) return SDValue(); 6139 6140 // We want to pull some binops through shifts, so that we have (and (shift)) 6141 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 6142 // thing happens with address calculations, so it's important to canonicalize 6143 // it. 6144 bool HighBitSet = false; // Can we transform this if the high bit is set? 6145 6146 switch (LHS->getOpcode()) { 6147 default: return SDValue(); 6148 case ISD::OR: 6149 case ISD::XOR: 6150 HighBitSet = false; // We can only transform sra if the high bit is clear. 6151 break; 6152 case ISD::AND: 6153 HighBitSet = true; // We can only transform sra if the high bit is set. 6154 break; 6155 case ISD::ADD: 6156 if (N->getOpcode() != ISD::SHL) 6157 return SDValue(); // only shl(add) not sr[al](add). 6158 HighBitSet = false; // We can only transform sra if the high bit is clear. 6159 break; 6160 } 6161 6162 // We require the RHS of the binop to be a constant and not opaque as well. 6163 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 6164 if (!BinOpCst) return SDValue(); 6165 6166 // FIXME: disable this unless the input to the binop is a shift by a constant 6167 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 6168 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 6169 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 6170 BinOpLHSVal->getOpcode() == ISD::SRA || 6171 BinOpLHSVal->getOpcode() == ISD::SRL; 6172 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 6173 BinOpLHSVal->getOpcode() == ISD::SELECT; 6174 6175 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 6176 !isCopyOrSelect) 6177 return SDValue(); 6178 6179 if (isCopyOrSelect && N->hasOneUse()) 6180 return SDValue(); 6181 6182 EVT VT = N->getValueType(0); 6183 6184 // If this is a signed shift right, and the high bit is modified by the 6185 // logical operation, do not perform the transformation. The highBitSet 6186 // boolean indicates the value of the high bit of the constant which would 6187 // cause it to be modified for this operation. 6188 if (N->getOpcode() == ISD::SRA) { 6189 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 6190 if (BinOpRHSSignSet != HighBitSet) 6191 return SDValue(); 6192 } 6193 6194 if (!TLI.isDesirableToCommuteWithShift(N, Level)) 6195 return SDValue(); 6196 6197 // Fold the constants, shifting the binop RHS by the shift amount. 6198 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 6199 N->getValueType(0), 6200 LHS->getOperand(1), N->getOperand(1)); 6201 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 6202 6203 // Create the new shift. 6204 SDValue NewShift = DAG.getNode(N->getOpcode(), 6205 SDLoc(LHS->getOperand(0)), 6206 VT, LHS->getOperand(0), N->getOperand(1)); 6207 6208 // Create the new binop. 6209 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 6210 } 6211 6212 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 6213 assert(N->getOpcode() == ISD::TRUNCATE); 6214 assert(N->getOperand(0).getOpcode() == ISD::AND); 6215 6216 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 6217 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 6218 SDValue N01 = N->getOperand(0).getOperand(1); 6219 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 6220 SDLoc DL(N); 6221 EVT TruncVT = N->getValueType(0); 6222 SDValue N00 = N->getOperand(0).getOperand(0); 6223 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 6224 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 6225 AddToWorklist(Trunc00.getNode()); 6226 AddToWorklist(Trunc01.getNode()); 6227 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 6228 } 6229 } 6230 6231 return SDValue(); 6232 } 6233 6234 SDValue DAGCombiner::visitRotate(SDNode *N) { 6235 SDLoc dl(N); 6236 SDValue N0 = N->getOperand(0); 6237 SDValue N1 = N->getOperand(1); 6238 EVT VT = N->getValueType(0); 6239 unsigned Bitsize = VT.getScalarSizeInBits(); 6240 6241 // fold (rot x, 0) -> x 6242 if (isNullConstantOrNullSplatConstant(N1)) 6243 return N0; 6244 6245 // fold (rot x, c) -> (rot x, c % BitSize) 6246 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 6247 if (Cst->getAPIntValue().uge(Bitsize)) { 6248 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 6249 return DAG.getNode(N->getOpcode(), dl, VT, N0, 6250 DAG.getConstant(RotAmt, dl, N1.getValueType())); 6251 } 6252 } 6253 6254 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 6255 if (N1.getOpcode() == ISD::TRUNCATE && 6256 N1.getOperand(0).getOpcode() == ISD::AND) { 6257 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6258 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 6259 } 6260 6261 unsigned NextOp = N0.getOpcode(); 6262 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 6263 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 6264 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 6265 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 6266 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 6267 EVT ShiftVT = C1->getValueType(0); 6268 bool SameSide = (N->getOpcode() == NextOp); 6269 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 6270 if (SDValue CombinedShift = 6271 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 6272 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 6273 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 6274 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 6275 BitsizeC.getNode()); 6276 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 6277 CombinedShiftNorm); 6278 } 6279 } 6280 } 6281 return SDValue(); 6282 } 6283 6284 SDValue DAGCombiner::visitSHL(SDNode *N) { 6285 SDValue N0 = N->getOperand(0); 6286 SDValue N1 = N->getOperand(1); 6287 EVT VT = N0.getValueType(); 6288 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6289 6290 // fold vector ops 6291 if (VT.isVector()) { 6292 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6293 return FoldedVOp; 6294 6295 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 6296 // If setcc produces all-one true value then: 6297 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 6298 if (N1CV && N1CV->isConstant()) { 6299 if (N0.getOpcode() == ISD::AND) { 6300 SDValue N00 = N0->getOperand(0); 6301 SDValue N01 = N0->getOperand(1); 6302 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 6303 6304 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 6305 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 6306 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6307 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 6308 N01CV, N1CV)) 6309 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 6310 } 6311 } 6312 } 6313 } 6314 6315 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6316 6317 // fold (shl c1, c2) -> c1<<c2 6318 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6319 if (N0C && N1C && !N1C->isOpaque()) 6320 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 6321 // fold (shl 0, x) -> 0 6322 if (isNullConstantOrNullSplatConstant(N0)) 6323 return N0; 6324 // fold (shl x, c >= size(x)) -> undef 6325 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6326 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6327 return Val->getAPIntValue().uge(OpSizeInBits); 6328 }; 6329 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6330 return DAG.getUNDEF(VT); 6331 // fold (shl x, 0) -> x 6332 if (N1C && N1C->isNullValue()) 6333 return N0; 6334 // fold (shl undef, x) -> 0 6335 if (N0.isUndef()) 6336 return DAG.getConstant(0, SDLoc(N), VT); 6337 6338 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6339 return NewSel; 6340 6341 // if (shl x, c) is known to be zero, return 0 6342 if (DAG.MaskedValueIsZero(SDValue(N, 0), 6343 APInt::getAllOnesValue(OpSizeInBits))) 6344 return DAG.getConstant(0, SDLoc(N), VT); 6345 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 6346 if (N1.getOpcode() == ISD::TRUNCATE && 6347 N1.getOperand(0).getOpcode() == ISD::AND) { 6348 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6349 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 6350 } 6351 6352 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6353 return SDValue(N, 0); 6354 6355 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 6356 if (N0.getOpcode() == ISD::SHL) { 6357 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6358 ConstantSDNode *RHS) { 6359 APInt c1 = LHS->getAPIntValue(); 6360 APInt c2 = RHS->getAPIntValue(); 6361 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6362 return (c1 + c2).uge(OpSizeInBits); 6363 }; 6364 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6365 return DAG.getConstant(0, SDLoc(N), VT); 6366 6367 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6368 ConstantSDNode *RHS) { 6369 APInt c1 = LHS->getAPIntValue(); 6370 APInt c2 = RHS->getAPIntValue(); 6371 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6372 return (c1 + c2).ult(OpSizeInBits); 6373 }; 6374 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6375 SDLoc DL(N); 6376 EVT ShiftVT = N1.getValueType(); 6377 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6378 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 6379 } 6380 } 6381 6382 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 6383 // For this to be valid, the second form must not preserve any of the bits 6384 // that are shifted out by the inner shift in the first form. This means 6385 // the outer shift size must be >= the number of bits added by the ext. 6386 // As a corollary, we don't care what kind of ext it is. 6387 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 6388 N0.getOpcode() == ISD::ANY_EXTEND || 6389 N0.getOpcode() == ISD::SIGN_EXTEND) && 6390 N0.getOperand(0).getOpcode() == ISD::SHL) { 6391 SDValue N0Op0 = N0.getOperand(0); 6392 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6393 APInt c1 = N0Op0C1->getAPIntValue(); 6394 APInt c2 = N1C->getAPIntValue(); 6395 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6396 6397 EVT InnerShiftVT = N0Op0.getValueType(); 6398 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6399 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 6400 SDLoc DL(N0); 6401 APInt Sum = c1 + c2; 6402 if (Sum.uge(OpSizeInBits)) 6403 return DAG.getConstant(0, DL, VT); 6404 6405 return DAG.getNode( 6406 ISD::SHL, DL, VT, 6407 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 6408 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 6409 } 6410 } 6411 } 6412 6413 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 6414 // Only fold this if the inner zext has no other uses to avoid increasing 6415 // the total number of instructions. 6416 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 6417 N0.getOperand(0).getOpcode() == ISD::SRL) { 6418 SDValue N0Op0 = N0.getOperand(0); 6419 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6420 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 6421 uint64_t c1 = N0Op0C1->getZExtValue(); 6422 uint64_t c2 = N1C->getZExtValue(); 6423 if (c1 == c2) { 6424 SDValue NewOp0 = N0.getOperand(0); 6425 EVT CountVT = NewOp0.getOperand(1).getValueType(); 6426 SDLoc DL(N); 6427 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 6428 NewOp0, 6429 DAG.getConstant(c2, DL, CountVT)); 6430 AddToWorklist(NewSHL.getNode()); 6431 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 6432 } 6433 } 6434 } 6435 } 6436 6437 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 6438 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 6439 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 6440 N0->getFlags().hasExact()) { 6441 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6442 uint64_t C1 = N0C1->getZExtValue(); 6443 uint64_t C2 = N1C->getZExtValue(); 6444 SDLoc DL(N); 6445 if (C1 <= C2) 6446 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6447 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 6448 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 6449 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 6450 } 6451 } 6452 6453 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 6454 // (and (srl x, (sub c1, c2), MASK) 6455 // Only fold this if the inner shift has no other uses -- if it does, folding 6456 // this will increase the total number of instructions. 6457 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6458 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6459 uint64_t c1 = N0C1->getZExtValue(); 6460 if (c1 < OpSizeInBits) { 6461 uint64_t c2 = N1C->getZExtValue(); 6462 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 6463 SDValue Shift; 6464 if (c2 > c1) { 6465 Mask <<= c2 - c1; 6466 SDLoc DL(N); 6467 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6468 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 6469 } else { 6470 Mask.lshrInPlace(c1 - c2); 6471 SDLoc DL(N); 6472 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 6473 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 6474 } 6475 SDLoc DL(N0); 6476 return DAG.getNode(ISD::AND, DL, VT, Shift, 6477 DAG.getConstant(Mask, DL, VT)); 6478 } 6479 } 6480 } 6481 6482 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 6483 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 6484 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 6485 SDLoc DL(N); 6486 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 6487 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 6488 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 6489 } 6490 6491 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 6492 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 6493 // Variant of version done on multiply, except mul by a power of 2 is turned 6494 // into a shift. 6495 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 6496 N0.getNode()->hasOneUse() && 6497 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6498 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 6499 TLI.isDesirableToCommuteWithShift(N, Level)) { 6500 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 6501 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6502 AddToWorklist(Shl0.getNode()); 6503 AddToWorklist(Shl1.getNode()); 6504 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 6505 } 6506 6507 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 6508 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 6509 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6510 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 6511 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6512 if (isConstantOrConstantVector(Shl)) 6513 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 6514 } 6515 6516 if (N1C && !N1C->isOpaque()) 6517 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 6518 return NewSHL; 6519 6520 return SDValue(); 6521 } 6522 6523 SDValue DAGCombiner::visitSRA(SDNode *N) { 6524 SDValue N0 = N->getOperand(0); 6525 SDValue N1 = N->getOperand(1); 6526 EVT VT = N0.getValueType(); 6527 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6528 6529 // Arithmetic shifting an all-sign-bit value is a no-op. 6530 // fold (sra 0, x) -> 0 6531 // fold (sra -1, x) -> -1 6532 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 6533 return N0; 6534 6535 // fold vector ops 6536 if (VT.isVector()) 6537 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6538 return FoldedVOp; 6539 6540 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6541 6542 // fold (sra c1, c2) -> (sra c1, c2) 6543 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6544 if (N0C && N1C && !N1C->isOpaque()) 6545 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 6546 // fold (sra x, c >= size(x)) -> undef 6547 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6548 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6549 return Val->getAPIntValue().uge(OpSizeInBits); 6550 }; 6551 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6552 return DAG.getUNDEF(VT); 6553 // fold (sra x, 0) -> x 6554 if (N1C && N1C->isNullValue()) 6555 return N0; 6556 6557 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6558 return NewSel; 6559 6560 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 6561 // sext_inreg. 6562 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 6563 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 6564 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 6565 if (VT.isVector()) 6566 ExtVT = EVT::getVectorVT(*DAG.getContext(), 6567 ExtVT, VT.getVectorNumElements()); 6568 if ((!LegalOperations || 6569 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 6570 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6571 N0.getOperand(0), DAG.getValueType(ExtVT)); 6572 } 6573 6574 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 6575 if (N0.getOpcode() == ISD::SRA) { 6576 SDLoc DL(N); 6577 EVT ShiftVT = N1.getValueType(); 6578 6579 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6580 ConstantSDNode *RHS) { 6581 APInt c1 = LHS->getAPIntValue(); 6582 APInt c2 = RHS->getAPIntValue(); 6583 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6584 return (c1 + c2).uge(OpSizeInBits); 6585 }; 6586 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6587 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 6588 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 6589 6590 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6591 ConstantSDNode *RHS) { 6592 APInt c1 = LHS->getAPIntValue(); 6593 APInt c2 = RHS->getAPIntValue(); 6594 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6595 return (c1 + c2).ult(OpSizeInBits); 6596 }; 6597 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6598 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6599 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 6600 } 6601 } 6602 6603 // fold (sra (shl X, m), (sub result_size, n)) 6604 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 6605 // result_size - n != m. 6606 // If truncate is free for the target sext(shl) is likely to result in better 6607 // code. 6608 if (N0.getOpcode() == ISD::SHL && N1C) { 6609 // Get the two constanst of the shifts, CN0 = m, CN = n. 6610 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 6611 if (N01C) { 6612 LLVMContext &Ctx = *DAG.getContext(); 6613 // Determine what the truncate's result bitsize and type would be. 6614 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 6615 6616 if (VT.isVector()) 6617 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 6618 6619 // Determine the residual right-shift amount. 6620 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 6621 6622 // If the shift is not a no-op (in which case this should be just a sign 6623 // extend already), the truncated to type is legal, sign_extend is legal 6624 // on that type, and the truncate to that type is both legal and free, 6625 // perform the transform. 6626 if ((ShiftAmt > 0) && 6627 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 6628 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 6629 TLI.isTruncateFree(VT, TruncVT)) { 6630 SDLoc DL(N); 6631 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 6632 getShiftAmountTy(N0.getOperand(0).getValueType())); 6633 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 6634 N0.getOperand(0), Amt); 6635 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 6636 Shift); 6637 return DAG.getNode(ISD::SIGN_EXTEND, DL, 6638 N->getValueType(0), Trunc); 6639 } 6640 } 6641 } 6642 6643 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 6644 if (N1.getOpcode() == ISD::TRUNCATE && 6645 N1.getOperand(0).getOpcode() == ISD::AND) { 6646 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6647 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 6648 } 6649 6650 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 6651 // if c1 is equal to the number of bits the trunc removes 6652 if (N0.getOpcode() == ISD::TRUNCATE && 6653 (N0.getOperand(0).getOpcode() == ISD::SRL || 6654 N0.getOperand(0).getOpcode() == ISD::SRA) && 6655 N0.getOperand(0).hasOneUse() && 6656 N0.getOperand(0).getOperand(1).hasOneUse() && 6657 N1C) { 6658 SDValue N0Op0 = N0.getOperand(0); 6659 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 6660 unsigned LargeShiftVal = LargeShift->getZExtValue(); 6661 EVT LargeVT = N0Op0.getValueType(); 6662 6663 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 6664 SDLoc DL(N); 6665 SDValue Amt = 6666 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 6667 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 6668 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 6669 N0Op0.getOperand(0), Amt); 6670 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 6671 } 6672 } 6673 } 6674 6675 // Simplify, based on bits shifted out of the LHS. 6676 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6677 return SDValue(N, 0); 6678 6679 // If the sign bit is known to be zero, switch this to a SRL. 6680 if (DAG.SignBitIsZero(N0)) 6681 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 6682 6683 if (N1C && !N1C->isOpaque()) 6684 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 6685 return NewSRA; 6686 6687 return SDValue(); 6688 } 6689 6690 SDValue DAGCombiner::visitSRL(SDNode *N) { 6691 SDValue N0 = N->getOperand(0); 6692 SDValue N1 = N->getOperand(1); 6693 EVT VT = N0.getValueType(); 6694 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6695 6696 // fold vector ops 6697 if (VT.isVector()) 6698 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6699 return FoldedVOp; 6700 6701 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6702 6703 // fold (srl c1, c2) -> c1 >>u c2 6704 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6705 if (N0C && N1C && !N1C->isOpaque()) 6706 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6707 // fold (srl 0, x) -> 0 6708 if (isNullConstantOrNullSplatConstant(N0)) 6709 return N0; 6710 // fold (srl x, c >= size(x)) -> undef 6711 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6712 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6713 return Val->getAPIntValue().uge(OpSizeInBits); 6714 }; 6715 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6716 return DAG.getUNDEF(VT); 6717 // fold (srl x, 0) -> x 6718 if (N1C && N1C->isNullValue()) 6719 return N0; 6720 6721 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6722 return NewSel; 6723 6724 // if (srl x, c) is known to be zero, return 0 6725 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6726 APInt::getAllOnesValue(OpSizeInBits))) 6727 return DAG.getConstant(0, SDLoc(N), VT); 6728 6729 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6730 if (N0.getOpcode() == ISD::SRL) { 6731 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6732 ConstantSDNode *RHS) { 6733 APInt c1 = LHS->getAPIntValue(); 6734 APInt c2 = RHS->getAPIntValue(); 6735 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6736 return (c1 + c2).uge(OpSizeInBits); 6737 }; 6738 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6739 return DAG.getConstant(0, SDLoc(N), VT); 6740 6741 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6742 ConstantSDNode *RHS) { 6743 APInt c1 = LHS->getAPIntValue(); 6744 APInt c2 = RHS->getAPIntValue(); 6745 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6746 return (c1 + c2).ult(OpSizeInBits); 6747 }; 6748 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6749 SDLoc DL(N); 6750 EVT ShiftVT = N1.getValueType(); 6751 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6752 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6753 } 6754 } 6755 6756 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6757 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6758 N0.getOperand(0).getOpcode() == ISD::SRL) { 6759 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6760 uint64_t c1 = N001C->getZExtValue(); 6761 uint64_t c2 = N1C->getZExtValue(); 6762 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6763 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6764 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6765 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6766 if (c1 + OpSizeInBits == InnerShiftSize) { 6767 SDLoc DL(N0); 6768 if (c1 + c2 >= InnerShiftSize) 6769 return DAG.getConstant(0, DL, VT); 6770 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6771 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6772 N0.getOperand(0).getOperand(0), 6773 DAG.getConstant(c1 + c2, DL, 6774 ShiftCountVT))); 6775 } 6776 } 6777 } 6778 6779 // fold (srl (shl x, c), c) -> (and x, cst2) 6780 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6781 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6782 SDLoc DL(N); 6783 SDValue Mask = 6784 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6785 AddToWorklist(Mask.getNode()); 6786 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6787 } 6788 6789 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6790 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6791 // Shifting in all undef bits? 6792 EVT SmallVT = N0.getOperand(0).getValueType(); 6793 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6794 if (N1C->getZExtValue() >= BitSize) 6795 return DAG.getUNDEF(VT); 6796 6797 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6798 uint64_t ShiftAmt = N1C->getZExtValue(); 6799 SDLoc DL0(N0); 6800 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6801 N0.getOperand(0), 6802 DAG.getConstant(ShiftAmt, DL0, 6803 getShiftAmountTy(SmallVT))); 6804 AddToWorklist(SmallShift.getNode()); 6805 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6806 SDLoc DL(N); 6807 return DAG.getNode(ISD::AND, DL, VT, 6808 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6809 DAG.getConstant(Mask, DL, VT)); 6810 } 6811 } 6812 6813 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6814 // bit, which is unmodified by sra. 6815 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6816 if (N0.getOpcode() == ISD::SRA) 6817 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6818 } 6819 6820 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6821 if (N1C && N0.getOpcode() == ISD::CTLZ && 6822 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6823 KnownBits Known; 6824 DAG.computeKnownBits(N0.getOperand(0), Known); 6825 6826 // If any of the input bits are KnownOne, then the input couldn't be all 6827 // zeros, thus the result of the srl will always be zero. 6828 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6829 6830 // If all of the bits input the to ctlz node are known to be zero, then 6831 // the result of the ctlz is "32" and the result of the shift is one. 6832 APInt UnknownBits = ~Known.Zero; 6833 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6834 6835 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6836 if (UnknownBits.isPowerOf2()) { 6837 // Okay, we know that only that the single bit specified by UnknownBits 6838 // could be set on input to the CTLZ node. If this bit is set, the SRL 6839 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6840 // to an SRL/XOR pair, which is likely to simplify more. 6841 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6842 SDValue Op = N0.getOperand(0); 6843 6844 if (ShAmt) { 6845 SDLoc DL(N0); 6846 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6847 DAG.getConstant(ShAmt, DL, 6848 getShiftAmountTy(Op.getValueType()))); 6849 AddToWorklist(Op.getNode()); 6850 } 6851 6852 SDLoc DL(N); 6853 return DAG.getNode(ISD::XOR, DL, VT, 6854 Op, DAG.getConstant(1, DL, VT)); 6855 } 6856 } 6857 6858 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6859 if (N1.getOpcode() == ISD::TRUNCATE && 6860 N1.getOperand(0).getOpcode() == ISD::AND) { 6861 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6862 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6863 } 6864 6865 // fold operands of srl based on knowledge that the low bits are not 6866 // demanded. 6867 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6868 return SDValue(N, 0); 6869 6870 if (N1C && !N1C->isOpaque()) 6871 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6872 return NewSRL; 6873 6874 // Attempt to convert a srl of a load into a narrower zero-extending load. 6875 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6876 return NarrowLoad; 6877 6878 // Here is a common situation. We want to optimize: 6879 // 6880 // %a = ... 6881 // %b = and i32 %a, 2 6882 // %c = srl i32 %b, 1 6883 // brcond i32 %c ... 6884 // 6885 // into 6886 // 6887 // %a = ... 6888 // %b = and %a, 2 6889 // %c = setcc eq %b, 0 6890 // brcond %c ... 6891 // 6892 // However when after the source operand of SRL is optimized into AND, the SRL 6893 // itself may not be optimized further. Look for it and add the BRCOND into 6894 // the worklist. 6895 if (N->hasOneUse()) { 6896 SDNode *Use = *N->use_begin(); 6897 if (Use->getOpcode() == ISD::BRCOND) 6898 AddToWorklist(Use); 6899 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6900 // Also look pass the truncate. 6901 Use = *Use->use_begin(); 6902 if (Use->getOpcode() == ISD::BRCOND) 6903 AddToWorklist(Use); 6904 } 6905 } 6906 6907 return SDValue(); 6908 } 6909 6910 SDValue DAGCombiner::visitABS(SDNode *N) { 6911 SDValue N0 = N->getOperand(0); 6912 EVT VT = N->getValueType(0); 6913 6914 // fold (abs c1) -> c2 6915 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6916 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6917 // fold (abs (abs x)) -> (abs x) 6918 if (N0.getOpcode() == ISD::ABS) 6919 return N0; 6920 // fold (abs x) -> x iff not-negative 6921 if (DAG.SignBitIsZero(N0)) 6922 return N0; 6923 return SDValue(); 6924 } 6925 6926 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6927 SDValue N0 = N->getOperand(0); 6928 EVT VT = N->getValueType(0); 6929 6930 // fold (bswap c1) -> c2 6931 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6932 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6933 // fold (bswap (bswap x)) -> x 6934 if (N0.getOpcode() == ISD::BSWAP) 6935 return N0->getOperand(0); 6936 return SDValue(); 6937 } 6938 6939 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6940 SDValue N0 = N->getOperand(0); 6941 EVT VT = N->getValueType(0); 6942 6943 // fold (bitreverse c1) -> c2 6944 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6945 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6946 // fold (bitreverse (bitreverse x)) -> x 6947 if (N0.getOpcode() == ISD::BITREVERSE) 6948 return N0.getOperand(0); 6949 return SDValue(); 6950 } 6951 6952 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6953 SDValue N0 = N->getOperand(0); 6954 EVT VT = N->getValueType(0); 6955 6956 // fold (ctlz c1) -> c2 6957 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6958 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6959 6960 // If the value is known never to be zero, switch to the undef version. 6961 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 6962 if (DAG.isKnownNeverZero(N0)) 6963 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6964 } 6965 6966 return SDValue(); 6967 } 6968 6969 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6970 SDValue N0 = N->getOperand(0); 6971 EVT VT = N->getValueType(0); 6972 6973 // fold (ctlz_zero_undef c1) -> c2 6974 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6975 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6976 return SDValue(); 6977 } 6978 6979 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6980 SDValue N0 = N->getOperand(0); 6981 EVT VT = N->getValueType(0); 6982 6983 // fold (cttz c1) -> c2 6984 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6985 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6986 6987 // If the value is known never to be zero, switch to the undef version. 6988 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 6989 if (DAG.isKnownNeverZero(N0)) 6990 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6991 } 6992 6993 return SDValue(); 6994 } 6995 6996 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6997 SDValue N0 = N->getOperand(0); 6998 EVT VT = N->getValueType(0); 6999 7000 // fold (cttz_zero_undef c1) -> c2 7001 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7002 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7003 return SDValue(); 7004 } 7005 7006 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 7007 SDValue N0 = N->getOperand(0); 7008 EVT VT = N->getValueType(0); 7009 7010 // fold (ctpop c1) -> c2 7011 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7012 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 7013 return SDValue(); 7014 } 7015 7016 /// Generate Min/Max node 7017 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 7018 SDValue RHS, SDValue True, SDValue False, 7019 ISD::CondCode CC, const TargetLowering &TLI, 7020 SelectionDAG &DAG) { 7021 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 7022 return SDValue(); 7023 7024 switch (CC) { 7025 case ISD::SETOLT: 7026 case ISD::SETOLE: 7027 case ISD::SETLT: 7028 case ISD::SETLE: 7029 case ISD::SETULT: 7030 case ISD::SETULE: { 7031 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 7032 if (TLI.isOperationLegal(Opcode, VT)) 7033 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7034 return SDValue(); 7035 } 7036 case ISD::SETOGT: 7037 case ISD::SETOGE: 7038 case ISD::SETGT: 7039 case ISD::SETGE: 7040 case ISD::SETUGT: 7041 case ISD::SETUGE: { 7042 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 7043 if (TLI.isOperationLegal(Opcode, VT)) 7044 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7045 return SDValue(); 7046 } 7047 default: 7048 return SDValue(); 7049 } 7050 } 7051 7052 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 7053 SDValue Cond = N->getOperand(0); 7054 SDValue N1 = N->getOperand(1); 7055 SDValue N2 = N->getOperand(2); 7056 EVT VT = N->getValueType(0); 7057 EVT CondVT = Cond.getValueType(); 7058 SDLoc DL(N); 7059 7060 if (!VT.isInteger()) 7061 return SDValue(); 7062 7063 auto *C1 = dyn_cast<ConstantSDNode>(N1); 7064 auto *C2 = dyn_cast<ConstantSDNode>(N2); 7065 if (!C1 || !C2) 7066 return SDValue(); 7067 7068 // Only do this before legalization to avoid conflicting with target-specific 7069 // transforms in the other direction (create a select from a zext/sext). There 7070 // is also a target-independent combine here in DAGCombiner in the other 7071 // direction for (select Cond, -1, 0) when the condition is not i1. 7072 if (CondVT == MVT::i1 && !LegalOperations) { 7073 if (C1->isNullValue() && C2->isOne()) { 7074 // select Cond, 0, 1 --> zext (!Cond) 7075 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7076 if (VT != MVT::i1) 7077 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 7078 return NotCond; 7079 } 7080 if (C1->isNullValue() && C2->isAllOnesValue()) { 7081 // select Cond, 0, -1 --> sext (!Cond) 7082 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7083 if (VT != MVT::i1) 7084 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 7085 return NotCond; 7086 } 7087 if (C1->isOne() && C2->isNullValue()) { 7088 // select Cond, 1, 0 --> zext (Cond) 7089 if (VT != MVT::i1) 7090 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7091 return Cond; 7092 } 7093 if (C1->isAllOnesValue() && C2->isNullValue()) { 7094 // select Cond, -1, 0 --> sext (Cond) 7095 if (VT != MVT::i1) 7096 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7097 return Cond; 7098 } 7099 7100 // For any constants that differ by 1, we can transform the select into an 7101 // extend and add. Use a target hook because some targets may prefer to 7102 // transform in the other direction. 7103 if (TLI.convertSelectOfConstantsToMath(VT)) { 7104 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 7105 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 7106 if (VT != MVT::i1) 7107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7108 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7109 } 7110 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 7111 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 7112 if (VT != MVT::i1) 7113 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7114 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7115 } 7116 } 7117 7118 return SDValue(); 7119 } 7120 7121 // fold (select Cond, 0, 1) -> (xor Cond, 1) 7122 // We can't do this reliably if integer based booleans have different contents 7123 // to floating point based booleans. This is because we can't tell whether we 7124 // have an integer-based boolean or a floating-point-based boolean unless we 7125 // can find the SETCC that produced it and inspect its operands. This is 7126 // fairly easy if C is the SETCC node, but it can potentially be 7127 // undiscoverable (or not reasonably discoverable). For example, it could be 7128 // in another basic block or it could require searching a complicated 7129 // expression. 7130 if (CondVT.isInteger() && 7131 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 7132 TargetLowering::ZeroOrOneBooleanContent && 7133 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 7134 TargetLowering::ZeroOrOneBooleanContent && 7135 C1->isNullValue() && C2->isOne()) { 7136 SDValue NotCond = 7137 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 7138 if (VT.bitsEq(CondVT)) 7139 return NotCond; 7140 return DAG.getZExtOrTrunc(NotCond, DL, VT); 7141 } 7142 7143 return SDValue(); 7144 } 7145 7146 SDValue DAGCombiner::visitSELECT(SDNode *N) { 7147 SDValue N0 = N->getOperand(0); 7148 SDValue N1 = N->getOperand(1); 7149 SDValue N2 = N->getOperand(2); 7150 EVT VT = N->getValueType(0); 7151 EVT VT0 = N0.getValueType(); 7152 SDLoc DL(N); 7153 7154 // fold (select C, X, X) -> X 7155 if (N1 == N2) 7156 return N1; 7157 7158 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 7159 // fold (select true, X, Y) -> X 7160 // fold (select false, X, Y) -> Y 7161 return !N0C->isNullValue() ? N1 : N2; 7162 } 7163 7164 // fold (select X, X, Y) -> (or X, Y) 7165 // fold (select X, 1, Y) -> (or C, Y) 7166 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 7167 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 7168 7169 if (SDValue V = foldSelectOfConstants(N)) 7170 return V; 7171 7172 // fold (select C, 0, X) -> (and (not C), X) 7173 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 7174 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7175 AddToWorklist(NOTNode.getNode()); 7176 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 7177 } 7178 // fold (select C, X, 1) -> (or (not C), X) 7179 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 7180 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7181 AddToWorklist(NOTNode.getNode()); 7182 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 7183 } 7184 // fold (select X, Y, X) -> (and X, Y) 7185 // fold (select X, Y, 0) -> (and X, Y) 7186 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 7187 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 7188 7189 // If we can fold this based on the true/false value, do so. 7190 if (SimplifySelectOps(N, N1, N2)) 7191 return SDValue(N, 0); // Don't revisit N. 7192 7193 if (VT0 == MVT::i1) { 7194 // The code in this block deals with the following 2 equivalences: 7195 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 7196 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 7197 // The target can specify its preferred form with the 7198 // shouldNormalizeToSelectSequence() callback. However we always transform 7199 // to the right anyway if we find the inner select exists in the DAG anyway 7200 // and we always transform to the left side if we know that we can further 7201 // optimize the combination of the conditions. 7202 bool normalizeToSequence = 7203 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 7204 // select (and Cond0, Cond1), X, Y 7205 // -> select Cond0, (select Cond1, X, Y), Y 7206 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 7207 SDValue Cond0 = N0->getOperand(0); 7208 SDValue Cond1 = N0->getOperand(1); 7209 SDValue InnerSelect = 7210 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7211 if (normalizeToSequence || !InnerSelect.use_empty()) 7212 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 7213 InnerSelect, N2); 7214 } 7215 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 7216 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 7217 SDValue Cond0 = N0->getOperand(0); 7218 SDValue Cond1 = N0->getOperand(1); 7219 SDValue InnerSelect = 7220 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7221 if (normalizeToSequence || !InnerSelect.use_empty()) 7222 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 7223 InnerSelect); 7224 } 7225 7226 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 7227 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 7228 SDValue N1_0 = N1->getOperand(0); 7229 SDValue N1_1 = N1->getOperand(1); 7230 SDValue N1_2 = N1->getOperand(2); 7231 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 7232 // Create the actual and node if we can generate good code for it. 7233 if (!normalizeToSequence) { 7234 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 7235 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 7236 } 7237 // Otherwise see if we can optimize the "and" to a better pattern. 7238 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 7239 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 7240 N2); 7241 } 7242 } 7243 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 7244 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 7245 SDValue N2_0 = N2->getOperand(0); 7246 SDValue N2_1 = N2->getOperand(1); 7247 SDValue N2_2 = N2->getOperand(2); 7248 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 7249 // Create the actual or node if we can generate good code for it. 7250 if (!normalizeToSequence) { 7251 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 7252 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 7253 } 7254 // Otherwise see if we can optimize to a better pattern. 7255 if (SDValue Combined = visitORLike(N0, N2_0, N)) 7256 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 7257 N2_2); 7258 } 7259 } 7260 } 7261 7262 if (VT0 == MVT::i1) { 7263 // select (not Cond), N1, N2 -> select Cond, N2, N1 7264 if (isBitwiseNot(N0)) 7265 return DAG.getNode(ISD::SELECT, DL, VT, N0->getOperand(0), N2, N1); 7266 } 7267 7268 // fold selects based on a setcc into other things, such as min/max/abs 7269 if (N0.getOpcode() == ISD::SETCC) { 7270 // select x, y (fcmp lt x, y) -> fminnum x, y 7271 // select x, y (fcmp gt x, y) -> fmaxnum x, y 7272 // 7273 // This is OK if we don't care about what happens if either operand is a 7274 // NaN. 7275 // 7276 7277 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 7278 // no signed zeros as well as no nans. 7279 const TargetOptions &Options = DAG.getTarget().Options; 7280 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 7281 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 7282 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7283 7284 if (SDValue FMinMax = combineMinNumMaxNum( 7285 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 7286 return FMinMax; 7287 } 7288 7289 if ((!LegalOperations && 7290 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 7291 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 7292 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 7293 N0.getOperand(1), N1, N2, N0.getOperand(2)); 7294 return SimplifySelect(DL, N0, N1, N2); 7295 } 7296 7297 return SDValue(); 7298 } 7299 7300 static 7301 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 7302 SDLoc DL(N); 7303 EVT LoVT, HiVT; 7304 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 7305 7306 // Split the inputs. 7307 SDValue Lo, Hi, LL, LH, RL, RH; 7308 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 7309 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 7310 7311 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 7312 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 7313 7314 return std::make_pair(Lo, Hi); 7315 } 7316 7317 // This function assumes all the vselect's arguments are CONCAT_VECTOR 7318 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 7319 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 7320 SDLoc DL(N); 7321 SDValue Cond = N->getOperand(0); 7322 SDValue LHS = N->getOperand(1); 7323 SDValue RHS = N->getOperand(2); 7324 EVT VT = N->getValueType(0); 7325 int NumElems = VT.getVectorNumElements(); 7326 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 7327 RHS.getOpcode() == ISD::CONCAT_VECTORS && 7328 Cond.getOpcode() == ISD::BUILD_VECTOR); 7329 7330 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 7331 // binary ones here. 7332 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 7333 return SDValue(); 7334 7335 // We're sure we have an even number of elements due to the 7336 // concat_vectors we have as arguments to vselect. 7337 // Skip BV elements until we find one that's not an UNDEF 7338 // After we find an UNDEF element, keep looping until we get to half the 7339 // length of the BV and see if all the non-undef nodes are the same. 7340 ConstantSDNode *BottomHalf = nullptr; 7341 for (int i = 0; i < NumElems / 2; ++i) { 7342 if (Cond->getOperand(i)->isUndef()) 7343 continue; 7344 7345 if (BottomHalf == nullptr) 7346 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7347 else if (Cond->getOperand(i).getNode() != BottomHalf) 7348 return SDValue(); 7349 } 7350 7351 // Do the same for the second half of the BuildVector 7352 ConstantSDNode *TopHalf = nullptr; 7353 for (int i = NumElems / 2; i < NumElems; ++i) { 7354 if (Cond->getOperand(i)->isUndef()) 7355 continue; 7356 7357 if (TopHalf == nullptr) 7358 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7359 else if (Cond->getOperand(i).getNode() != TopHalf) 7360 return SDValue(); 7361 } 7362 7363 assert(TopHalf && BottomHalf && 7364 "One half of the selector was all UNDEFs and the other was all the " 7365 "same value. This should have been addressed before this function."); 7366 return DAG.getNode( 7367 ISD::CONCAT_VECTORS, DL, VT, 7368 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 7369 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 7370 } 7371 7372 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 7373 if (Level >= AfterLegalizeTypes) 7374 return SDValue(); 7375 7376 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 7377 SDValue Mask = MSC->getMask(); 7378 SDValue Data = MSC->getValue(); 7379 SDLoc DL(N); 7380 7381 // If the MSCATTER data type requires splitting and the mask is provided by a 7382 // SETCC, then split both nodes and its operands before legalization. This 7383 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7384 // and enables future optimizations (e.g. min/max pattern matching on X86). 7385 if (Mask.getOpcode() != ISD::SETCC) 7386 return SDValue(); 7387 7388 // Check if any splitting is required. 7389 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 7390 TargetLowering::TypeSplitVector) 7391 return SDValue(); 7392 SDValue MaskLo, MaskHi, Lo, Hi; 7393 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7394 7395 EVT LoVT, HiVT; 7396 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 7397 7398 SDValue Chain = MSC->getChain(); 7399 7400 EVT MemoryVT = MSC->getMemoryVT(); 7401 unsigned Alignment = MSC->getOriginalAlignment(); 7402 7403 EVT LoMemVT, HiMemVT; 7404 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7405 7406 SDValue DataLo, DataHi; 7407 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7408 7409 SDValue Scale = MSC->getScale(); 7410 SDValue BasePtr = MSC->getBasePtr(); 7411 SDValue IndexLo, IndexHi; 7412 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 7413 7414 MachineMemOperand *MMO = DAG.getMachineFunction(). 7415 getMachineMemOperand(MSC->getPointerInfo(), 7416 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7417 Alignment, MSC->getAAInfo(), MSC->getRanges()); 7418 7419 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale }; 7420 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 7421 DL, OpsLo, MMO); 7422 7423 SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale }; 7424 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 7425 DL, OpsHi, MMO); 7426 7427 AddToWorklist(Lo.getNode()); 7428 AddToWorklist(Hi.getNode()); 7429 7430 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 7431 } 7432 7433 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 7434 if (Level >= AfterLegalizeTypes) 7435 return SDValue(); 7436 7437 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 7438 SDValue Mask = MST->getMask(); 7439 SDValue Data = MST->getValue(); 7440 EVT VT = Data.getValueType(); 7441 SDLoc DL(N); 7442 7443 // If the MSTORE data type requires splitting and the mask is provided by a 7444 // SETCC, then split both nodes and its operands before legalization. This 7445 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7446 // and enables future optimizations (e.g. min/max pattern matching on X86). 7447 if (Mask.getOpcode() == ISD::SETCC) { 7448 // Check if any splitting is required. 7449 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7450 TargetLowering::TypeSplitVector) 7451 return SDValue(); 7452 7453 SDValue MaskLo, MaskHi, Lo, Hi; 7454 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7455 7456 SDValue Chain = MST->getChain(); 7457 SDValue Ptr = MST->getBasePtr(); 7458 7459 EVT MemoryVT = MST->getMemoryVT(); 7460 unsigned Alignment = MST->getOriginalAlignment(); 7461 7462 // if Alignment is equal to the vector size, 7463 // take the half of it for the second part 7464 unsigned SecondHalfAlignment = 7465 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 7466 7467 EVT LoMemVT, HiMemVT; 7468 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7469 7470 SDValue DataLo, DataHi; 7471 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7472 7473 MachineMemOperand *MMO = DAG.getMachineFunction(). 7474 getMachineMemOperand(MST->getPointerInfo(), 7475 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7476 Alignment, MST->getAAInfo(), MST->getRanges()); 7477 7478 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 7479 MST->isTruncatingStore(), 7480 MST->isCompressingStore()); 7481 7482 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7483 MST->isCompressingStore()); 7484 unsigned HiOffset = LoMemVT.getStoreSize(); 7485 7486 MMO = DAG.getMachineFunction().getMachineMemOperand( 7487 MST->getPointerInfo().getWithOffset(HiOffset), 7488 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment, 7489 MST->getAAInfo(), MST->getRanges()); 7490 7491 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 7492 MST->isTruncatingStore(), 7493 MST->isCompressingStore()); 7494 7495 AddToWorklist(Lo.getNode()); 7496 AddToWorklist(Hi.getNode()); 7497 7498 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 7499 } 7500 return SDValue(); 7501 } 7502 7503 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 7504 if (Level >= AfterLegalizeTypes) 7505 return SDValue(); 7506 7507 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 7508 SDValue Mask = MGT->getMask(); 7509 SDLoc DL(N); 7510 7511 // If the MGATHER result requires splitting and the mask is provided by a 7512 // SETCC, then split both nodes and its operands before legalization. This 7513 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7514 // and enables future optimizations (e.g. min/max pattern matching on X86). 7515 7516 if (Mask.getOpcode() != ISD::SETCC) 7517 return SDValue(); 7518 7519 EVT VT = N->getValueType(0); 7520 7521 // Check if any splitting is required. 7522 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7523 TargetLowering::TypeSplitVector) 7524 return SDValue(); 7525 7526 SDValue MaskLo, MaskHi, Lo, Hi; 7527 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7528 7529 SDValue Src0 = MGT->getValue(); 7530 SDValue Src0Lo, Src0Hi; 7531 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 7532 7533 EVT LoVT, HiVT; 7534 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 7535 7536 SDValue Chain = MGT->getChain(); 7537 EVT MemoryVT = MGT->getMemoryVT(); 7538 unsigned Alignment = MGT->getOriginalAlignment(); 7539 7540 EVT LoMemVT, HiMemVT; 7541 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7542 7543 SDValue Scale = MGT->getScale(); 7544 SDValue BasePtr = MGT->getBasePtr(); 7545 SDValue Index = MGT->getIndex(); 7546 SDValue IndexLo, IndexHi; 7547 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 7548 7549 MachineMemOperand *MMO = DAG.getMachineFunction(). 7550 getMachineMemOperand(MGT->getPointerInfo(), 7551 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7552 Alignment, MGT->getAAInfo(), MGT->getRanges()); 7553 7554 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale }; 7555 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 7556 MMO); 7557 7558 SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale }; 7559 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 7560 MMO); 7561 7562 AddToWorklist(Lo.getNode()); 7563 AddToWorklist(Hi.getNode()); 7564 7565 // Build a factor node to remember that this load is independent of the 7566 // other one. 7567 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7568 Hi.getValue(1)); 7569 7570 // Legalized the chain result - switch anything that used the old chain to 7571 // use the new one. 7572 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 7573 7574 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7575 7576 SDValue RetOps[] = { GatherRes, Chain }; 7577 return DAG.getMergeValues(RetOps, DL); 7578 } 7579 7580 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 7581 if (Level >= AfterLegalizeTypes) 7582 return SDValue(); 7583 7584 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 7585 SDValue Mask = MLD->getMask(); 7586 SDLoc DL(N); 7587 7588 // If the MLOAD result requires splitting and the mask is provided by a 7589 // SETCC, then split both nodes and its operands before legalization. This 7590 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7591 // and enables future optimizations (e.g. min/max pattern matching on X86). 7592 if (Mask.getOpcode() == ISD::SETCC) { 7593 EVT VT = N->getValueType(0); 7594 7595 // Check if any splitting is required. 7596 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7597 TargetLowering::TypeSplitVector) 7598 return SDValue(); 7599 7600 SDValue MaskLo, MaskHi, Lo, Hi; 7601 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7602 7603 SDValue Src0 = MLD->getSrc0(); 7604 SDValue Src0Lo, Src0Hi; 7605 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 7606 7607 EVT LoVT, HiVT; 7608 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 7609 7610 SDValue Chain = MLD->getChain(); 7611 SDValue Ptr = MLD->getBasePtr(); 7612 EVT MemoryVT = MLD->getMemoryVT(); 7613 unsigned Alignment = MLD->getOriginalAlignment(); 7614 7615 // if Alignment is equal to the vector size, 7616 // take the half of it for the second part 7617 unsigned SecondHalfAlignment = 7618 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 7619 Alignment/2 : Alignment; 7620 7621 EVT LoMemVT, HiMemVT; 7622 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7623 7624 MachineMemOperand *MMO = DAG.getMachineFunction(). 7625 getMachineMemOperand(MLD->getPointerInfo(), 7626 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7627 Alignment, MLD->getAAInfo(), MLD->getRanges()); 7628 7629 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 7630 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7631 7632 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7633 MLD->isExpandingLoad()); 7634 unsigned HiOffset = LoMemVT.getStoreSize(); 7635 7636 MMO = DAG.getMachineFunction().getMachineMemOperand( 7637 MLD->getPointerInfo().getWithOffset(HiOffset), 7638 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment, 7639 MLD->getAAInfo(), MLD->getRanges()); 7640 7641 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 7642 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7643 7644 AddToWorklist(Lo.getNode()); 7645 AddToWorklist(Hi.getNode()); 7646 7647 // Build a factor node to remember that this load is independent of the 7648 // other one. 7649 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7650 Hi.getValue(1)); 7651 7652 // Legalized the chain result - switch anything that used the old chain to 7653 // use the new one. 7654 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 7655 7656 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7657 7658 SDValue RetOps[] = { LoadRes, Chain }; 7659 return DAG.getMergeValues(RetOps, DL); 7660 } 7661 return SDValue(); 7662 } 7663 7664 /// A vector select of 2 constant vectors can be simplified to math/logic to 7665 /// avoid a variable select instruction and possibly avoid constant loads. 7666 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 7667 SDValue Cond = N->getOperand(0); 7668 SDValue N1 = N->getOperand(1); 7669 SDValue N2 = N->getOperand(2); 7670 EVT VT = N->getValueType(0); 7671 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 7672 !TLI.convertSelectOfConstantsToMath(VT) || 7673 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 7674 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 7675 return SDValue(); 7676 7677 // Check if we can use the condition value to increment/decrement a single 7678 // constant value. This simplifies a select to an add and removes a constant 7679 // load/materialization from the general case. 7680 bool AllAddOne = true; 7681 bool AllSubOne = true; 7682 unsigned Elts = VT.getVectorNumElements(); 7683 for (unsigned i = 0; i != Elts; ++i) { 7684 SDValue N1Elt = N1.getOperand(i); 7685 SDValue N2Elt = N2.getOperand(i); 7686 if (N1Elt.isUndef() || N2Elt.isUndef()) 7687 continue; 7688 7689 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 7690 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 7691 if (C1 != C2 + 1) 7692 AllAddOne = false; 7693 if (C1 != C2 - 1) 7694 AllSubOne = false; 7695 } 7696 7697 // Further simplifications for the extra-special cases where the constants are 7698 // all 0 or all -1 should be implemented as folds of these patterns. 7699 SDLoc DL(N); 7700 if (AllAddOne || AllSubOne) { 7701 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7702 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7703 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7704 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7705 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7706 } 7707 7708 // The general case for select-of-constants: 7709 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7710 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7711 // leave that to a machine-specific pass. 7712 return SDValue(); 7713 } 7714 7715 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7716 SDValue N0 = N->getOperand(0); 7717 SDValue N1 = N->getOperand(1); 7718 SDValue N2 = N->getOperand(2); 7719 SDLoc DL(N); 7720 7721 // fold (vselect C, X, X) -> X 7722 if (N1 == N2) 7723 return N1; 7724 7725 // Canonicalize integer abs. 7726 // vselect (setg[te] X, 0), X, -X -> 7727 // vselect (setgt X, -1), X, -X -> 7728 // vselect (setl[te] X, 0), -X, X -> 7729 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7730 if (N0.getOpcode() == ISD::SETCC) { 7731 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7732 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7733 bool isAbs = false; 7734 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7735 7736 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7737 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7738 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7739 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7740 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7741 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7742 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7743 7744 if (isAbs) { 7745 EVT VT = LHS.getValueType(); 7746 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7747 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7748 7749 SDValue Shift = DAG.getNode( 7750 ISD::SRA, DL, VT, LHS, 7751 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7752 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7753 AddToWorklist(Shift.getNode()); 7754 AddToWorklist(Add.getNode()); 7755 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7756 } 7757 7758 // If this select has a condition (setcc) with narrower operands than the 7759 // select, try to widen the compare to match the select width. 7760 // TODO: This should be extended to handle any constant. 7761 // TODO: This could be extended to handle non-loading patterns, but that 7762 // requires thorough testing to avoid regressions. 7763 if (isNullConstantOrNullSplatConstant(RHS)) { 7764 EVT NarrowVT = LHS.getValueType(); 7765 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 7766 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 7767 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 7768 unsigned WideWidth = WideVT.getScalarSizeInBits(); 7769 bool IsSigned = isSignedIntSetCC(CC); 7770 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7771 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 7772 SetCCWidth != 1 && SetCCWidth < WideWidth && 7773 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 7774 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 7775 // Both compare operands can be widened for free. The LHS can use an 7776 // extended load, and the RHS is a constant: 7777 // vselect (ext (setcc load(X), C)), N1, N2 --> 7778 // vselect (setcc extload(X), C'), N1, N2 7779 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7780 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 7781 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 7782 EVT WideSetCCVT = getSetCCResultType(WideVT); 7783 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 7784 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 7785 } 7786 } 7787 } 7788 7789 if (SimplifySelectOps(N, N1, N2)) 7790 return SDValue(N, 0); // Don't revisit N. 7791 7792 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7793 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7794 return N1; 7795 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7796 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7797 return N2; 7798 7799 // The ConvertSelectToConcatVector function is assuming both the above 7800 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7801 // and addressed. 7802 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7803 N2.getOpcode() == ISD::CONCAT_VECTORS && 7804 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7805 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7806 return CV; 7807 } 7808 7809 if (SDValue V = foldVSelectOfConstants(N)) 7810 return V; 7811 7812 return SDValue(); 7813 } 7814 7815 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7816 SDValue N0 = N->getOperand(0); 7817 SDValue N1 = N->getOperand(1); 7818 SDValue N2 = N->getOperand(2); 7819 SDValue N3 = N->getOperand(3); 7820 SDValue N4 = N->getOperand(4); 7821 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7822 7823 // fold select_cc lhs, rhs, x, x, cc -> x 7824 if (N2 == N3) 7825 return N2; 7826 7827 // Determine if the condition we're dealing with is constant 7828 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7829 CC, SDLoc(N), false)) { 7830 AddToWorklist(SCC.getNode()); 7831 7832 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7833 if (!SCCC->isNullValue()) 7834 return N2; // cond always true -> true val 7835 else 7836 return N3; // cond always false -> false val 7837 } else if (SCC->isUndef()) { 7838 // When the condition is UNDEF, just return the first operand. This is 7839 // coherent the DAG creation, no setcc node is created in this case 7840 return N2; 7841 } else if (SCC.getOpcode() == ISD::SETCC) { 7842 // Fold to a simpler select_cc 7843 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7844 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7845 SCC.getOperand(2)); 7846 } 7847 } 7848 7849 // If we can fold this based on the true/false value, do so. 7850 if (SimplifySelectOps(N, N2, N3)) 7851 return SDValue(N, 0); // Don't revisit N. 7852 7853 // fold select_cc into other things, such as min/max/abs 7854 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7855 } 7856 7857 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7858 // setcc is very commonly used as an argument to brcond. This pattern 7859 // also lend itself to numerous combines and, as a result, it is desired 7860 // we keep the argument to a brcond as a setcc as much as possible. 7861 bool PreferSetCC = 7862 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 7863 7864 SDValue Combined = SimplifySetCC( 7865 N->getValueType(0), N->getOperand(0), N->getOperand(1), 7866 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 7867 7868 if (!Combined) 7869 return SDValue(); 7870 7871 // If we prefer to have a setcc, and we don't, we'll try our best to 7872 // recreate one using rebuildSetCC. 7873 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 7874 SDValue NewSetCC = rebuildSetCC(Combined); 7875 7876 // We don't have anything interesting to combine to. 7877 if (NewSetCC.getNode() == N) 7878 return SDValue(); 7879 7880 if (NewSetCC) 7881 return NewSetCC; 7882 } 7883 7884 return Combined; 7885 } 7886 7887 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 7888 SDValue LHS = N->getOperand(0); 7889 SDValue RHS = N->getOperand(1); 7890 SDValue Carry = N->getOperand(2); 7891 SDValue Cond = N->getOperand(3); 7892 7893 // If Carry is false, fold to a regular SETCC. 7894 if (isNullConstant(Carry)) 7895 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 7896 7897 return SDValue(); 7898 } 7899 7900 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 7901 /// a build_vector of constants. 7902 /// This function is called by the DAGCombiner when visiting sext/zext/aext 7903 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 7904 /// Vector extends are not folded if operations are legal; this is to 7905 /// avoid introducing illegal build_vector dag nodes. 7906 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 7907 SelectionDAG &DAG, bool LegalTypes, 7908 bool LegalOperations) { 7909 unsigned Opcode = N->getOpcode(); 7910 SDValue N0 = N->getOperand(0); 7911 EVT VT = N->getValueType(0); 7912 7913 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 7914 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 7915 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 7916 && "Expected EXTEND dag node in input!"); 7917 7918 // fold (sext c1) -> c1 7919 // fold (zext c1) -> c1 7920 // fold (aext c1) -> c1 7921 if (isa<ConstantSDNode>(N0)) 7922 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 7923 7924 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 7925 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 7926 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 7927 EVT SVT = VT.getScalarType(); 7928 if (!(VT.isVector() && 7929 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 7930 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 7931 return nullptr; 7932 7933 // We can fold this node into a build_vector. 7934 unsigned VTBits = SVT.getSizeInBits(); 7935 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 7936 SmallVector<SDValue, 8> Elts; 7937 unsigned NumElts = VT.getVectorNumElements(); 7938 SDLoc DL(N); 7939 7940 for (unsigned i=0; i != NumElts; ++i) { 7941 SDValue Op = N0->getOperand(i); 7942 if (Op->isUndef()) { 7943 Elts.push_back(DAG.getUNDEF(SVT)); 7944 continue; 7945 } 7946 7947 SDLoc DL(Op); 7948 // Get the constant value and if needed trunc it to the size of the type. 7949 // Nodes like build_vector might have constants wider than the scalar type. 7950 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 7951 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 7952 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 7953 else 7954 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 7955 } 7956 7957 return DAG.getBuildVector(VT, DL, Elts).getNode(); 7958 } 7959 7960 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 7961 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 7962 // transformation. Returns true if extension are possible and the above 7963 // mentioned transformation is profitable. 7964 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 7965 unsigned ExtOpc, 7966 SmallVectorImpl<SDNode *> &ExtendNodes, 7967 const TargetLowering &TLI) { 7968 bool HasCopyToRegUses = false; 7969 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 7970 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 7971 UE = N0.getNode()->use_end(); 7972 UI != UE; ++UI) { 7973 SDNode *User = *UI; 7974 if (User == N) 7975 continue; 7976 if (UI.getUse().getResNo() != N0.getResNo()) 7977 continue; 7978 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 7979 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 7980 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 7981 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 7982 // Sign bits will be lost after a zext. 7983 return false; 7984 bool Add = false; 7985 for (unsigned i = 0; i != 2; ++i) { 7986 SDValue UseOp = User->getOperand(i); 7987 if (UseOp == N0) 7988 continue; 7989 if (!isa<ConstantSDNode>(UseOp)) 7990 return false; 7991 Add = true; 7992 } 7993 if (Add) 7994 ExtendNodes.push_back(User); 7995 continue; 7996 } 7997 // If truncates aren't free and there are users we can't 7998 // extend, it isn't worthwhile. 7999 if (!isTruncFree) 8000 return false; 8001 // Remember if this value is live-out. 8002 if (User->getOpcode() == ISD::CopyToReg) 8003 HasCopyToRegUses = true; 8004 } 8005 8006 if (HasCopyToRegUses) { 8007 bool BothLiveOut = false; 8008 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8009 UI != UE; ++UI) { 8010 SDUse &Use = UI.getUse(); 8011 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 8012 BothLiveOut = true; 8013 break; 8014 } 8015 } 8016 if (BothLiveOut) 8017 // Both unextended and extended values are live out. There had better be 8018 // a good reason for the transformation. 8019 return ExtendNodes.size(); 8020 } 8021 return true; 8022 } 8023 8024 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 8025 SDValue OrigLoad, SDValue ExtLoad, 8026 ISD::NodeType ExtType) { 8027 // Extend SetCC uses if necessary. 8028 SDLoc DL(ExtLoad); 8029 for (SDNode *SetCC : SetCCs) { 8030 SmallVector<SDValue, 4> Ops; 8031 8032 for (unsigned j = 0; j != 2; ++j) { 8033 SDValue SOp = SetCC->getOperand(j); 8034 if (SOp == OrigLoad) 8035 Ops.push_back(ExtLoad); 8036 else 8037 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 8038 } 8039 8040 Ops.push_back(SetCC->getOperand(2)); 8041 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 8042 } 8043 } 8044 8045 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 8046 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 8047 SDValue N0 = N->getOperand(0); 8048 EVT DstVT = N->getValueType(0); 8049 EVT SrcVT = N0.getValueType(); 8050 8051 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8052 N->getOpcode() == ISD::ZERO_EXTEND) && 8053 "Unexpected node type (not an extend)!"); 8054 8055 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 8056 // For example, on a target with legal v4i32, but illegal v8i32, turn: 8057 // (v8i32 (sext (v8i16 (load x)))) 8058 // into: 8059 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8060 // (v4i32 (sextload (x + 16))))) 8061 // Where uses of the original load, i.e.: 8062 // (v8i16 (load x)) 8063 // are replaced with: 8064 // (v8i16 (truncate 8065 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8066 // (v4i32 (sextload (x + 16))))))) 8067 // 8068 // This combine is only applicable to illegal, but splittable, vectors. 8069 // All legal types, and illegal non-vector types, are handled elsewhere. 8070 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 8071 // 8072 if (N0->getOpcode() != ISD::LOAD) 8073 return SDValue(); 8074 8075 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8076 8077 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 8078 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 8079 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 8080 return SDValue(); 8081 8082 SmallVector<SDNode *, 4> SetCCs; 8083 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 8084 return SDValue(); 8085 8086 ISD::LoadExtType ExtType = 8087 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 8088 8089 // Try to split the vector types to get down to legal types. 8090 EVT SplitSrcVT = SrcVT; 8091 EVT SplitDstVT = DstVT; 8092 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 8093 SplitSrcVT.getVectorNumElements() > 1) { 8094 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 8095 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 8096 } 8097 8098 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 8099 return SDValue(); 8100 8101 SDLoc DL(N); 8102 const unsigned NumSplits = 8103 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 8104 const unsigned Stride = SplitSrcVT.getStoreSize(); 8105 SmallVector<SDValue, 4> Loads; 8106 SmallVector<SDValue, 4> Chains; 8107 8108 SDValue BasePtr = LN0->getBasePtr(); 8109 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 8110 const unsigned Offset = Idx * Stride; 8111 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 8112 8113 SDValue SplitLoad = DAG.getExtLoad( 8114 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 8115 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 8116 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8117 8118 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 8119 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 8120 8121 Loads.push_back(SplitLoad.getValue(0)); 8122 Chains.push_back(SplitLoad.getValue(1)); 8123 } 8124 8125 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 8126 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 8127 8128 // Simplify TF. 8129 AddToWorklist(NewChain.getNode()); 8130 8131 CombineTo(N, NewValue); 8132 8133 // Replace uses of the original load (before extension) 8134 // with a truncate of the concatenated sextloaded vectors. 8135 SDValue Trunc = 8136 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 8137 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 8138 CombineTo(N0.getNode(), Trunc, NewChain); 8139 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8140 } 8141 8142 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8143 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8144 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 8145 assert(N->getOpcode() == ISD::ZERO_EXTEND); 8146 EVT VT = N->getValueType(0); 8147 8148 // and/or/xor 8149 SDValue N0 = N->getOperand(0); 8150 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8151 N0.getOpcode() == ISD::XOR) || 8152 N0.getOperand(1).getOpcode() != ISD::Constant || 8153 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 8154 return SDValue(); 8155 8156 // shl/shr 8157 SDValue N1 = N0->getOperand(0); 8158 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 8159 N1.getOperand(1).getOpcode() != ISD::Constant || 8160 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 8161 return SDValue(); 8162 8163 // load 8164 if (!isa<LoadSDNode>(N1.getOperand(0))) 8165 return SDValue(); 8166 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 8167 EVT MemVT = Load->getMemoryVT(); 8168 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 8169 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 8170 return SDValue(); 8171 8172 8173 // If the shift op is SHL, the logic op must be AND, otherwise the result 8174 // will be wrong. 8175 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 8176 return SDValue(); 8177 8178 if (!N0.hasOneUse() || !N1.hasOneUse()) 8179 return SDValue(); 8180 8181 SmallVector<SDNode*, 4> SetCCs; 8182 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 8183 ISD::ZERO_EXTEND, SetCCs, TLI)) 8184 return SDValue(); 8185 8186 // Actually do the transformation. 8187 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 8188 Load->getChain(), Load->getBasePtr(), 8189 Load->getMemoryVT(), Load->getMemOperand()); 8190 8191 SDLoc DL1(N1); 8192 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 8193 N1.getOperand(1)); 8194 8195 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8196 Mask = Mask.zext(VT.getSizeInBits()); 8197 SDLoc DL0(N0); 8198 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 8199 DAG.getConstant(Mask, DL0, VT)); 8200 8201 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8202 CombineTo(N, And); 8203 if (SDValue(Load, 0).hasOneUse()) { 8204 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 8205 } else { 8206 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 8207 Load->getValueType(0), ExtLoad); 8208 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 8209 } 8210 return SDValue(N,0); // Return N so it doesn't get rechecked! 8211 } 8212 8213 /// If we're narrowing or widening the result of a vector select and the final 8214 /// size is the same size as a setcc (compare) feeding the select, then try to 8215 /// apply the cast operation to the select's operands because matching vector 8216 /// sizes for a select condition and other operands should be more efficient. 8217 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 8218 unsigned CastOpcode = Cast->getOpcode(); 8219 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 8220 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 8221 CastOpcode == ISD::FP_ROUND) && 8222 "Unexpected opcode for vector select narrowing/widening"); 8223 8224 // We only do this transform before legal ops because the pattern may be 8225 // obfuscated by target-specific operations after legalization. Do not create 8226 // an illegal select op, however, because that may be difficult to lower. 8227 EVT VT = Cast->getValueType(0); 8228 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 8229 return SDValue(); 8230 8231 SDValue VSel = Cast->getOperand(0); 8232 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 8233 VSel.getOperand(0).getOpcode() != ISD::SETCC) 8234 return SDValue(); 8235 8236 // Does the setcc have the same vector size as the casted select? 8237 SDValue SetCC = VSel.getOperand(0); 8238 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 8239 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 8240 return SDValue(); 8241 8242 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 8243 SDValue A = VSel.getOperand(1); 8244 SDValue B = VSel.getOperand(2); 8245 SDValue CastA, CastB; 8246 SDLoc DL(Cast); 8247 if (CastOpcode == ISD::FP_ROUND) { 8248 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 8249 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 8250 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 8251 } else { 8252 CastA = DAG.getNode(CastOpcode, DL, VT, A); 8253 CastB = DAG.getNode(CastOpcode, DL, VT, B); 8254 } 8255 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 8256 } 8257 8258 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8259 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8260 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 8261 const TargetLowering &TLI, EVT VT, 8262 bool LegalOperations, SDNode *N, 8263 SDValue N0, ISD::LoadExtType ExtLoadType) { 8264 SDNode *N0Node = N0.getNode(); 8265 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 8266 : ISD::isZEXTLoad(N0Node); 8267 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 8268 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 8269 return {}; 8270 8271 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8272 EVT MemVT = LN0->getMemoryVT(); 8273 if ((LegalOperations || LN0->isVolatile()) && 8274 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 8275 return {}; 8276 8277 SDValue ExtLoad = 8278 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8279 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 8280 Combiner.CombineTo(N, ExtLoad); 8281 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8282 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8283 } 8284 8285 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8286 // Only generate vector extloads when 1) they're legal, and 2) they are 8287 // deemed desirable by the target. 8288 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 8289 const TargetLowering &TLI, EVT VT, 8290 bool LegalOperations, SDNode *N, SDValue N0, 8291 ISD::LoadExtType ExtLoadType, 8292 ISD::NodeType ExtOpc) { 8293 if (!ISD::isNON_EXTLoad(N0.getNode()) || 8294 !ISD::isUNINDEXEDLoad(N0.getNode()) || 8295 ((LegalOperations || VT.isVector() || 8296 cast<LoadSDNode>(N0)->isVolatile()) && 8297 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 8298 return {}; 8299 8300 bool DoXform = true; 8301 SmallVector<SDNode *, 4> SetCCs; 8302 if (!N0.hasOneUse()) 8303 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 8304 if (VT.isVector()) 8305 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 8306 if (!DoXform) 8307 return {}; 8308 8309 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8310 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8311 LN0->getBasePtr(), N0.getValueType(), 8312 LN0->getMemOperand()); 8313 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 8314 // If the load value is used only by N, replace it via CombineTo N. 8315 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 8316 Combiner.CombineTo(N, ExtLoad); 8317 if (NoReplaceTrunc) { 8318 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8319 } else { 8320 SDValue Trunc = 8321 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 8322 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8323 } 8324 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8325 } 8326 8327 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 8328 bool LegalOperations) { 8329 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8330 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 8331 8332 SDValue SetCC = N->getOperand(0); 8333 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 8334 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 8335 return SDValue(); 8336 8337 SDValue X = SetCC.getOperand(0); 8338 SDValue Ones = SetCC.getOperand(1); 8339 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 8340 EVT VT = N->getValueType(0); 8341 EVT XVT = X.getValueType(); 8342 // setge X, C is canonicalized to setgt, so we do not need to match that 8343 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 8344 // not require the 'not' op. 8345 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 8346 // Invert and smear/shift the sign bit: 8347 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 8348 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 8349 SDLoc DL(N); 8350 SDValue NotX = DAG.getNOT(DL, X, VT); 8351 SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT); 8352 auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 8353 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 8354 } 8355 return SDValue(); 8356 } 8357 8358 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 8359 SDValue N0 = N->getOperand(0); 8360 EVT VT = N->getValueType(0); 8361 SDLoc DL(N); 8362 8363 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8364 LegalOperations)) 8365 return SDValue(Res, 0); 8366 8367 // fold (sext (sext x)) -> (sext x) 8368 // fold (sext (aext x)) -> (sext x) 8369 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8370 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 8371 8372 if (N0.getOpcode() == ISD::TRUNCATE) { 8373 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 8374 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 8375 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8376 SDNode *oye = N0.getOperand(0).getNode(); 8377 if (NarrowLoad.getNode() != N0.getNode()) { 8378 CombineTo(N0.getNode(), NarrowLoad); 8379 // CombineTo deleted the truncate, if needed, but not what's under it. 8380 AddToWorklist(oye); 8381 } 8382 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8383 } 8384 8385 // See if the value being truncated is already sign extended. If so, just 8386 // eliminate the trunc/sext pair. 8387 SDValue Op = N0.getOperand(0); 8388 unsigned OpBits = Op.getScalarValueSizeInBits(); 8389 unsigned MidBits = N0.getScalarValueSizeInBits(); 8390 unsigned DestBits = VT.getScalarSizeInBits(); 8391 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 8392 8393 if (OpBits == DestBits) { 8394 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 8395 // bits, it is already ready. 8396 if (NumSignBits > DestBits-MidBits) 8397 return Op; 8398 } else if (OpBits < DestBits) { 8399 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 8400 // bits, just sext from i32. 8401 if (NumSignBits > OpBits-MidBits) 8402 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 8403 } else { 8404 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 8405 // bits, just truncate to i32. 8406 if (NumSignBits > OpBits-MidBits) 8407 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 8408 } 8409 8410 // fold (sext (truncate x)) -> (sextinreg x). 8411 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 8412 N0.getValueType())) { 8413 if (OpBits < DestBits) 8414 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 8415 else if (OpBits > DestBits) 8416 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 8417 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 8418 DAG.getValueType(N0.getValueType())); 8419 } 8420 } 8421 8422 // Try to simplify (sext (load x)). 8423 if (SDValue foldedExt = 8424 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8425 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 8426 return foldedExt; 8427 8428 // fold (sext (load x)) to multiple smaller sextloads. 8429 // Only on illegal but splittable vectors. 8430 if (SDValue ExtLoad = CombineExtLoad(N)) 8431 return ExtLoad; 8432 8433 // Try to simplify (sext (sextload x)). 8434 if (SDValue foldedExt = tryToFoldExtOfExtload( 8435 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 8436 return foldedExt; 8437 8438 // fold (sext (and/or/xor (load x), cst)) -> 8439 // (and/or/xor (sextload x), (sext cst)) 8440 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8441 N0.getOpcode() == ISD::XOR) && 8442 isa<LoadSDNode>(N0.getOperand(0)) && 8443 N0.getOperand(1).getOpcode() == ISD::Constant && 8444 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8445 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8446 EVT MemVT = LN00->getMemoryVT(); 8447 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 8448 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 8449 SmallVector<SDNode*, 4> SetCCs; 8450 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8451 ISD::SIGN_EXTEND, SetCCs, TLI); 8452 if (DoXform) { 8453 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 8454 LN00->getChain(), LN00->getBasePtr(), 8455 LN00->getMemoryVT(), 8456 LN00->getMemOperand()); 8457 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8458 Mask = Mask.sext(VT.getSizeInBits()); 8459 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8460 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8461 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 8462 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8463 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8464 CombineTo(N, And); 8465 // If N0 has multiple uses, change other uses as well. 8466 if (NoReplaceTruncAnd) { 8467 SDValue TruncAnd = 8468 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8469 CombineTo(N0.getNode(), TruncAnd); 8470 } 8471 if (NoReplaceTrunc) { 8472 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8473 } else { 8474 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8475 LN00->getValueType(0), ExtLoad); 8476 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8477 } 8478 return SDValue(N,0); // Return N so it doesn't get rechecked! 8479 } 8480 } 8481 } 8482 8483 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8484 return V; 8485 8486 if (N0.getOpcode() == ISD::SETCC) { 8487 SDValue N00 = N0.getOperand(0); 8488 SDValue N01 = N0.getOperand(1); 8489 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 8490 EVT N00VT = N0.getOperand(0).getValueType(); 8491 8492 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 8493 // Only do this before legalize for now. 8494 if (VT.isVector() && !LegalOperations && 8495 TLI.getBooleanContents(N00VT) == 8496 TargetLowering::ZeroOrNegativeOneBooleanContent) { 8497 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 8498 // of the same size as the compared operands. Only optimize sext(setcc()) 8499 // if this is the case. 8500 EVT SVT = getSetCCResultType(N00VT); 8501 8502 // We know that the # elements of the results is the same as the 8503 // # elements of the compare (and the # elements of the compare result 8504 // for that matter). Check to see that they are the same size. If so, 8505 // we know that the element size of the sext'd result matches the 8506 // element size of the compare operands. 8507 if (VT.getSizeInBits() == SVT.getSizeInBits()) 8508 return DAG.getSetCC(DL, VT, N00, N01, CC); 8509 8510 // If the desired elements are smaller or larger than the source 8511 // elements, we can use a matching integer vector type and then 8512 // truncate/sign extend. 8513 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 8514 if (SVT == MatchingVecType) { 8515 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 8516 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 8517 } 8518 } 8519 8520 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 8521 // Here, T can be 1 or -1, depending on the type of the setcc and 8522 // getBooleanContents(). 8523 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 8524 8525 // To determine the "true" side of the select, we need to know the high bit 8526 // of the value returned by the setcc if it evaluates to true. 8527 // If the type of the setcc is i1, then the true case of the select is just 8528 // sext(i1 1), that is, -1. 8529 // If the type of the setcc is larger (say, i8) then the value of the high 8530 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 8531 // of the appropriate width. 8532 SDValue ExtTrueVal = (SetCCWidth == 1) 8533 ? DAG.getAllOnesConstant(DL, VT) 8534 : DAG.getBoolConstant(true, DL, VT, N00VT); 8535 SDValue Zero = DAG.getConstant(0, DL, VT); 8536 if (SDValue SCC = 8537 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 8538 return SCC; 8539 8540 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 8541 EVT SetCCVT = getSetCCResultType(N00VT); 8542 // Don't do this transform for i1 because there's a select transform 8543 // that would reverse it. 8544 // TODO: We should not do this transform at all without a target hook 8545 // because a sext is likely cheaper than a select? 8546 if (SetCCVT.getScalarSizeInBits() != 1 && 8547 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 8548 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 8549 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 8550 } 8551 } 8552 } 8553 8554 // fold (sext x) -> (zext x) if the sign bit is known zero. 8555 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 8556 DAG.SignBitIsZero(N0)) 8557 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 8558 8559 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8560 return NewVSel; 8561 8562 return SDValue(); 8563 } 8564 8565 // isTruncateOf - If N is a truncate of some other value, return true, record 8566 // the value being truncated in Op and which of Op's bits are zero/one in Known. 8567 // This function computes KnownBits to avoid a duplicated call to 8568 // computeKnownBits in the caller. 8569 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 8570 KnownBits &Known) { 8571 if (N->getOpcode() == ISD::TRUNCATE) { 8572 Op = N->getOperand(0); 8573 DAG.computeKnownBits(Op, Known); 8574 return true; 8575 } 8576 8577 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 8578 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 8579 return false; 8580 8581 SDValue Op0 = N->getOperand(0); 8582 SDValue Op1 = N->getOperand(1); 8583 assert(Op0.getValueType() == Op1.getValueType()); 8584 8585 if (isNullConstant(Op0)) 8586 Op = Op1; 8587 else if (isNullConstant(Op1)) 8588 Op = Op0; 8589 else 8590 return false; 8591 8592 DAG.computeKnownBits(Op, Known); 8593 8594 if (!(Known.Zero | 1).isAllOnesValue()) 8595 return false; 8596 8597 return true; 8598 } 8599 8600 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 8601 SDValue N0 = N->getOperand(0); 8602 EVT VT = N->getValueType(0); 8603 8604 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8605 LegalOperations)) 8606 return SDValue(Res, 0); 8607 8608 // fold (zext (zext x)) -> (zext x) 8609 // fold (zext (aext x)) -> (zext x) 8610 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8611 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 8612 N0.getOperand(0)); 8613 8614 // fold (zext (truncate x)) -> (zext x) or 8615 // (zext (truncate x)) -> (truncate x) 8616 // This is valid when the truncated bits of x are already zero. 8617 // FIXME: We should extend this to work for vectors too. 8618 SDValue Op; 8619 KnownBits Known; 8620 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 8621 APInt TruncatedBits = 8622 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 8623 APInt(Op.getValueSizeInBits(), 0) : 8624 APInt::getBitsSet(Op.getValueSizeInBits(), 8625 N0.getValueSizeInBits(), 8626 std::min(Op.getValueSizeInBits(), 8627 VT.getSizeInBits())); 8628 if (TruncatedBits.isSubsetOf(Known.Zero)) 8629 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8630 } 8631 8632 // fold (zext (truncate x)) -> (and x, mask) 8633 if (N0.getOpcode() == ISD::TRUNCATE) { 8634 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 8635 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 8636 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8637 SDNode *oye = N0.getOperand(0).getNode(); 8638 if (NarrowLoad.getNode() != N0.getNode()) { 8639 CombineTo(N0.getNode(), NarrowLoad); 8640 // CombineTo deleted the truncate, if needed, but not what's under it. 8641 AddToWorklist(oye); 8642 } 8643 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8644 } 8645 8646 EVT SrcVT = N0.getOperand(0).getValueType(); 8647 EVT MinVT = N0.getValueType(); 8648 8649 // Try to mask before the extension to avoid having to generate a larger mask, 8650 // possibly over several sub-vectors. 8651 if (SrcVT.bitsLT(VT) && VT.isVector()) { 8652 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 8653 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 8654 SDValue Op = N0.getOperand(0); 8655 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8656 AddToWorklist(Op.getNode()); 8657 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8658 // Transfer the debug info; the new node is equivalent to N0. 8659 DAG.transferDbgValues(N0, ZExtOrTrunc); 8660 return ZExtOrTrunc; 8661 } 8662 } 8663 8664 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 8665 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8666 AddToWorklist(Op.getNode()); 8667 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8668 // We may safely transfer the debug info describing the truncate node over 8669 // to the equivalent and operation. 8670 DAG.transferDbgValues(N0, And); 8671 return And; 8672 } 8673 } 8674 8675 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 8676 // if either of the casts is not free. 8677 if (N0.getOpcode() == ISD::AND && 8678 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8679 N0.getOperand(1).getOpcode() == ISD::Constant && 8680 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8681 N0.getValueType()) || 8682 !TLI.isZExtFree(N0.getValueType(), VT))) { 8683 SDValue X = N0.getOperand(0).getOperand(0); 8684 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 8685 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8686 Mask = Mask.zext(VT.getSizeInBits()); 8687 SDLoc DL(N); 8688 return DAG.getNode(ISD::AND, DL, VT, 8689 X, DAG.getConstant(Mask, DL, VT)); 8690 } 8691 8692 // Try to simplify (zext (load x)). 8693 if (SDValue foldedExt = 8694 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8695 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 8696 return foldedExt; 8697 8698 // fold (zext (load x)) to multiple smaller zextloads. 8699 // Only on illegal but splittable vectors. 8700 if (SDValue ExtLoad = CombineExtLoad(N)) 8701 return ExtLoad; 8702 8703 // fold (zext (and/or/xor (load x), cst)) -> 8704 // (and/or/xor (zextload x), (zext cst)) 8705 // Unless (and (load x) cst) will match as a zextload already and has 8706 // additional users. 8707 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8708 N0.getOpcode() == ISD::XOR) && 8709 isa<LoadSDNode>(N0.getOperand(0)) && 8710 N0.getOperand(1).getOpcode() == ISD::Constant && 8711 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8712 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8713 EVT MemVT = LN00->getMemoryVT(); 8714 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 8715 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 8716 bool DoXform = true; 8717 SmallVector<SDNode*, 4> SetCCs; 8718 if (!N0.hasOneUse()) { 8719 if (N0.getOpcode() == ISD::AND) { 8720 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 8721 EVT LoadResultTy = AndC->getValueType(0); 8722 EVT ExtVT; 8723 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 8724 DoXform = false; 8725 } 8726 } 8727 if (DoXform) 8728 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8729 ISD::ZERO_EXTEND, SetCCs, TLI); 8730 if (DoXform) { 8731 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 8732 LN00->getChain(), LN00->getBasePtr(), 8733 LN00->getMemoryVT(), 8734 LN00->getMemOperand()); 8735 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8736 Mask = Mask.zext(VT.getSizeInBits()); 8737 SDLoc DL(N); 8738 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8739 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8740 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8741 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8742 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8743 CombineTo(N, And); 8744 // If N0 has multiple uses, change other uses as well. 8745 if (NoReplaceTruncAnd) { 8746 SDValue TruncAnd = 8747 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8748 CombineTo(N0.getNode(), TruncAnd); 8749 } 8750 if (NoReplaceTrunc) { 8751 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8752 } else { 8753 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8754 LN00->getValueType(0), ExtLoad); 8755 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8756 } 8757 return SDValue(N,0); // Return N so it doesn't get rechecked! 8758 } 8759 } 8760 } 8761 8762 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8763 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8764 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 8765 return ZExtLoad; 8766 8767 // Try to simplify (zext (zextload x)). 8768 if (SDValue foldedExt = tryToFoldExtOfExtload( 8769 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 8770 return foldedExt; 8771 8772 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8773 return V; 8774 8775 if (N0.getOpcode() == ISD::SETCC) { 8776 // Only do this before legalize for now. 8777 if (!LegalOperations && VT.isVector() && 8778 N0.getValueType().getVectorElementType() == MVT::i1) { 8779 EVT N00VT = N0.getOperand(0).getValueType(); 8780 if (getSetCCResultType(N00VT) == N0.getValueType()) 8781 return SDValue(); 8782 8783 // We know that the # elements of the results is the same as the # 8784 // elements of the compare (and the # elements of the compare result for 8785 // that matter). Check to see that they are the same size. If so, we know 8786 // that the element size of the sext'd result matches the element size of 8787 // the compare operands. 8788 SDLoc DL(N); 8789 SDValue VecOnes = DAG.getConstant(1, DL, VT); 8790 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 8791 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 8792 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 8793 N0.getOperand(1), N0.getOperand(2)); 8794 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 8795 } 8796 8797 // If the desired elements are smaller or larger than the source 8798 // elements we can use a matching integer vector type and then 8799 // truncate/sign extend. 8800 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8801 SDValue VsetCC = 8802 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 8803 N0.getOperand(1), N0.getOperand(2)); 8804 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 8805 VecOnes); 8806 } 8807 8808 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8809 SDLoc DL(N); 8810 if (SDValue SCC = SimplifySelectCC( 8811 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8812 DAG.getConstant(0, DL, VT), 8813 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8814 return SCC; 8815 } 8816 8817 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 8818 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 8819 isa<ConstantSDNode>(N0.getOperand(1)) && 8820 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 8821 N0.hasOneUse()) { 8822 SDValue ShAmt = N0.getOperand(1); 8823 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8824 if (N0.getOpcode() == ISD::SHL) { 8825 SDValue InnerZExt = N0.getOperand(0); 8826 // If the original shl may be shifting out bits, do not perform this 8827 // transformation. 8828 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 8829 InnerZExt.getOperand(0).getValueSizeInBits(); 8830 if (ShAmtVal > KnownZeroBits) 8831 return SDValue(); 8832 } 8833 8834 SDLoc DL(N); 8835 8836 // Ensure that the shift amount is wide enough for the shifted value. 8837 if (VT.getSizeInBits() >= 256) 8838 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 8839 8840 return DAG.getNode(N0.getOpcode(), DL, VT, 8841 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8842 ShAmt); 8843 } 8844 8845 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8846 return NewVSel; 8847 8848 return SDValue(); 8849 } 8850 8851 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8852 SDValue N0 = N->getOperand(0); 8853 EVT VT = N->getValueType(0); 8854 8855 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8856 LegalOperations)) 8857 return SDValue(Res, 0); 8858 8859 // fold (aext (aext x)) -> (aext x) 8860 // fold (aext (zext x)) -> (zext x) 8861 // fold (aext (sext x)) -> (sext x) 8862 if (N0.getOpcode() == ISD::ANY_EXTEND || 8863 N0.getOpcode() == ISD::ZERO_EXTEND || 8864 N0.getOpcode() == ISD::SIGN_EXTEND) 8865 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8866 8867 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8868 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8869 if (N0.getOpcode() == ISD::TRUNCATE) { 8870 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8871 SDNode *oye = N0.getOperand(0).getNode(); 8872 if (NarrowLoad.getNode() != N0.getNode()) { 8873 CombineTo(N0.getNode(), NarrowLoad); 8874 // CombineTo deleted the truncate, if needed, but not what's under it. 8875 AddToWorklist(oye); 8876 } 8877 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8878 } 8879 } 8880 8881 // fold (aext (truncate x)) 8882 if (N0.getOpcode() == ISD::TRUNCATE) 8883 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8884 8885 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 8886 // if the trunc is not free. 8887 if (N0.getOpcode() == ISD::AND && 8888 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8889 N0.getOperand(1).getOpcode() == ISD::Constant && 8890 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8891 N0.getValueType())) { 8892 SDLoc DL(N); 8893 SDValue X = N0.getOperand(0).getOperand(0); 8894 X = DAG.getAnyExtOrTrunc(X, DL, VT); 8895 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8896 Mask = Mask.zext(VT.getSizeInBits()); 8897 return DAG.getNode(ISD::AND, DL, VT, 8898 X, DAG.getConstant(Mask, DL, VT)); 8899 } 8900 8901 // fold (aext (load x)) -> (aext (truncate (extload x))) 8902 // None of the supported targets knows how to perform load and any_ext 8903 // on vectors in one instruction. We only perform this transformation on 8904 // scalars. 8905 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 8906 ISD::isUNINDEXEDLoad(N0.getNode()) && 8907 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8908 bool DoXform = true; 8909 SmallVector<SDNode*, 4> SetCCs; 8910 if (!N0.hasOneUse()) 8911 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, 8912 TLI); 8913 if (DoXform) { 8914 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8915 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8916 LN0->getChain(), 8917 LN0->getBasePtr(), N0.getValueType(), 8918 LN0->getMemOperand()); 8919 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 8920 // If the load value is used only by N, replace it via CombineTo N. 8921 bool NoReplaceTrunc = N0.hasOneUse(); 8922 CombineTo(N, ExtLoad); 8923 if (NoReplaceTrunc) { 8924 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8925 } else { 8926 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 8927 N0.getValueType(), ExtLoad); 8928 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8929 } 8930 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8931 } 8932 } 8933 8934 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 8935 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 8936 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 8937 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 8938 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 8939 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8940 ISD::LoadExtType ExtType = LN0->getExtensionType(); 8941 EVT MemVT = LN0->getMemoryVT(); 8942 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 8943 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 8944 VT, LN0->getChain(), LN0->getBasePtr(), 8945 MemVT, LN0->getMemOperand()); 8946 CombineTo(N, ExtLoad); 8947 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8948 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8949 } 8950 } 8951 8952 if (N0.getOpcode() == ISD::SETCC) { 8953 // For vectors: 8954 // aext(setcc) -> vsetcc 8955 // aext(setcc) -> truncate(vsetcc) 8956 // aext(setcc) -> aext(vsetcc) 8957 // Only do this before legalize for now. 8958 if (VT.isVector() && !LegalOperations) { 8959 EVT N00VT = N0.getOperand(0).getValueType(); 8960 if (getSetCCResultType(N00VT) == N0.getValueType()) 8961 return SDValue(); 8962 8963 // We know that the # elements of the results is the same as the 8964 // # elements of the compare (and the # elements of the compare result 8965 // for that matter). Check to see that they are the same size. If so, 8966 // we know that the element size of the sext'd result matches the 8967 // element size of the compare operands. 8968 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 8969 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 8970 N0.getOperand(1), 8971 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8972 // If the desired elements are smaller or larger than the source 8973 // elements we can use a matching integer vector type and then 8974 // truncate/any extend 8975 else { 8976 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8977 SDValue VsetCC = 8978 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 8979 N0.getOperand(1), 8980 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8981 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 8982 } 8983 } 8984 8985 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8986 SDLoc DL(N); 8987 if (SDValue SCC = SimplifySelectCC( 8988 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8989 DAG.getConstant(0, DL, VT), 8990 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8991 return SCC; 8992 } 8993 8994 return SDValue(); 8995 } 8996 8997 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 8998 unsigned Opcode = N->getOpcode(); 8999 SDValue N0 = N->getOperand(0); 9000 SDValue N1 = N->getOperand(1); 9001 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 9002 9003 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 9004 if (N0.getOpcode() == Opcode && 9005 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 9006 return N0; 9007 9008 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 9009 N0.getOperand(0).getOpcode() == Opcode) { 9010 // We have an assert, truncate, assert sandwich. Make one stronger assert 9011 // by asserting on the smallest asserted type to the larger source type. 9012 // This eliminates the later assert: 9013 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 9014 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 9015 SDValue BigA = N0.getOperand(0); 9016 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 9017 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 9018 "Asserting zero/sign-extended bits to a type larger than the " 9019 "truncated destination does not provide information"); 9020 9021 SDLoc DL(N); 9022 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 9023 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 9024 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 9025 BigA.getOperand(0), MinAssertVTVal); 9026 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 9027 } 9028 9029 return SDValue(); 9030 } 9031 9032 /// If the result of a wider load is shifted to right of N bits and then 9033 /// truncated to a narrower type and where N is a multiple of number of bits of 9034 /// the narrower type, transform it to a narrower load from address + N / num of 9035 /// bits of new type. Also narrow the load if the result is masked with an AND 9036 /// to effectively produce a smaller type. If the result is to be extended, also 9037 /// fold the extension to form a extending load. 9038 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 9039 unsigned Opc = N->getOpcode(); 9040 9041 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 9042 SDValue N0 = N->getOperand(0); 9043 EVT VT = N->getValueType(0); 9044 EVT ExtVT = VT; 9045 9046 // This transformation isn't valid for vector loads. 9047 if (VT.isVector()) 9048 return SDValue(); 9049 9050 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 9051 // extended to VT. 9052 if (Opc == ISD::SIGN_EXTEND_INREG) { 9053 ExtType = ISD::SEXTLOAD; 9054 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9055 } else if (Opc == ISD::SRL) { 9056 // Another special-case: SRL is basically zero-extending a narrower value, 9057 // or it maybe shifting a higher subword, half or byte into the lowest 9058 // bits. 9059 ExtType = ISD::ZEXTLOAD; 9060 N0 = SDValue(N, 0); 9061 9062 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 9063 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9064 if (!N01 || !LN0) 9065 return SDValue(); 9066 9067 uint64_t ShiftAmt = N01->getZExtValue(); 9068 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 9069 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 9070 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 9071 else 9072 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 9073 VT.getSizeInBits() - ShiftAmt); 9074 } else if (Opc == ISD::AND) { 9075 // An AND with a constant mask is the same as a truncate + zero-extend. 9076 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9077 if (!AndC || !AndC->getAPIntValue().isMask()) 9078 return SDValue(); 9079 9080 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 9081 ExtType = ISD::ZEXTLOAD; 9082 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 9083 } 9084 9085 unsigned ShAmt = 0; 9086 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 9087 SDValue SRL = N0; 9088 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 9089 ShAmt = ConstShift->getZExtValue(); 9090 unsigned EVTBits = ExtVT.getSizeInBits(); 9091 // Is the shift amount a multiple of size of VT? 9092 if ((ShAmt & (EVTBits-1)) == 0) { 9093 N0 = N0.getOperand(0); 9094 // Is the load width a multiple of size of VT? 9095 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 9096 return SDValue(); 9097 } 9098 9099 // At this point, we must have a load or else we can't do the transform. 9100 if (!isa<LoadSDNode>(N0)) return SDValue(); 9101 9102 auto *LN0 = cast<LoadSDNode>(N0); 9103 9104 // Because a SRL must be assumed to *need* to zero-extend the high bits 9105 // (as opposed to anyext the high bits), we can't combine the zextload 9106 // lowering of SRL and an sextload. 9107 if (LN0->getExtensionType() == ISD::SEXTLOAD) 9108 return SDValue(); 9109 9110 // If the shift amount is larger than the input type then we're not 9111 // accessing any of the loaded bytes. If the load was a zextload/extload 9112 // then the result of the shift+trunc is zero/undef (handled elsewhere). 9113 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 9114 return SDValue(); 9115 9116 // If the SRL is only used by a masking AND, we may be able to adjust 9117 // the ExtVT to make the AND redundant. 9118 SDNode *Mask = *(SRL->use_begin()); 9119 if (Mask->getOpcode() == ISD::AND && 9120 isa<ConstantSDNode>(Mask->getOperand(1))) { 9121 const APInt &ShiftMask = 9122 cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue(); 9123 if (ShiftMask.isMask()) { 9124 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 9125 ShiftMask.countTrailingOnes()); 9126 // If the mask is smaller, recompute the type. 9127 if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) && 9128 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 9129 ExtVT = MaskedVT; 9130 } 9131 } 9132 } 9133 } 9134 9135 // If the load is shifted left (and the result isn't shifted back right), 9136 // we can fold the truncate through the shift. 9137 unsigned ShLeftAmt = 0; 9138 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9139 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 9140 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 9141 ShLeftAmt = N01->getZExtValue(); 9142 N0 = N0.getOperand(0); 9143 } 9144 } 9145 9146 // If we haven't found a load, we can't narrow it. 9147 if (!isa<LoadSDNode>(N0)) 9148 return SDValue(); 9149 9150 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9151 if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 9152 return SDValue(); 9153 9154 // For big endian targets, we need to adjust the offset to the pointer to 9155 // load the correct bytes. 9156 if (DAG.getDataLayout().isBigEndian()) { 9157 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 9158 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 9159 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 9160 } 9161 9162 EVT PtrType = N0.getOperand(1).getValueType(); 9163 uint64_t PtrOff = ShAmt / 8; 9164 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 9165 SDLoc DL(LN0); 9166 // The original load itself didn't wrap, so an offset within it doesn't. 9167 SDNodeFlags Flags; 9168 Flags.setNoUnsignedWrap(true); 9169 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 9170 PtrType, LN0->getBasePtr(), 9171 DAG.getConstant(PtrOff, DL, PtrType), 9172 Flags); 9173 AddToWorklist(NewPtr.getNode()); 9174 9175 SDValue Load; 9176 if (ExtType == ISD::NON_EXTLOAD) 9177 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 9178 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9179 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9180 else 9181 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 9182 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 9183 NewAlign, LN0->getMemOperand()->getFlags(), 9184 LN0->getAAInfo()); 9185 9186 // Replace the old load's chain with the new load's chain. 9187 WorklistRemover DeadNodes(*this); 9188 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9189 9190 // Shift the result left, if we've swallowed a left shift. 9191 SDValue Result = Load; 9192 if (ShLeftAmt != 0) { 9193 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 9194 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 9195 ShImmTy = VT; 9196 // If the shift amount is as large as the result size (but, presumably, 9197 // no larger than the source) then the useful bits of the result are 9198 // zero; we can't simply return the shortened shift, because the result 9199 // of that operation is undefined. 9200 SDLoc DL(N0); 9201 if (ShLeftAmt >= VT.getSizeInBits()) 9202 Result = DAG.getConstant(0, DL, VT); 9203 else 9204 Result = DAG.getNode(ISD::SHL, DL, VT, 9205 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 9206 } 9207 9208 // Return the new loaded value. 9209 return Result; 9210 } 9211 9212 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 9213 SDValue N0 = N->getOperand(0); 9214 SDValue N1 = N->getOperand(1); 9215 EVT VT = N->getValueType(0); 9216 EVT EVT = cast<VTSDNode>(N1)->getVT(); 9217 unsigned VTBits = VT.getScalarSizeInBits(); 9218 unsigned EVTBits = EVT.getScalarSizeInBits(); 9219 9220 if (N0.isUndef()) 9221 return DAG.getUNDEF(VT); 9222 9223 // fold (sext_in_reg c1) -> c1 9224 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9225 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 9226 9227 // If the input is already sign extended, just drop the extension. 9228 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 9229 return N0; 9230 9231 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 9232 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 9233 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 9234 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9235 N0.getOperand(0), N1); 9236 9237 // fold (sext_in_reg (sext x)) -> (sext x) 9238 // fold (sext_in_reg (aext x)) -> (sext x) 9239 // if x is small enough. 9240 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 9241 SDValue N00 = N0.getOperand(0); 9242 if (N00.getScalarValueSizeInBits() <= EVTBits && 9243 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9244 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9245 } 9246 9247 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 9248 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 9249 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 9250 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 9251 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 9252 if (!LegalOperations || 9253 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 9254 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 9255 } 9256 9257 // fold (sext_in_reg (zext x)) -> (sext x) 9258 // iff we are extending the source sign bit. 9259 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 9260 SDValue N00 = N0.getOperand(0); 9261 if (N00.getScalarValueSizeInBits() == EVTBits && 9262 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9263 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9264 } 9265 9266 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 9267 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 9268 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 9269 9270 // fold operands of sext_in_reg based on knowledge that the top bits are not 9271 // demanded. 9272 if (SimplifyDemandedBits(SDValue(N, 0))) 9273 return SDValue(N, 0); 9274 9275 // fold (sext_in_reg (load x)) -> (smaller sextload x) 9276 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 9277 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 9278 return NarrowLoad; 9279 9280 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 9281 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 9282 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 9283 if (N0.getOpcode() == ISD::SRL) { 9284 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 9285 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 9286 // We can turn this into an SRA iff the input to the SRL is already sign 9287 // extended enough. 9288 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 9289 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 9290 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 9291 N0.getOperand(0), N0.getOperand(1)); 9292 } 9293 } 9294 9295 // fold (sext_inreg (extload x)) -> (sextload x) 9296 // If sextload is not supported by target, we can only do the combine when 9297 // load has one use. Doing otherwise can block folding the extload with other 9298 // extends that the target does support. 9299 if (ISD::isEXTLoad(N0.getNode()) && 9300 ISD::isUNINDEXEDLoad(N0.getNode()) && 9301 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9302 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 9303 N0.hasOneUse()) || 9304 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9305 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9306 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9307 LN0->getChain(), 9308 LN0->getBasePtr(), EVT, 9309 LN0->getMemOperand()); 9310 CombineTo(N, ExtLoad); 9311 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9312 AddToWorklist(ExtLoad.getNode()); 9313 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9314 } 9315 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 9316 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 9317 N0.hasOneUse() && 9318 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9319 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9320 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9321 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9322 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9323 LN0->getChain(), 9324 LN0->getBasePtr(), EVT, 9325 LN0->getMemOperand()); 9326 CombineTo(N, ExtLoad); 9327 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9328 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9329 } 9330 9331 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 9332 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 9333 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 9334 N0.getOperand(1), false)) 9335 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9336 BSwap, N1); 9337 } 9338 9339 return SDValue(); 9340 } 9341 9342 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 9343 SDValue N0 = N->getOperand(0); 9344 EVT VT = N->getValueType(0); 9345 9346 if (N0.isUndef()) 9347 return DAG.getUNDEF(VT); 9348 9349 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9350 LegalOperations)) 9351 return SDValue(Res, 0); 9352 9353 return SDValue(); 9354 } 9355 9356 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 9357 SDValue N0 = N->getOperand(0); 9358 EVT VT = N->getValueType(0); 9359 9360 if (N0.isUndef()) 9361 return DAG.getUNDEF(VT); 9362 9363 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9364 LegalOperations)) 9365 return SDValue(Res, 0); 9366 9367 return SDValue(); 9368 } 9369 9370 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 9371 SDValue N0 = N->getOperand(0); 9372 EVT VT = N->getValueType(0); 9373 bool isLE = DAG.getDataLayout().isLittleEndian(); 9374 9375 // noop truncate 9376 if (N0.getValueType() == N->getValueType(0)) 9377 return N0; 9378 9379 // fold (truncate (truncate x)) -> (truncate x) 9380 if (N0.getOpcode() == ISD::TRUNCATE) 9381 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9382 9383 // fold (truncate c1) -> c1 9384 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 9385 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 9386 if (C.getNode() != N) 9387 return C; 9388 } 9389 9390 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 9391 if (N0.getOpcode() == ISD::ZERO_EXTEND || 9392 N0.getOpcode() == ISD::SIGN_EXTEND || 9393 N0.getOpcode() == ISD::ANY_EXTEND) { 9394 // if the source is smaller than the dest, we still need an extend. 9395 if (N0.getOperand(0).getValueType().bitsLT(VT)) 9396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 9397 // if the source is larger than the dest, than we just need the truncate. 9398 if (N0.getOperand(0).getValueType().bitsGT(VT)) 9399 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9400 // if the source and dest are the same type, we can drop both the extend 9401 // and the truncate. 9402 return N0.getOperand(0); 9403 } 9404 9405 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 9406 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 9407 return SDValue(); 9408 9409 // Fold extract-and-trunc into a narrow extract. For example: 9410 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 9411 // i32 y = TRUNCATE(i64 x) 9412 // -- becomes -- 9413 // v16i8 b = BITCAST (v2i64 val) 9414 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 9415 // 9416 // Note: We only run this optimization after type legalization (which often 9417 // creates this pattern) and before operation legalization after which 9418 // we need to be more careful about the vector instructions that we generate. 9419 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 9420 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 9421 EVT VecTy = N0.getOperand(0).getValueType(); 9422 EVT ExTy = N0.getValueType(); 9423 EVT TrTy = N->getValueType(0); 9424 9425 unsigned NumElem = VecTy.getVectorNumElements(); 9426 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 9427 9428 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 9429 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 9430 9431 SDValue EltNo = N0->getOperand(1); 9432 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 9433 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9434 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 9435 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 9436 9437 SDLoc DL(N); 9438 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 9439 DAG.getBitcast(NVT, N0.getOperand(0)), 9440 DAG.getConstant(Index, DL, IndexTy)); 9441 } 9442 } 9443 9444 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 9445 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 9446 EVT SrcVT = N0.getValueType(); 9447 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 9448 TLI.isTruncateFree(SrcVT, VT)) { 9449 SDLoc SL(N0); 9450 SDValue Cond = N0.getOperand(0); 9451 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9452 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 9453 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 9454 } 9455 } 9456 9457 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 9458 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9459 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 9460 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 9461 SDValue Amt = N0.getOperand(1); 9462 KnownBits Known; 9463 DAG.computeKnownBits(Amt, Known); 9464 unsigned Size = VT.getScalarSizeInBits(); 9465 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 9466 SDLoc SL(N); 9467 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 9468 9469 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9470 if (AmtVT != Amt.getValueType()) { 9471 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 9472 AddToWorklist(Amt.getNode()); 9473 } 9474 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 9475 } 9476 } 9477 9478 // Fold a series of buildvector, bitcast, and truncate if possible. 9479 // For example fold 9480 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 9481 // (2xi32 (buildvector x, y)). 9482 if (Level == AfterLegalizeVectorOps && VT.isVector() && 9483 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 9484 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 9485 N0.getOperand(0).hasOneUse()) { 9486 SDValue BuildVect = N0.getOperand(0); 9487 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 9488 EVT TruncVecEltTy = VT.getVectorElementType(); 9489 9490 // Check that the element types match. 9491 if (BuildVectEltTy == TruncVecEltTy) { 9492 // Now we only need to compute the offset of the truncated elements. 9493 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 9494 unsigned TruncVecNumElts = VT.getVectorNumElements(); 9495 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 9496 9497 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 9498 "Invalid number of elements"); 9499 9500 SmallVector<SDValue, 8> Opnds; 9501 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 9502 Opnds.push_back(BuildVect.getOperand(i)); 9503 9504 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 9505 } 9506 } 9507 9508 // See if we can simplify the input to this truncate through knowledge that 9509 // only the low bits are being used. 9510 // For example "trunc (or (shl x, 8), y)" // -> trunc y 9511 // Currently we only perform this optimization on scalars because vectors 9512 // may have different active low bits. 9513 if (!VT.isVector()) { 9514 APInt Mask = 9515 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 9516 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 9517 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 9518 } 9519 9520 // fold (truncate (load x)) -> (smaller load x) 9521 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 9522 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 9523 if (SDValue Reduced = ReduceLoadWidth(N)) 9524 return Reduced; 9525 9526 // Handle the case where the load remains an extending load even 9527 // after truncation. 9528 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 9529 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9530 if (!LN0->isVolatile() && 9531 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 9532 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 9533 VT, LN0->getChain(), LN0->getBasePtr(), 9534 LN0->getMemoryVT(), 9535 LN0->getMemOperand()); 9536 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 9537 return NewLoad; 9538 } 9539 } 9540 } 9541 9542 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 9543 // where ... are all 'undef'. 9544 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 9545 SmallVector<EVT, 8> VTs; 9546 SDValue V; 9547 unsigned Idx = 0; 9548 unsigned NumDefs = 0; 9549 9550 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 9551 SDValue X = N0.getOperand(i); 9552 if (!X.isUndef()) { 9553 V = X; 9554 Idx = i; 9555 NumDefs++; 9556 } 9557 // Stop if more than one members are non-undef. 9558 if (NumDefs > 1) 9559 break; 9560 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 9561 VT.getVectorElementType(), 9562 X.getValueType().getVectorNumElements())); 9563 } 9564 9565 if (NumDefs == 0) 9566 return DAG.getUNDEF(VT); 9567 9568 if (NumDefs == 1) { 9569 assert(V.getNode() && "The single defined operand is empty!"); 9570 SmallVector<SDValue, 8> Opnds; 9571 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 9572 if (i != Idx) { 9573 Opnds.push_back(DAG.getUNDEF(VTs[i])); 9574 continue; 9575 } 9576 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 9577 AddToWorklist(NV.getNode()); 9578 Opnds.push_back(NV); 9579 } 9580 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 9581 } 9582 } 9583 9584 // Fold truncate of a bitcast of a vector to an extract of the low vector 9585 // element. 9586 // 9587 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 9588 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 9589 SDValue VecSrc = N0.getOperand(0); 9590 EVT SrcVT = VecSrc.getValueType(); 9591 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 9592 (!LegalOperations || 9593 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 9594 SDLoc SL(N); 9595 9596 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 9597 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 9598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 9599 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 9600 } 9601 } 9602 9603 // Simplify the operands using demanded-bits information. 9604 if (!VT.isVector() && 9605 SimplifyDemandedBits(SDValue(N, 0))) 9606 return SDValue(N, 0); 9607 9608 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 9609 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 9610 // When the adde's carry is not used. 9611 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 9612 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 9613 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 9614 SDLoc SL(N); 9615 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9616 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9617 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 9618 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 9619 } 9620 9621 // fold (truncate (extract_subvector(ext x))) -> 9622 // (extract_subvector x) 9623 // TODO: This can be generalized to cover cases where the truncate and extract 9624 // do not fully cancel each other out. 9625 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 9626 SDValue N00 = N0.getOperand(0); 9627 if (N00.getOpcode() == ISD::SIGN_EXTEND || 9628 N00.getOpcode() == ISD::ZERO_EXTEND || 9629 N00.getOpcode() == ISD::ANY_EXTEND) { 9630 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 9631 VT.getVectorElementType()) 9632 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 9633 N00.getOperand(0), N0.getOperand(1)); 9634 } 9635 } 9636 9637 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 9638 return NewVSel; 9639 9640 return SDValue(); 9641 } 9642 9643 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 9644 SDValue Elt = N->getOperand(i); 9645 if (Elt.getOpcode() != ISD::MERGE_VALUES) 9646 return Elt.getNode(); 9647 return Elt.getOperand(Elt.getResNo()).getNode(); 9648 } 9649 9650 /// build_pair (load, load) -> load 9651 /// if load locations are consecutive. 9652 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 9653 assert(N->getOpcode() == ISD::BUILD_PAIR); 9654 9655 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 9656 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 9657 9658 // A BUILD_PAIR is always having the least significant part in elt 0 and the 9659 // most significant part in elt 1. So when combining into one large load, we 9660 // need to consider the endianness. 9661 if (DAG.getDataLayout().isBigEndian()) 9662 std::swap(LD1, LD2); 9663 9664 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 9665 LD1->getAddressSpace() != LD2->getAddressSpace()) 9666 return SDValue(); 9667 EVT LD1VT = LD1->getValueType(0); 9668 unsigned LD1Bytes = LD1VT.getStoreSize(); 9669 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 9670 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 9671 unsigned Align = LD1->getAlignment(); 9672 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 9673 VT.getTypeForEVT(*DAG.getContext())); 9674 9675 if (NewAlign <= Align && 9676 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 9677 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 9678 LD1->getPointerInfo(), Align); 9679 } 9680 9681 return SDValue(); 9682 } 9683 9684 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 9685 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 9686 // and Lo parts; on big-endian machines it doesn't. 9687 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 9688 } 9689 9690 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 9691 const TargetLowering &TLI) { 9692 // If this is not a bitcast to an FP type or if the target doesn't have 9693 // IEEE754-compliant FP logic, we're done. 9694 EVT VT = N->getValueType(0); 9695 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 9696 return SDValue(); 9697 9698 // TODO: Use splat values for the constant-checking below and remove this 9699 // restriction. 9700 SDValue N0 = N->getOperand(0); 9701 EVT SourceVT = N0.getValueType(); 9702 if (SourceVT.isVector()) 9703 return SDValue(); 9704 9705 unsigned FPOpcode; 9706 APInt SignMask; 9707 switch (N0.getOpcode()) { 9708 case ISD::AND: 9709 FPOpcode = ISD::FABS; 9710 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 9711 break; 9712 case ISD::XOR: 9713 FPOpcode = ISD::FNEG; 9714 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 9715 break; 9716 // TODO: ISD::OR --> ISD::FNABS? 9717 default: 9718 return SDValue(); 9719 } 9720 9721 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 9722 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 9723 SDValue LogicOp0 = N0.getOperand(0); 9724 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9725 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 9726 LogicOp0.getOpcode() == ISD::BITCAST && 9727 LogicOp0->getOperand(0).getValueType() == VT) 9728 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 9729 9730 return SDValue(); 9731 } 9732 9733 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 9734 SDValue N0 = N->getOperand(0); 9735 EVT VT = N->getValueType(0); 9736 9737 if (N0.isUndef()) 9738 return DAG.getUNDEF(VT); 9739 9740 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 9741 // Only do this before legalize, since afterward the target may be depending 9742 // on the bitconvert. 9743 // First check to see if this is all constant. 9744 if (!LegalTypes && 9745 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 9746 VT.isVector()) { 9747 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 9748 9749 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 9750 assert(!DestEltVT.isVector() && 9751 "Element type of vector ValueType must not be vector!"); 9752 if (isSimple) 9753 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 9754 } 9755 9756 // If the input is a constant, let getNode fold it. 9757 // We always need to check that this is just a fp -> int or int -> conversion 9758 // otherwise we will get back N which will confuse the caller into thinking 9759 // we used CombineTo. This can block target combines from running. If we can't 9760 // allowed legal operations, we need to ensure the resulting operation will be 9761 // legal. 9762 // TODO: Maybe we should check that the return value isn't N explicitly? 9763 if ((isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 9764 (!LegalOperations || TLI.isOperationLegal(ISD::ConstantFP, VT))) || 9765 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 9766 (!LegalOperations || TLI.isOperationLegal(ISD::Constant, VT)))) 9767 return DAG.getBitcast(VT, N0); 9768 9769 // (conv (conv x, t1), t2) -> (conv x, t2) 9770 if (N0.getOpcode() == ISD::BITCAST) 9771 return DAG.getBitcast(VT, N0.getOperand(0)); 9772 9773 // fold (conv (load x)) -> (load (conv*)x) 9774 // If the resultant load doesn't need a higher alignment than the original! 9775 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9776 // Do not change the width of a volatile load. 9777 !cast<LoadSDNode>(N0)->isVolatile() && 9778 // Do not remove the cast if the types differ in endian layout. 9779 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 9780 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 9781 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 9782 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 9783 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9784 unsigned OrigAlign = LN0->getAlignment(); 9785 9786 bool Fast = false; 9787 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9788 LN0->getAddressSpace(), OrigAlign, &Fast) && 9789 Fast) { 9790 SDValue Load = 9791 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9792 LN0->getPointerInfo(), OrigAlign, 9793 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9794 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9795 return Load; 9796 } 9797 } 9798 9799 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 9800 return V; 9801 9802 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 9803 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 9804 // 9805 // For ppc_fp128: 9806 // fold (bitcast (fneg x)) -> 9807 // flipbit = signbit 9808 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9809 // 9810 // fold (bitcast (fabs x)) -> 9811 // flipbit = (and (extract_element (bitcast x), 0), signbit) 9812 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9813 // This often reduces constant pool loads. 9814 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 9815 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 9816 N0.getNode()->hasOneUse() && VT.isInteger() && 9817 !VT.isVector() && !N0.getValueType().isVector()) { 9818 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 9819 AddToWorklist(NewConv.getNode()); 9820 9821 SDLoc DL(N); 9822 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9823 assert(VT.getSizeInBits() == 128); 9824 SDValue SignBit = DAG.getConstant( 9825 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 9826 SDValue FlipBit; 9827 if (N0.getOpcode() == ISD::FNEG) { 9828 FlipBit = SignBit; 9829 AddToWorklist(FlipBit.getNode()); 9830 } else { 9831 assert(N0.getOpcode() == ISD::FABS); 9832 SDValue Hi = 9833 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 9834 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9835 SDLoc(NewConv))); 9836 AddToWorklist(Hi.getNode()); 9837 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 9838 AddToWorklist(FlipBit.getNode()); 9839 } 9840 SDValue FlipBits = 9841 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9842 AddToWorklist(FlipBits.getNode()); 9843 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 9844 } 9845 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9846 if (N0.getOpcode() == ISD::FNEG) 9847 return DAG.getNode(ISD::XOR, DL, VT, 9848 NewConv, DAG.getConstant(SignBit, DL, VT)); 9849 assert(N0.getOpcode() == ISD::FABS); 9850 return DAG.getNode(ISD::AND, DL, VT, 9851 NewConv, DAG.getConstant(~SignBit, DL, VT)); 9852 } 9853 9854 // fold (bitconvert (fcopysign cst, x)) -> 9855 // (or (and (bitconvert x), sign), (and cst, (not sign))) 9856 // Note that we don't handle (copysign x, cst) because this can always be 9857 // folded to an fneg or fabs. 9858 // 9859 // For ppc_fp128: 9860 // fold (bitcast (fcopysign cst, x)) -> 9861 // flipbit = (and (extract_element 9862 // (xor (bitcast cst), (bitcast x)), 0), 9863 // signbit) 9864 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 9865 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 9866 isa<ConstantFPSDNode>(N0.getOperand(0)) && 9867 VT.isInteger() && !VT.isVector()) { 9868 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 9869 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 9870 if (isTypeLegal(IntXVT)) { 9871 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 9872 AddToWorklist(X.getNode()); 9873 9874 // If X has a different width than the result/lhs, sext it or truncate it. 9875 unsigned VTWidth = VT.getSizeInBits(); 9876 if (OrigXWidth < VTWidth) { 9877 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 9878 AddToWorklist(X.getNode()); 9879 } else if (OrigXWidth > VTWidth) { 9880 // To get the sign bit in the right place, we have to shift it right 9881 // before truncating. 9882 SDLoc DL(X); 9883 X = DAG.getNode(ISD::SRL, DL, 9884 X.getValueType(), X, 9885 DAG.getConstant(OrigXWidth-VTWidth, DL, 9886 X.getValueType())); 9887 AddToWorklist(X.getNode()); 9888 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 9889 AddToWorklist(X.getNode()); 9890 } 9891 9892 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9893 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 9894 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9895 AddToWorklist(Cst.getNode()); 9896 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 9897 AddToWorklist(X.getNode()); 9898 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 9899 AddToWorklist(XorResult.getNode()); 9900 SDValue XorResult64 = DAG.getNode( 9901 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 9902 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 9903 SDLoc(XorResult))); 9904 AddToWorklist(XorResult64.getNode()); 9905 SDValue FlipBit = 9906 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 9907 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 9908 AddToWorklist(FlipBit.getNode()); 9909 SDValue FlipBits = 9910 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 9911 AddToWorklist(FlipBits.getNode()); 9912 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 9913 } 9914 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 9915 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 9916 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 9917 AddToWorklist(X.getNode()); 9918 9919 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 9920 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 9921 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 9922 AddToWorklist(Cst.getNode()); 9923 9924 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 9925 } 9926 } 9927 9928 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 9929 if (N0.getOpcode() == ISD::BUILD_PAIR) 9930 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 9931 return CombineLD; 9932 9933 // Remove double bitcasts from shuffles - this is often a legacy of 9934 // XformToShuffleWithZero being used to combine bitmaskings (of 9935 // float vectors bitcast to integer vectors) into shuffles. 9936 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 9937 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 9938 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 9939 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 9940 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 9941 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 9942 9943 // If operands are a bitcast, peek through if it casts the original VT. 9944 // If operands are a constant, just bitcast back to original VT. 9945 auto PeekThroughBitcast = [&](SDValue Op) { 9946 if (Op.getOpcode() == ISD::BITCAST && 9947 Op.getOperand(0).getValueType() == VT) 9948 return SDValue(Op.getOperand(0)); 9949 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 9950 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 9951 return DAG.getBitcast(VT, Op); 9952 return SDValue(); 9953 }; 9954 9955 // FIXME: If either input vector is bitcast, try to convert the shuffle to 9956 // the result type of this bitcast. This would eliminate at least one 9957 // bitcast. See the transform in InstCombine. 9958 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 9959 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 9960 if (!(SV0 && SV1)) 9961 return SDValue(); 9962 9963 int MaskScale = 9964 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 9965 SmallVector<int, 8> NewMask; 9966 for (int M : SVN->getMask()) 9967 for (int i = 0; i != MaskScale; ++i) 9968 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 9969 9970 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9971 if (!LegalMask) { 9972 std::swap(SV0, SV1); 9973 ShuffleVectorSDNode::commuteMask(NewMask); 9974 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 9975 } 9976 9977 if (LegalMask) 9978 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 9979 } 9980 9981 return SDValue(); 9982 } 9983 9984 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 9985 EVT VT = N->getValueType(0); 9986 return CombineConsecutiveLoads(N, VT); 9987 } 9988 9989 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 9990 /// operands. DstEltVT indicates the destination element value type. 9991 SDValue DAGCombiner:: 9992 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 9993 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 9994 9995 // If this is already the right type, we're done. 9996 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 9997 9998 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 9999 unsigned DstBitSize = DstEltVT.getSizeInBits(); 10000 10001 // If this is a conversion of N elements of one type to N elements of another 10002 // type, convert each element. This handles FP<->INT cases. 10003 if (SrcBitSize == DstBitSize) { 10004 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10005 BV->getValueType(0).getVectorNumElements()); 10006 10007 // Due to the FP element handling below calling this routine recursively, 10008 // we can end up with a scalar-to-vector node here. 10009 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 10010 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 10011 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 10012 10013 SmallVector<SDValue, 8> Ops; 10014 for (SDValue Op : BV->op_values()) { 10015 // If the vector element type is not legal, the BUILD_VECTOR operands 10016 // are promoted and implicitly truncated. Make that explicit here. 10017 if (Op.getValueType() != SrcEltVT) 10018 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 10019 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 10020 AddToWorklist(Ops.back().getNode()); 10021 } 10022 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 10023 } 10024 10025 // Otherwise, we're growing or shrinking the elements. To avoid having to 10026 // handle annoying details of growing/shrinking FP values, we convert them to 10027 // int first. 10028 if (SrcEltVT.isFloatingPoint()) { 10029 // Convert the input float vector to a int vector where the elements are the 10030 // same sizes. 10031 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 10032 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 10033 SrcEltVT = IntVT; 10034 } 10035 10036 // Now we know the input is an integer vector. If the output is a FP type, 10037 // convert to integer first, then to FP of the right size. 10038 if (DstEltVT.isFloatingPoint()) { 10039 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 10040 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 10041 10042 // Next, convert to FP elements of the same size. 10043 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 10044 } 10045 10046 SDLoc DL(BV); 10047 10048 // Okay, we know the src/dst types are both integers of differing types. 10049 // Handling growing first. 10050 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 10051 if (SrcBitSize < DstBitSize) { 10052 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 10053 10054 SmallVector<SDValue, 8> Ops; 10055 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 10056 i += NumInputsPerOutput) { 10057 bool isLE = DAG.getDataLayout().isLittleEndian(); 10058 APInt NewBits = APInt(DstBitSize, 0); 10059 bool EltIsUndef = true; 10060 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 10061 // Shift the previously computed bits over. 10062 NewBits <<= SrcBitSize; 10063 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 10064 if (Op.isUndef()) continue; 10065 EltIsUndef = false; 10066 10067 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 10068 zextOrTrunc(SrcBitSize).zext(DstBitSize); 10069 } 10070 10071 if (EltIsUndef) 10072 Ops.push_back(DAG.getUNDEF(DstEltVT)); 10073 else 10074 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 10075 } 10076 10077 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 10078 return DAG.getBuildVector(VT, DL, Ops); 10079 } 10080 10081 // Finally, this must be the case where we are shrinking elements: each input 10082 // turns into multiple outputs. 10083 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 10084 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10085 NumOutputsPerInput*BV->getNumOperands()); 10086 SmallVector<SDValue, 8> Ops; 10087 10088 for (const SDValue &Op : BV->op_values()) { 10089 if (Op.isUndef()) { 10090 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 10091 continue; 10092 } 10093 10094 APInt OpVal = cast<ConstantSDNode>(Op)-> 10095 getAPIntValue().zextOrTrunc(SrcBitSize); 10096 10097 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 10098 APInt ThisVal = OpVal.trunc(DstBitSize); 10099 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 10100 OpVal.lshrInPlace(DstBitSize); 10101 } 10102 10103 // For big endian targets, swap the order of the pieces of each element. 10104 if (DAG.getDataLayout().isBigEndian()) 10105 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 10106 } 10107 10108 return DAG.getBuildVector(VT, DL, Ops); 10109 } 10110 10111 static bool isContractable(SDNode *N) { 10112 SDNodeFlags F = N->getFlags(); 10113 return F.hasAllowContract() || F.hasAllowReassociation(); 10114 } 10115 10116 /// Try to perform FMA combining on a given FADD node. 10117 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 10118 SDValue N0 = N->getOperand(0); 10119 SDValue N1 = N->getOperand(1); 10120 EVT VT = N->getValueType(0); 10121 SDLoc SL(N); 10122 10123 const TargetOptions &Options = DAG.getTarget().Options; 10124 10125 // Floating-point multiply-add with intermediate rounding. 10126 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10127 10128 // Floating-point multiply-add without intermediate rounding. 10129 bool HasFMA = 10130 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10131 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10132 10133 // No valid opcode, do not combine. 10134 if (!HasFMAD && !HasFMA) 10135 return SDValue(); 10136 10137 SDNodeFlags Flags = N->getFlags(); 10138 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10139 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10140 CanFuse || HasFMAD); 10141 // If the addition is not contractable, do not combine. 10142 if (!AllowFusionGlobally && !isContractable(N)) 10143 return SDValue(); 10144 10145 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10146 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10147 return SDValue(); 10148 10149 // Always prefer FMAD to FMA for precision. 10150 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10151 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10152 10153 // Is the node an FMUL and contractable either due to global flags or 10154 // SDNodeFlags. 10155 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10156 if (N.getOpcode() != ISD::FMUL) 10157 return false; 10158 return AllowFusionGlobally || isContractable(N.getNode()); 10159 }; 10160 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 10161 // prefer to fold the multiply with fewer uses. 10162 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 10163 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 10164 std::swap(N0, N1); 10165 } 10166 10167 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 10168 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10169 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10170 N0.getOperand(0), N0.getOperand(1), N1, Flags); 10171 } 10172 10173 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 10174 // Note: Commutes FADD operands. 10175 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10176 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10177 N1.getOperand(0), N1.getOperand(1), N0, Flags); 10178 } 10179 10180 // Look through FP_EXTEND nodes to do more combining. 10181 10182 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 10183 if (N0.getOpcode() == ISD::FP_EXTEND) { 10184 SDValue N00 = N0.getOperand(0); 10185 if (isContractableFMUL(N00) && 10186 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10187 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10188 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10189 N00.getOperand(0)), 10190 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10191 N00.getOperand(1)), N1, Flags); 10192 } 10193 } 10194 10195 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 10196 // Note: Commutes FADD operands. 10197 if (N1.getOpcode() == ISD::FP_EXTEND) { 10198 SDValue N10 = N1.getOperand(0); 10199 if (isContractableFMUL(N10) && 10200 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10201 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10202 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10203 N10.getOperand(0)), 10204 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10205 N10.getOperand(1)), N0, Flags); 10206 } 10207 } 10208 10209 // More folding opportunities when target permits. 10210 if (Aggressive) { 10211 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 10212 if (CanFuse && 10213 N0.getOpcode() == PreferredFusedOpcode && 10214 N0.getOperand(2).getOpcode() == ISD::FMUL && 10215 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 10216 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10217 N0.getOperand(0), N0.getOperand(1), 10218 DAG.getNode(PreferredFusedOpcode, SL, VT, 10219 N0.getOperand(2).getOperand(0), 10220 N0.getOperand(2).getOperand(1), 10221 N1, Flags), Flags); 10222 } 10223 10224 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 10225 if (CanFuse && 10226 N1->getOpcode() == PreferredFusedOpcode && 10227 N1.getOperand(2).getOpcode() == ISD::FMUL && 10228 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 10229 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10230 N1.getOperand(0), N1.getOperand(1), 10231 DAG.getNode(PreferredFusedOpcode, SL, VT, 10232 N1.getOperand(2).getOperand(0), 10233 N1.getOperand(2).getOperand(1), 10234 N0, Flags), Flags); 10235 } 10236 10237 10238 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 10239 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 10240 auto FoldFAddFMAFPExtFMul = [&] ( 10241 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10242 SDNodeFlags Flags) { 10243 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 10244 DAG.getNode(PreferredFusedOpcode, SL, VT, 10245 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10246 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10247 Z, Flags), Flags); 10248 }; 10249 if (N0.getOpcode() == PreferredFusedOpcode) { 10250 SDValue N02 = N0.getOperand(2); 10251 if (N02.getOpcode() == ISD::FP_EXTEND) { 10252 SDValue N020 = N02.getOperand(0); 10253 if (isContractableFMUL(N020) && 10254 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10255 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 10256 N020.getOperand(0), N020.getOperand(1), 10257 N1, Flags); 10258 } 10259 } 10260 } 10261 10262 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 10263 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 10264 // FIXME: This turns two single-precision and one double-precision 10265 // operation into two double-precision operations, which might not be 10266 // interesting for all targets, especially GPUs. 10267 auto FoldFAddFPExtFMAFMul = [&] ( 10268 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10269 SDNodeFlags Flags) { 10270 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10271 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 10272 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 10273 DAG.getNode(PreferredFusedOpcode, SL, VT, 10274 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10275 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10276 Z, Flags), Flags); 10277 }; 10278 if (N0.getOpcode() == ISD::FP_EXTEND) { 10279 SDValue N00 = N0.getOperand(0); 10280 if (N00.getOpcode() == PreferredFusedOpcode) { 10281 SDValue N002 = N00.getOperand(2); 10282 if (isContractableFMUL(N002) && 10283 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10284 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 10285 N002.getOperand(0), N002.getOperand(1), 10286 N1, Flags); 10287 } 10288 } 10289 } 10290 10291 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 10292 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 10293 if (N1.getOpcode() == PreferredFusedOpcode) { 10294 SDValue N12 = N1.getOperand(2); 10295 if (N12.getOpcode() == ISD::FP_EXTEND) { 10296 SDValue N120 = N12.getOperand(0); 10297 if (isContractableFMUL(N120) && 10298 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10299 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 10300 N120.getOperand(0), N120.getOperand(1), 10301 N0, Flags); 10302 } 10303 } 10304 } 10305 10306 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 10307 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 10308 // FIXME: This turns two single-precision and one double-precision 10309 // operation into two double-precision operations, which might not be 10310 // interesting for all targets, especially GPUs. 10311 if (N1.getOpcode() == ISD::FP_EXTEND) { 10312 SDValue N10 = N1.getOperand(0); 10313 if (N10.getOpcode() == PreferredFusedOpcode) { 10314 SDValue N102 = N10.getOperand(2); 10315 if (isContractableFMUL(N102) && 10316 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10317 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 10318 N102.getOperand(0), N102.getOperand(1), 10319 N0, Flags); 10320 } 10321 } 10322 } 10323 } 10324 10325 return SDValue(); 10326 } 10327 10328 /// Try to perform FMA combining on a given FSUB node. 10329 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 10330 SDValue N0 = N->getOperand(0); 10331 SDValue N1 = N->getOperand(1); 10332 EVT VT = N->getValueType(0); 10333 SDLoc SL(N); 10334 10335 const TargetOptions &Options = DAG.getTarget().Options; 10336 // Floating-point multiply-add with intermediate rounding. 10337 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10338 10339 // Floating-point multiply-add without intermediate rounding. 10340 bool HasFMA = 10341 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10342 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10343 10344 // No valid opcode, do not combine. 10345 if (!HasFMAD && !HasFMA) 10346 return SDValue(); 10347 10348 const SDNodeFlags Flags = N->getFlags(); 10349 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10350 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10351 CanFuse || HasFMAD); 10352 10353 // If the subtraction is not contractable, do not combine. 10354 if (!AllowFusionGlobally && !isContractable(N)) 10355 return SDValue(); 10356 10357 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10358 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10359 return SDValue(); 10360 10361 // Always prefer FMAD to FMA for precision. 10362 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10363 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10364 10365 // Is the node an FMUL and contractable either due to global flags or 10366 // SDNodeFlags. 10367 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10368 if (N.getOpcode() != ISD::FMUL) 10369 return false; 10370 return AllowFusionGlobally || isContractable(N.getNode()); 10371 }; 10372 10373 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 10374 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10375 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10376 N0.getOperand(0), N0.getOperand(1), 10377 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10378 } 10379 10380 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 10381 // Note: Commutes FSUB operands. 10382 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10383 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10384 DAG.getNode(ISD::FNEG, SL, VT, 10385 N1.getOperand(0)), 10386 N1.getOperand(1), N0, Flags); 10387 } 10388 10389 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 10390 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 10391 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 10392 SDValue N00 = N0.getOperand(0).getOperand(0); 10393 SDValue N01 = N0.getOperand(0).getOperand(1); 10394 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10395 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 10396 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10397 } 10398 10399 // Look through FP_EXTEND nodes to do more combining. 10400 10401 // fold (fsub (fpext (fmul x, y)), z) 10402 // -> (fma (fpext x), (fpext y), (fneg z)) 10403 if (N0.getOpcode() == ISD::FP_EXTEND) { 10404 SDValue N00 = N0.getOperand(0); 10405 if (isContractableFMUL(N00) && 10406 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10407 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10408 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10409 N00.getOperand(0)), 10410 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10411 N00.getOperand(1)), 10412 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10413 } 10414 } 10415 10416 // fold (fsub x, (fpext (fmul y, z))) 10417 // -> (fma (fneg (fpext y)), (fpext z), x) 10418 // Note: Commutes FSUB operands. 10419 if (N1.getOpcode() == ISD::FP_EXTEND) { 10420 SDValue N10 = N1.getOperand(0); 10421 if (isContractableFMUL(N10) && 10422 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10423 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10424 DAG.getNode(ISD::FNEG, SL, VT, 10425 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10426 N10.getOperand(0))), 10427 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10428 N10.getOperand(1)), 10429 N0, Flags); 10430 } 10431 } 10432 10433 // fold (fsub (fpext (fneg (fmul, x, y))), z) 10434 // -> (fneg (fma (fpext x), (fpext y), z)) 10435 // Note: This could be removed with appropriate canonicalization of the 10436 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10437 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10438 // from implementing the canonicalization in visitFSUB. 10439 if (N0.getOpcode() == ISD::FP_EXTEND) { 10440 SDValue N00 = N0.getOperand(0); 10441 if (N00.getOpcode() == ISD::FNEG) { 10442 SDValue N000 = N00.getOperand(0); 10443 if (isContractableFMUL(N000) && 10444 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10445 return DAG.getNode(ISD::FNEG, SL, VT, 10446 DAG.getNode(PreferredFusedOpcode, SL, VT, 10447 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10448 N000.getOperand(0)), 10449 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10450 N000.getOperand(1)), 10451 N1, Flags)); 10452 } 10453 } 10454 } 10455 10456 // fold (fsub (fneg (fpext (fmul, x, y))), z) 10457 // -> (fneg (fma (fpext x)), (fpext y), z) 10458 // Note: This could be removed with appropriate canonicalization of the 10459 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10460 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10461 // from implementing the canonicalization in visitFSUB. 10462 if (N0.getOpcode() == ISD::FNEG) { 10463 SDValue N00 = N0.getOperand(0); 10464 if (N00.getOpcode() == ISD::FP_EXTEND) { 10465 SDValue N000 = N00.getOperand(0); 10466 if (isContractableFMUL(N000) && 10467 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 10468 return DAG.getNode(ISD::FNEG, SL, VT, 10469 DAG.getNode(PreferredFusedOpcode, SL, VT, 10470 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10471 N000.getOperand(0)), 10472 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10473 N000.getOperand(1)), 10474 N1, Flags)); 10475 } 10476 } 10477 } 10478 10479 // More folding opportunities when target permits. 10480 if (Aggressive) { 10481 // fold (fsub (fma x, y, (fmul u, v)), z) 10482 // -> (fma x, y (fma u, v, (fneg z))) 10483 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && 10484 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 10485 N0.getOperand(2)->hasOneUse()) { 10486 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10487 N0.getOperand(0), N0.getOperand(1), 10488 DAG.getNode(PreferredFusedOpcode, SL, VT, 10489 N0.getOperand(2).getOperand(0), 10490 N0.getOperand(2).getOperand(1), 10491 DAG.getNode(ISD::FNEG, SL, VT, 10492 N1), Flags), Flags); 10493 } 10494 10495 // fold (fsub x, (fma y, z, (fmul u, v))) 10496 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 10497 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && 10498 isContractableFMUL(N1.getOperand(2))) { 10499 SDValue N20 = N1.getOperand(2).getOperand(0); 10500 SDValue N21 = N1.getOperand(2).getOperand(1); 10501 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10502 DAG.getNode(ISD::FNEG, SL, VT, 10503 N1.getOperand(0)), 10504 N1.getOperand(1), 10505 DAG.getNode(PreferredFusedOpcode, SL, VT, 10506 DAG.getNode(ISD::FNEG, SL, VT, N20), 10507 N21, N0, Flags), Flags); 10508 } 10509 10510 10511 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 10512 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 10513 if (N0.getOpcode() == PreferredFusedOpcode) { 10514 SDValue N02 = N0.getOperand(2); 10515 if (N02.getOpcode() == ISD::FP_EXTEND) { 10516 SDValue N020 = N02.getOperand(0); 10517 if (isContractableFMUL(N020) && 10518 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10519 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10520 N0.getOperand(0), N0.getOperand(1), 10521 DAG.getNode(PreferredFusedOpcode, SL, VT, 10522 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10523 N020.getOperand(0)), 10524 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10525 N020.getOperand(1)), 10526 DAG.getNode(ISD::FNEG, SL, VT, 10527 N1), Flags), Flags); 10528 } 10529 } 10530 } 10531 10532 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 10533 // -> (fma (fpext x), (fpext y), 10534 // (fma (fpext u), (fpext v), (fneg z))) 10535 // FIXME: This turns two single-precision and one double-precision 10536 // operation into two double-precision operations, which might not be 10537 // interesting for all targets, especially GPUs. 10538 if (N0.getOpcode() == ISD::FP_EXTEND) { 10539 SDValue N00 = N0.getOperand(0); 10540 if (N00.getOpcode() == PreferredFusedOpcode) { 10541 SDValue N002 = N00.getOperand(2); 10542 if (isContractableFMUL(N002) && 10543 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10544 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10545 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10546 N00.getOperand(0)), 10547 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10548 N00.getOperand(1)), 10549 DAG.getNode(PreferredFusedOpcode, SL, VT, 10550 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10551 N002.getOperand(0)), 10552 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10553 N002.getOperand(1)), 10554 DAG.getNode(ISD::FNEG, SL, VT, 10555 N1), Flags), Flags); 10556 } 10557 } 10558 } 10559 10560 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 10561 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 10562 if (N1.getOpcode() == PreferredFusedOpcode && 10563 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 10564 SDValue N120 = N1.getOperand(2).getOperand(0); 10565 if (isContractableFMUL(N120) && 10566 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10567 SDValue N1200 = N120.getOperand(0); 10568 SDValue N1201 = N120.getOperand(1); 10569 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10570 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 10571 N1.getOperand(1), 10572 DAG.getNode(PreferredFusedOpcode, SL, VT, 10573 DAG.getNode(ISD::FNEG, SL, VT, 10574 DAG.getNode(ISD::FP_EXTEND, SL, 10575 VT, N1200)), 10576 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10577 N1201), 10578 N0, Flags), Flags); 10579 } 10580 } 10581 10582 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 10583 // -> (fma (fneg (fpext y)), (fpext z), 10584 // (fma (fneg (fpext u)), (fpext v), x)) 10585 // FIXME: This turns two single-precision and one double-precision 10586 // operation into two double-precision operations, which might not be 10587 // interesting for all targets, especially GPUs. 10588 if (N1.getOpcode() == ISD::FP_EXTEND && 10589 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 10590 SDValue CvtSrc = N1.getOperand(0); 10591 SDValue N100 = CvtSrc.getOperand(0); 10592 SDValue N101 = CvtSrc.getOperand(1); 10593 SDValue N102 = CvtSrc.getOperand(2); 10594 if (isContractableFMUL(N102) && 10595 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 10596 SDValue N1020 = N102.getOperand(0); 10597 SDValue N1021 = N102.getOperand(1); 10598 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10599 DAG.getNode(ISD::FNEG, SL, VT, 10600 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10601 N100)), 10602 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 10603 DAG.getNode(PreferredFusedOpcode, SL, VT, 10604 DAG.getNode(ISD::FNEG, SL, VT, 10605 DAG.getNode(ISD::FP_EXTEND, SL, 10606 VT, N1020)), 10607 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10608 N1021), 10609 N0, Flags), Flags); 10610 } 10611 } 10612 } 10613 10614 return SDValue(); 10615 } 10616 10617 /// Try to perform FMA combining on a given FMUL node based on the distributive 10618 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 10619 /// subtraction instead of addition). 10620 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 10621 SDValue N0 = N->getOperand(0); 10622 SDValue N1 = N->getOperand(1); 10623 EVT VT = N->getValueType(0); 10624 SDLoc SL(N); 10625 const SDNodeFlags Flags = N->getFlags(); 10626 10627 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 10628 10629 const TargetOptions &Options = DAG.getTarget().Options; 10630 10631 // The transforms below are incorrect when x == 0 and y == inf, because the 10632 // intermediate multiplication produces a nan. 10633 if (!Options.NoInfsFPMath) 10634 return SDValue(); 10635 10636 // Floating-point multiply-add without intermediate rounding. 10637 bool HasFMA = 10638 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 10639 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10640 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10641 10642 // Floating-point multiply-add with intermediate rounding. This can result 10643 // in a less precise result due to the changed rounding order. 10644 bool HasFMAD = Options.UnsafeFPMath && 10645 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10646 10647 // No valid opcode, do not combine. 10648 if (!HasFMAD && !HasFMA) 10649 return SDValue(); 10650 10651 // Always prefer FMAD to FMA for precision. 10652 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10653 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10654 10655 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 10656 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 10657 auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10658 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 10659 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 10660 if (XC1 && XC1->isExactlyValue(+1.0)) 10661 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10662 Y, Flags); 10663 if (XC1 && XC1->isExactlyValue(-1.0)) 10664 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10665 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10666 } 10667 return SDValue(); 10668 }; 10669 10670 if (SDValue FMA = FuseFADD(N0, N1, Flags)) 10671 return FMA; 10672 if (SDValue FMA = FuseFADD(N1, N0, Flags)) 10673 return FMA; 10674 10675 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 10676 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 10677 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 10678 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 10679 auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10680 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 10681 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 10682 if (XC0 && XC0->isExactlyValue(+1.0)) 10683 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10684 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10685 Y, Flags); 10686 if (XC0 && XC0->isExactlyValue(-1.0)) 10687 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10688 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10689 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10690 10691 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 10692 if (XC1 && XC1->isExactlyValue(+1.0)) 10693 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10694 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10695 if (XC1 && XC1->isExactlyValue(-1.0)) 10696 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10697 Y, Flags); 10698 } 10699 return SDValue(); 10700 }; 10701 10702 if (SDValue FMA = FuseFSUB(N0, N1, Flags)) 10703 return FMA; 10704 if (SDValue FMA = FuseFSUB(N1, N0, Flags)) 10705 return FMA; 10706 10707 return SDValue(); 10708 } 10709 10710 static bool isFMulNegTwo(SDValue &N) { 10711 if (N.getOpcode() != ISD::FMUL) 10712 return false; 10713 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 10714 return CFP->isExactlyValue(-2.0); 10715 return false; 10716 } 10717 10718 SDValue DAGCombiner::visitFADD(SDNode *N) { 10719 SDValue N0 = N->getOperand(0); 10720 SDValue N1 = N->getOperand(1); 10721 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 10722 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 10723 EVT VT = N->getValueType(0); 10724 SDLoc DL(N); 10725 const TargetOptions &Options = DAG.getTarget().Options; 10726 const SDNodeFlags Flags = N->getFlags(); 10727 10728 // fold vector ops 10729 if (VT.isVector()) 10730 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10731 return FoldedVOp; 10732 10733 // fold (fadd c1, c2) -> c1 + c2 10734 if (N0CFP && N1CFP) 10735 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 10736 10737 // canonicalize constant to RHS 10738 if (N0CFP && !N1CFP) 10739 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 10740 10741 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10742 return NewSel; 10743 10744 // fold (fadd A, (fneg B)) -> (fsub A, B) 10745 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10746 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 10747 return DAG.getNode(ISD::FSUB, DL, VT, N0, 10748 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10749 10750 // fold (fadd (fneg A), B) -> (fsub B, A) 10751 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10752 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 10753 return DAG.getNode(ISD::FSUB, DL, VT, N1, 10754 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 10755 10756 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 10757 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 10758 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 10759 (isFMulNegTwo(N1) && N1.hasOneUse())) { 10760 bool N1IsFMul = isFMulNegTwo(N1); 10761 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 10762 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 10763 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 10764 } 10765 10766 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1); 10767 if (N1C && N1C->isZero()) { 10768 if (N1C->isNegative() || Options.UnsafeFPMath || 10769 Flags.hasNoSignedZeros()) { 10770 // fold (fadd A, 0) -> A 10771 return N0; 10772 } 10773 } 10774 10775 // No FP constant should be created after legalization as Instruction 10776 // Selection pass has a hard time dealing with FP constants. 10777 bool AllowNewConst = (Level < AfterLegalizeDAG); 10778 10779 // If 'unsafe math' or nnan is enabled, fold lots of things. 10780 if ((Options.UnsafeFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 10781 // If allowed, fold (fadd (fneg x), x) -> 0.0 10782 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 10783 return DAG.getConstantFP(0.0, DL, VT); 10784 10785 // If allowed, fold (fadd x, (fneg x)) -> 0.0 10786 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 10787 return DAG.getConstantFP(0.0, DL, VT); 10788 } 10789 10790 // If 'unsafe math' or reassoc and nsz, fold lots of things. 10791 // TODO: break out portions of the transformations below for which Unsafe is 10792 // considered and which do not require both nsz and reassoc 10793 if ((Options.UnsafeFPMath || 10794 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 10795 AllowNewConst) { 10796 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 10797 if (N1CFP && N0.getOpcode() == ISD::FADD && 10798 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10799 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags); 10800 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags); 10801 } 10802 10803 // We can fold chains of FADD's of the same value into multiplications. 10804 // This transform is not safe in general because we are reducing the number 10805 // of rounding steps. 10806 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 10807 if (N0.getOpcode() == ISD::FMUL) { 10808 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10809 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 10810 10811 // (fadd (fmul x, c), x) -> (fmul x, c+1) 10812 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 10813 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10814 DAG.getConstantFP(1.0, DL, VT), Flags); 10815 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 10816 } 10817 10818 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 10819 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 10820 N1.getOperand(0) == N1.getOperand(1) && 10821 N0.getOperand(0) == N1.getOperand(0)) { 10822 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10823 DAG.getConstantFP(2.0, DL, VT), Flags); 10824 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 10825 } 10826 } 10827 10828 if (N1.getOpcode() == ISD::FMUL) { 10829 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10830 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 10831 10832 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 10833 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 10834 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10835 DAG.getConstantFP(1.0, DL, VT), Flags); 10836 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 10837 } 10838 10839 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 10840 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 10841 N0.getOperand(0) == N0.getOperand(1) && 10842 N1.getOperand(0) == N0.getOperand(0)) { 10843 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10844 DAG.getConstantFP(2.0, DL, VT), Flags); 10845 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 10846 } 10847 } 10848 10849 if (N0.getOpcode() == ISD::FADD) { 10850 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10851 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 10852 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 10853 (N0.getOperand(0) == N1)) { 10854 return DAG.getNode(ISD::FMUL, DL, VT, 10855 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 10856 } 10857 } 10858 10859 if (N1.getOpcode() == ISD::FADD) { 10860 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10861 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 10862 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 10863 N1.getOperand(0) == N0) { 10864 return DAG.getNode(ISD::FMUL, DL, VT, 10865 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 10866 } 10867 } 10868 10869 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 10870 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 10871 N0.getOperand(0) == N0.getOperand(1) && 10872 N1.getOperand(0) == N1.getOperand(1) && 10873 N0.getOperand(0) == N1.getOperand(0)) { 10874 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 10875 DAG.getConstantFP(4.0, DL, VT), Flags); 10876 } 10877 } 10878 } // enable-unsafe-fp-math 10879 10880 // FADD -> FMA combines: 10881 if (SDValue Fused = visitFADDForFMACombine(N)) { 10882 AddToWorklist(Fused.getNode()); 10883 return Fused; 10884 } 10885 return SDValue(); 10886 } 10887 10888 SDValue DAGCombiner::visitFSUB(SDNode *N) { 10889 SDValue N0 = N->getOperand(0); 10890 SDValue N1 = N->getOperand(1); 10891 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10892 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10893 EVT VT = N->getValueType(0); 10894 SDLoc DL(N); 10895 const TargetOptions &Options = DAG.getTarget().Options; 10896 const SDNodeFlags Flags = N->getFlags(); 10897 10898 // fold vector ops 10899 if (VT.isVector()) 10900 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10901 return FoldedVOp; 10902 10903 // fold (fsub c1, c2) -> c1-c2 10904 if (N0CFP && N1CFP) 10905 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 10906 10907 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10908 return NewSel; 10909 10910 // (fsub A, 0) -> A 10911 if (N1CFP && N1CFP->isZero()) { 10912 if (!N1CFP->isNegative() || Options.UnsafeFPMath || 10913 Flags.hasNoSignedZeros()) { 10914 return N0; 10915 } 10916 } 10917 10918 if (N0 == N1) { 10919 // (fsub x, x) -> 0.0 10920 if (Options.UnsafeFPMath || Flags.hasNoNaNs()) 10921 return DAG.getConstantFP(0.0f, DL, VT); 10922 } 10923 10924 // (fsub 0, B) -> -B 10925 if (N0CFP && N0CFP->isZero()) { 10926 if (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) { 10927 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10928 return GetNegatedExpression(N1, DAG, LegalOperations); 10929 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10930 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 10931 } 10932 } 10933 10934 // fold (fsub A, (fneg B)) -> (fadd A, B) 10935 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 10936 return DAG.getNode(ISD::FADD, DL, VT, N0, 10937 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10938 10939 // If 'unsafe math' is enabled, fold lots of things. 10940 if (Options.UnsafeFPMath) { 10941 // (fsub x, (fadd x, y)) -> (fneg y) 10942 // (fsub x, (fadd y, x)) -> (fneg y) 10943 if (N1.getOpcode() == ISD::FADD) { 10944 SDValue N10 = N1->getOperand(0); 10945 SDValue N11 = N1->getOperand(1); 10946 10947 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 10948 return GetNegatedExpression(N11, DAG, LegalOperations); 10949 10950 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 10951 return GetNegatedExpression(N10, DAG, LegalOperations); 10952 } 10953 } 10954 10955 // FSUB -> FMA combines: 10956 if (SDValue Fused = visitFSUBForFMACombine(N)) { 10957 AddToWorklist(Fused.getNode()); 10958 return Fused; 10959 } 10960 10961 return SDValue(); 10962 } 10963 10964 SDValue DAGCombiner::visitFMUL(SDNode *N) { 10965 SDValue N0 = N->getOperand(0); 10966 SDValue N1 = N->getOperand(1); 10967 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10968 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10969 EVT VT = N->getValueType(0); 10970 SDLoc DL(N); 10971 const TargetOptions &Options = DAG.getTarget().Options; 10972 const SDNodeFlags Flags = N->getFlags(); 10973 10974 // fold vector ops 10975 if (VT.isVector()) { 10976 // This just handles C1 * C2 for vectors. Other vector folds are below. 10977 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10978 return FoldedVOp; 10979 } 10980 10981 // fold (fmul c1, c2) -> c1*c2 10982 if (N0CFP && N1CFP) 10983 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 10984 10985 // canonicalize constant to RHS 10986 if (isConstantFPBuildVectorOrConstantFP(N0) && 10987 !isConstantFPBuildVectorOrConstantFP(N1)) 10988 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 10989 10990 // fold (fmul A, 1.0) -> A 10991 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10992 return N0; 10993 10994 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10995 return NewSel; 10996 10997 if (Options.UnsafeFPMath || 10998 (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) { 10999 // fold (fmul A, 0) -> 0 11000 if (N1CFP && N1CFP->isZero()) 11001 return N1; 11002 } 11003 11004 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 11005 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 11006 if (N0.getOpcode() == ISD::FMUL) { 11007 // Fold scalars or any vector constants (not just splats). 11008 // This fold is done in general by InstCombine, but extra fmul insts 11009 // may have been generated during lowering. 11010 SDValue N00 = N0.getOperand(0); 11011 SDValue N01 = N0.getOperand(1); 11012 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 11013 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 11014 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 11015 11016 // Check 1: Make sure that the first operand of the inner multiply is NOT 11017 // a constant. Otherwise, we may induce infinite looping. 11018 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 11019 // Check 2: Make sure that the second operand of the inner multiply and 11020 // the second operand of the outer multiply are constants. 11021 if ((N1CFP && isConstOrConstSplatFP(N01)) || 11022 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 11023 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 11024 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 11025 } 11026 } 11027 } 11028 11029 // Match a special-case: we convert X * 2.0 into fadd. 11030 // fmul (fadd X, X), C -> fmul X, 2.0 * C 11031 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 11032 N0.getOperand(0) == N0.getOperand(1)) { 11033 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 11034 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 11035 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 11036 } 11037 } 11038 11039 // fold (fmul X, 2.0) -> (fadd X, X) 11040 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 11041 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 11042 11043 // fold (fmul X, -1.0) -> (fneg X) 11044 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 11045 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11046 return DAG.getNode(ISD::FNEG, DL, VT, N0); 11047 11048 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 11049 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11050 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11051 // Both can be negated for free, check to see if at least one is cheaper 11052 // negated. 11053 if (LHSNeg == 2 || RHSNeg == 2) 11054 return DAG.getNode(ISD::FMUL, DL, VT, 11055 GetNegatedExpression(N0, DAG, LegalOperations), 11056 GetNegatedExpression(N1, DAG, LegalOperations), 11057 Flags); 11058 } 11059 } 11060 11061 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 11062 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 11063 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 11064 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 11065 TLI.isOperationLegal(ISD::FABS, VT)) { 11066 SDValue Select = N0, X = N1; 11067 if (Select.getOpcode() != ISD::SELECT) 11068 std::swap(Select, X); 11069 11070 SDValue Cond = Select.getOperand(0); 11071 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 11072 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 11073 11074 if (TrueOpnd && FalseOpnd && 11075 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 11076 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 11077 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 11078 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 11079 switch (CC) { 11080 default: break; 11081 case ISD::SETOLT: 11082 case ISD::SETULT: 11083 case ISD::SETOLE: 11084 case ISD::SETULE: 11085 case ISD::SETLT: 11086 case ISD::SETLE: 11087 std::swap(TrueOpnd, FalseOpnd); 11088 LLVM_FALLTHROUGH; 11089 case ISD::SETOGT: 11090 case ISD::SETUGT: 11091 case ISD::SETOGE: 11092 case ISD::SETUGE: 11093 case ISD::SETGT: 11094 case ISD::SETGE: 11095 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 11096 TLI.isOperationLegal(ISD::FNEG, VT)) 11097 return DAG.getNode(ISD::FNEG, DL, VT, 11098 DAG.getNode(ISD::FABS, DL, VT, X)); 11099 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 11100 return DAG.getNode(ISD::FABS, DL, VT, X); 11101 11102 break; 11103 } 11104 } 11105 } 11106 11107 // FMUL -> FMA combines: 11108 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 11109 AddToWorklist(Fused.getNode()); 11110 return Fused; 11111 } 11112 11113 return SDValue(); 11114 } 11115 11116 SDValue DAGCombiner::visitFMA(SDNode *N) { 11117 SDValue N0 = N->getOperand(0); 11118 SDValue N1 = N->getOperand(1); 11119 SDValue N2 = N->getOperand(2); 11120 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11121 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11122 EVT VT = N->getValueType(0); 11123 SDLoc DL(N); 11124 const TargetOptions &Options = DAG.getTarget().Options; 11125 11126 // FMA nodes have flags that propagate to the created nodes. 11127 const SDNodeFlags Flags = N->getFlags(); 11128 bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N); 11129 11130 // Constant fold FMA. 11131 if (isa<ConstantFPSDNode>(N0) && 11132 isa<ConstantFPSDNode>(N1) && 11133 isa<ConstantFPSDNode>(N2)) { 11134 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 11135 } 11136 11137 if (UnsafeFPMath) { 11138 if (N0CFP && N0CFP->isZero()) 11139 return N2; 11140 if (N1CFP && N1CFP->isZero()) 11141 return N2; 11142 } 11143 // TODO: The FMA node should have flags that propagate to these nodes. 11144 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11145 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 11146 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11147 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 11148 11149 // Canonicalize (fma c, x, y) -> (fma x, c, y) 11150 if (isConstantFPBuildVectorOrConstantFP(N0) && 11151 !isConstantFPBuildVectorOrConstantFP(N1)) 11152 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 11153 11154 if (UnsafeFPMath) { 11155 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 11156 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 11157 isConstantFPBuildVectorOrConstantFP(N1) && 11158 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 11159 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11160 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 11161 Flags), Flags); 11162 } 11163 11164 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 11165 if (N0.getOpcode() == ISD::FMUL && 11166 isConstantFPBuildVectorOrConstantFP(N1) && 11167 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 11168 return DAG.getNode(ISD::FMA, DL, VT, 11169 N0.getOperand(0), 11170 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 11171 Flags), 11172 N2); 11173 } 11174 } 11175 11176 // (fma x, 1, y) -> (fadd x, y) 11177 // (fma x, -1, y) -> (fadd (fneg x), y) 11178 if (N1CFP) { 11179 if (N1CFP->isExactlyValue(1.0)) 11180 // TODO: The FMA node should have flags that propagate to this node. 11181 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 11182 11183 if (N1CFP->isExactlyValue(-1.0) && 11184 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 11185 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 11186 AddToWorklist(RHSNeg.getNode()); 11187 // TODO: The FMA node should have flags that propagate to this node. 11188 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 11189 } 11190 11191 // fma (fneg x), K, y -> fma x -K, y 11192 if (N0.getOpcode() == ISD::FNEG && 11193 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 11194 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 11195 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 11196 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 11197 } 11198 } 11199 11200 if (UnsafeFPMath) { 11201 // (fma x, c, x) -> (fmul x, (c+1)) 11202 if (N1CFP && N0 == N2) { 11203 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11204 DAG.getNode(ISD::FADD, DL, VT, N1, 11205 DAG.getConstantFP(1.0, DL, VT), Flags), 11206 Flags); 11207 } 11208 11209 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 11210 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 11211 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11212 DAG.getNode(ISD::FADD, DL, VT, N1, 11213 DAG.getConstantFP(-1.0, DL, VT), Flags), 11214 Flags); 11215 } 11216 } 11217 11218 return SDValue(); 11219 } 11220 11221 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11222 // reciprocal. 11223 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 11224 // Notice that this is not always beneficial. One reason is different targets 11225 // may have different costs for FDIV and FMUL, so sometimes the cost of two 11226 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 11227 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 11228 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 11229 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 11230 const SDNodeFlags Flags = N->getFlags(); 11231 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 11232 return SDValue(); 11233 11234 // Skip if current node is a reciprocal. 11235 SDValue N0 = N->getOperand(0); 11236 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11237 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11238 return SDValue(); 11239 11240 // Exit early if the target does not want this transform or if there can't 11241 // possibly be enough uses of the divisor to make the transform worthwhile. 11242 SDValue N1 = N->getOperand(1); 11243 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 11244 if (!MinUses || N1->use_size() < MinUses) 11245 return SDValue(); 11246 11247 // Find all FDIV users of the same divisor. 11248 // Use a set because duplicates may be present in the user list. 11249 SetVector<SDNode *> Users; 11250 for (auto *U : N1->uses()) { 11251 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 11252 // This division is eligible for optimization only if global unsafe math 11253 // is enabled or if this division allows reciprocal formation. 11254 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 11255 Users.insert(U); 11256 } 11257 } 11258 11259 // Now that we have the actual number of divisor uses, make sure it meets 11260 // the minimum threshold specified by the target. 11261 if (Users.size() < MinUses) 11262 return SDValue(); 11263 11264 EVT VT = N->getValueType(0); 11265 SDLoc DL(N); 11266 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 11267 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 11268 11269 // Dividend / Divisor -> Dividend * Reciprocal 11270 for (auto *U : Users) { 11271 SDValue Dividend = U->getOperand(0); 11272 if (Dividend != FPOne) { 11273 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 11274 Reciprocal, Flags); 11275 CombineTo(U, NewNode); 11276 } else if (U != Reciprocal.getNode()) { 11277 // In the absence of fast-math-flags, this user node is always the 11278 // same node as Reciprocal, but with FMF they may be different nodes. 11279 CombineTo(U, Reciprocal); 11280 } 11281 } 11282 return SDValue(N, 0); // N was replaced. 11283 } 11284 11285 SDValue DAGCombiner::visitFDIV(SDNode *N) { 11286 SDValue N0 = N->getOperand(0); 11287 SDValue N1 = N->getOperand(1); 11288 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11289 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11290 EVT VT = N->getValueType(0); 11291 SDLoc DL(N); 11292 const TargetOptions &Options = DAG.getTarget().Options; 11293 SDNodeFlags Flags = N->getFlags(); 11294 11295 // fold vector ops 11296 if (VT.isVector()) 11297 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11298 return FoldedVOp; 11299 11300 // fold (fdiv c1, c2) -> c1/c2 11301 if (N0CFP && N1CFP) 11302 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 11303 11304 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11305 return NewSel; 11306 11307 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 11308 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 11309 if (N1CFP) { 11310 // Compute the reciprocal 1.0 / c2. 11311 const APFloat &N1APF = N1CFP->getValueAPF(); 11312 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 11313 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 11314 // Only do the transform if the reciprocal is a legal fp immediate that 11315 // isn't too nasty (eg NaN, denormal, ...). 11316 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 11317 (!LegalOperations || 11318 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 11319 // backend)... we should handle this gracefully after Legalize. 11320 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 11321 TLI.isOperationLegal(ISD::ConstantFP, VT) || 11322 TLI.isFPImmLegal(Recip, VT))) 11323 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11324 DAG.getConstantFP(Recip, DL, VT), Flags); 11325 } 11326 11327 // If this FDIV is part of a reciprocal square root, it may be folded 11328 // into a target-specific square root estimate instruction. 11329 if (N1.getOpcode() == ISD::FSQRT) { 11330 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 11331 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11332 } 11333 } else if (N1.getOpcode() == ISD::FP_EXTEND && 11334 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11335 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11336 Flags)) { 11337 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 11338 AddToWorklist(RV.getNode()); 11339 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11340 } 11341 } else if (N1.getOpcode() == ISD::FP_ROUND && 11342 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11343 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11344 Flags)) { 11345 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 11346 AddToWorklist(RV.getNode()); 11347 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11348 } 11349 } else if (N1.getOpcode() == ISD::FMUL) { 11350 // Look through an FMUL. Even though this won't remove the FDIV directly, 11351 // it's still worthwhile to get rid of the FSQRT if possible. 11352 SDValue SqrtOp; 11353 SDValue OtherOp; 11354 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11355 SqrtOp = N1.getOperand(0); 11356 OtherOp = N1.getOperand(1); 11357 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 11358 SqrtOp = N1.getOperand(1); 11359 OtherOp = N1.getOperand(0); 11360 } 11361 if (SqrtOp.getNode()) { 11362 // We found a FSQRT, so try to make this fold: 11363 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 11364 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 11365 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 11366 AddToWorklist(RV.getNode()); 11367 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11368 } 11369 } 11370 } 11371 11372 // Fold into a reciprocal estimate and multiply instead of a real divide. 11373 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 11374 AddToWorklist(RV.getNode()); 11375 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11376 } 11377 } 11378 11379 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 11380 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11381 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11382 // Both can be negated for free, check to see if at least one is cheaper 11383 // negated. 11384 if (LHSNeg == 2 || RHSNeg == 2) 11385 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 11386 GetNegatedExpression(N0, DAG, LegalOperations), 11387 GetNegatedExpression(N1, DAG, LegalOperations), 11388 Flags); 11389 } 11390 } 11391 11392 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 11393 return CombineRepeatedDivisors; 11394 11395 return SDValue(); 11396 } 11397 11398 SDValue DAGCombiner::visitFREM(SDNode *N) { 11399 SDValue N0 = N->getOperand(0); 11400 SDValue N1 = N->getOperand(1); 11401 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11402 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11403 EVT VT = N->getValueType(0); 11404 11405 // fold (frem c1, c2) -> fmod(c1,c2) 11406 if (N0CFP && N1CFP) 11407 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 11408 11409 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11410 return NewSel; 11411 11412 return SDValue(); 11413 } 11414 11415 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 11416 SDNodeFlags Flags = N->getFlags(); 11417 if (!DAG.getTarget().Options.UnsafeFPMath && 11418 !Flags.hasApproximateFuncs()) 11419 return SDValue(); 11420 11421 SDValue N0 = N->getOperand(0); 11422 if (TLI.isFsqrtCheap(N0, DAG)) 11423 return SDValue(); 11424 11425 // FSQRT nodes have flags that propagate to the created nodes. 11426 return buildSqrtEstimate(N0, Flags); 11427 } 11428 11429 /// copysign(x, fp_extend(y)) -> copysign(x, y) 11430 /// copysign(x, fp_round(y)) -> copysign(x, y) 11431 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 11432 SDValue N1 = N->getOperand(1); 11433 if ((N1.getOpcode() == ISD::FP_EXTEND || 11434 N1.getOpcode() == ISD::FP_ROUND)) { 11435 // Do not optimize out type conversion of f128 type yet. 11436 // For some targets like x86_64, configuration is changed to keep one f128 11437 // value in one SSE register, but instruction selection cannot handle 11438 // FCOPYSIGN on SSE registers yet. 11439 EVT N1VT = N1->getValueType(0); 11440 EVT N1Op0VT = N1->getOperand(0).getValueType(); 11441 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 11442 } 11443 return false; 11444 } 11445 11446 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 11447 SDValue N0 = N->getOperand(0); 11448 SDValue N1 = N->getOperand(1); 11449 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11450 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11451 EVT VT = N->getValueType(0); 11452 11453 if (N0CFP && N1CFP) // Constant fold 11454 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 11455 11456 if (N1CFP) { 11457 const APFloat &V = N1CFP->getValueAPF(); 11458 // copysign(x, c1) -> fabs(x) iff ispos(c1) 11459 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 11460 if (!V.isNegative()) { 11461 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 11462 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11463 } else { 11464 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11465 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 11466 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 11467 } 11468 } 11469 11470 // copysign(fabs(x), y) -> copysign(x, y) 11471 // copysign(fneg(x), y) -> copysign(x, y) 11472 // copysign(copysign(x,z), y) -> copysign(x, y) 11473 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 11474 N0.getOpcode() == ISD::FCOPYSIGN) 11475 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 11476 11477 // copysign(x, abs(y)) -> abs(x) 11478 if (N1.getOpcode() == ISD::FABS) 11479 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11480 11481 // copysign(x, copysign(y,z)) -> copysign(x, z) 11482 if (N1.getOpcode() == ISD::FCOPYSIGN) 11483 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 11484 11485 // copysign(x, fp_extend(y)) -> copysign(x, y) 11486 // copysign(x, fp_round(y)) -> copysign(x, y) 11487 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 11488 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 11489 11490 return SDValue(); 11491 } 11492 11493 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 11494 const TargetLowering &TLI) { 11495 // This optimization is guarded by a function attribute because it may produce 11496 // unexpected results. Ie, programs may be relying on the platform-specific 11497 // undefined behavior when the float-to-int conversion overflows. 11498 const Function &F = DAG.getMachineFunction().getFunction(); 11499 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 11500 if (StrictOverflow.getValueAsString().equals("false")) 11501 return SDValue(); 11502 11503 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 11504 // replacing casts with a libcall. We also must be allowed to ignore -0.0 11505 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 11506 // conversions would return +0.0. 11507 // FIXME: We should be able to use node-level FMF here. 11508 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 11509 EVT VT = N->getValueType(0); 11510 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 11511 !DAG.getTarget().Options.NoSignedZerosFPMath) 11512 return SDValue(); 11513 11514 // fptosi/fptoui round towards zero, so converting from FP to integer and 11515 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 11516 SDValue N0 = N->getOperand(0); 11517 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 11518 N0.getOperand(0).getValueType() == VT) 11519 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11520 11521 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 11522 N0.getOperand(0).getValueType() == VT) 11523 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11524 11525 return SDValue(); 11526 } 11527 11528 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 11529 SDValue N0 = N->getOperand(0); 11530 EVT VT = N->getValueType(0); 11531 EVT OpVT = N0.getValueType(); 11532 11533 // fold (sint_to_fp c1) -> c1fp 11534 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11535 // ...but only if the target supports immediate floating-point values 11536 (!LegalOperations || 11537 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11538 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11539 11540 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 11541 // but UINT_TO_FP is legal on this target, try to convert. 11542 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 11543 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 11544 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 11545 if (DAG.SignBitIsZero(N0)) 11546 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11547 } 11548 11549 // The next optimizations are desirable only if SELECT_CC can be lowered. 11550 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11551 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11552 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 11553 !VT.isVector() && 11554 (!LegalOperations || 11555 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11556 SDLoc DL(N); 11557 SDValue Ops[] = 11558 { N0.getOperand(0), N0.getOperand(1), 11559 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11560 N0.getOperand(2) }; 11561 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11562 } 11563 11564 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 11565 // (select_cc x, y, 1.0, 0.0,, cc) 11566 if (N0.getOpcode() == ISD::ZERO_EXTEND && 11567 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 11568 (!LegalOperations || 11569 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11570 SDLoc DL(N); 11571 SDValue Ops[] = 11572 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 11573 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11574 N0.getOperand(0).getOperand(2) }; 11575 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11576 } 11577 } 11578 11579 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11580 return FTrunc; 11581 11582 return SDValue(); 11583 } 11584 11585 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 11586 SDValue N0 = N->getOperand(0); 11587 EVT VT = N->getValueType(0); 11588 EVT OpVT = N0.getValueType(); 11589 11590 // fold (uint_to_fp c1) -> c1fp 11591 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11592 // ...but only if the target supports immediate floating-point values 11593 (!LegalOperations || 11594 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11595 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11596 11597 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 11598 // but SINT_TO_FP is legal on this target, try to convert. 11599 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 11600 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 11601 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 11602 if (DAG.SignBitIsZero(N0)) 11603 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11604 } 11605 11606 // The next optimizations are desirable only if SELECT_CC can be lowered. 11607 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11608 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11609 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 11610 (!LegalOperations || 11611 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11612 SDLoc DL(N); 11613 SDValue Ops[] = 11614 { N0.getOperand(0), N0.getOperand(1), 11615 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11616 N0.getOperand(2) }; 11617 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11618 } 11619 } 11620 11621 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11622 return FTrunc; 11623 11624 return SDValue(); 11625 } 11626 11627 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 11628 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 11629 SDValue N0 = N->getOperand(0); 11630 EVT VT = N->getValueType(0); 11631 11632 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 11633 return SDValue(); 11634 11635 SDValue Src = N0.getOperand(0); 11636 EVT SrcVT = Src.getValueType(); 11637 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 11638 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 11639 11640 // We can safely assume the conversion won't overflow the output range, 11641 // because (for example) (uint8_t)18293.f is undefined behavior. 11642 11643 // Since we can assume the conversion won't overflow, our decision as to 11644 // whether the input will fit in the float should depend on the minimum 11645 // of the input range and output range. 11646 11647 // This means this is also safe for a signed input and unsigned output, since 11648 // a negative input would lead to undefined behavior. 11649 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 11650 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 11651 unsigned ActualSize = std::min(InputSize, OutputSize); 11652 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 11653 11654 // We can only fold away the float conversion if the input range can be 11655 // represented exactly in the float range. 11656 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 11657 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 11658 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 11659 : ISD::ZERO_EXTEND; 11660 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 11661 } 11662 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 11663 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 11664 return DAG.getBitcast(VT, Src); 11665 } 11666 return SDValue(); 11667 } 11668 11669 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 11670 SDValue N0 = N->getOperand(0); 11671 EVT VT = N->getValueType(0); 11672 11673 // fold (fp_to_sint c1fp) -> c1 11674 if (isConstantFPBuildVectorOrConstantFP(N0)) 11675 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 11676 11677 return FoldIntToFPToInt(N, DAG); 11678 } 11679 11680 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 11681 SDValue N0 = N->getOperand(0); 11682 EVT VT = N->getValueType(0); 11683 11684 // fold (fp_to_uint c1fp) -> c1 11685 if (isConstantFPBuildVectorOrConstantFP(N0)) 11686 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 11687 11688 return FoldIntToFPToInt(N, DAG); 11689 } 11690 11691 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 11692 SDValue N0 = N->getOperand(0); 11693 SDValue N1 = N->getOperand(1); 11694 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11695 EVT VT = N->getValueType(0); 11696 11697 // fold (fp_round c1fp) -> c1fp 11698 if (N0CFP) 11699 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 11700 11701 // fold (fp_round (fp_extend x)) -> x 11702 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 11703 return N0.getOperand(0); 11704 11705 // fold (fp_round (fp_round x)) -> (fp_round x) 11706 if (N0.getOpcode() == ISD::FP_ROUND) { 11707 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 11708 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 11709 11710 // Skip this folding if it results in an fp_round from f80 to f16. 11711 // 11712 // f80 to f16 always generates an expensive (and as yet, unimplemented) 11713 // libcall to __truncxfhf2 instead of selecting native f16 conversion 11714 // instructions from f32 or f64. Moreover, the first (value-preserving) 11715 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 11716 // x86. 11717 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 11718 return SDValue(); 11719 11720 // If the first fp_round isn't a value preserving truncation, it might 11721 // introduce a tie in the second fp_round, that wouldn't occur in the 11722 // single-step fp_round we want to fold to. 11723 // In other words, double rounding isn't the same as rounding. 11724 // Also, this is a value preserving truncation iff both fp_round's are. 11725 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 11726 SDLoc DL(N); 11727 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 11728 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 11729 } 11730 } 11731 11732 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 11733 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 11734 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 11735 N0.getOperand(0), N1); 11736 AddToWorklist(Tmp.getNode()); 11737 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 11738 Tmp, N0.getOperand(1)); 11739 } 11740 11741 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11742 return NewVSel; 11743 11744 return SDValue(); 11745 } 11746 11747 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 11748 SDValue N0 = N->getOperand(0); 11749 EVT VT = N->getValueType(0); 11750 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 11751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11752 11753 // fold (fp_round_inreg c1fp) -> c1fp 11754 if (N0CFP && isTypeLegal(EVT)) { 11755 SDLoc DL(N); 11756 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 11757 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 11758 } 11759 11760 return SDValue(); 11761 } 11762 11763 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 11764 SDValue N0 = N->getOperand(0); 11765 EVT VT = N->getValueType(0); 11766 11767 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 11768 if (N->hasOneUse() && 11769 N->use_begin()->getOpcode() == ISD::FP_ROUND) 11770 return SDValue(); 11771 11772 // fold (fp_extend c1fp) -> c1fp 11773 if (isConstantFPBuildVectorOrConstantFP(N0)) 11774 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 11775 11776 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 11777 if (N0.getOpcode() == ISD::FP16_TO_FP && 11778 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 11779 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 11780 11781 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 11782 // value of X. 11783 if (N0.getOpcode() == ISD::FP_ROUND 11784 && N0.getConstantOperandVal(1) == 1) { 11785 SDValue In = N0.getOperand(0); 11786 if (In.getValueType() == VT) return In; 11787 if (VT.bitsLT(In.getValueType())) 11788 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 11789 In, N0.getOperand(1)); 11790 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 11791 } 11792 11793 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 11794 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11795 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 11796 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11797 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 11798 LN0->getChain(), 11799 LN0->getBasePtr(), N0.getValueType(), 11800 LN0->getMemOperand()); 11801 CombineTo(N, ExtLoad); 11802 CombineTo(N0.getNode(), 11803 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 11804 N0.getValueType(), ExtLoad, 11805 DAG.getIntPtrConstant(1, SDLoc(N0))), 11806 ExtLoad.getValue(1)); 11807 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11808 } 11809 11810 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11811 return NewVSel; 11812 11813 return SDValue(); 11814 } 11815 11816 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 11817 SDValue N0 = N->getOperand(0); 11818 EVT VT = N->getValueType(0); 11819 11820 // fold (fceil c1) -> fceil(c1) 11821 if (isConstantFPBuildVectorOrConstantFP(N0)) 11822 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 11823 11824 return SDValue(); 11825 } 11826 11827 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 11828 SDValue N0 = N->getOperand(0); 11829 EVT VT = N->getValueType(0); 11830 11831 // fold (ftrunc c1) -> ftrunc(c1) 11832 if (isConstantFPBuildVectorOrConstantFP(N0)) 11833 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 11834 11835 // fold ftrunc (known rounded int x) -> x 11836 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 11837 // likely to be generated to extract integer from a rounded floating value. 11838 switch (N0.getOpcode()) { 11839 default: break; 11840 case ISD::FRINT: 11841 case ISD::FTRUNC: 11842 case ISD::FNEARBYINT: 11843 case ISD::FFLOOR: 11844 case ISD::FCEIL: 11845 return N0; 11846 } 11847 11848 return SDValue(); 11849 } 11850 11851 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 11852 SDValue N0 = N->getOperand(0); 11853 EVT VT = N->getValueType(0); 11854 11855 // fold (ffloor c1) -> ffloor(c1) 11856 if (isConstantFPBuildVectorOrConstantFP(N0)) 11857 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 11858 11859 return SDValue(); 11860 } 11861 11862 // FIXME: FNEG and FABS have a lot in common; refactor. 11863 SDValue DAGCombiner::visitFNEG(SDNode *N) { 11864 SDValue N0 = N->getOperand(0); 11865 EVT VT = N->getValueType(0); 11866 11867 // Constant fold FNEG. 11868 if (isConstantFPBuildVectorOrConstantFP(N0)) 11869 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 11870 11871 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 11872 &DAG.getTarget().Options)) 11873 return GetNegatedExpression(N0, DAG, LegalOperations); 11874 11875 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 11876 // constant pool values. 11877 if (!TLI.isFNegFree(VT) && 11878 N0.getOpcode() == ISD::BITCAST && 11879 N0.getNode()->hasOneUse()) { 11880 SDValue Int = N0.getOperand(0); 11881 EVT IntVT = Int.getValueType(); 11882 if (IntVT.isInteger() && !IntVT.isVector()) { 11883 APInt SignMask; 11884 if (N0.getValueType().isVector()) { 11885 // For a vector, get a mask such as 0x80... per scalar element 11886 // and splat it. 11887 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 11888 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11889 } else { 11890 // For a scalar, just generate 0x80... 11891 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 11892 } 11893 SDLoc DL0(N0); 11894 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 11895 DAG.getConstant(SignMask, DL0, IntVT)); 11896 AddToWorklist(Int.getNode()); 11897 return DAG.getBitcast(VT, Int); 11898 } 11899 } 11900 11901 // (fneg (fmul c, x)) -> (fmul -c, x) 11902 if (N0.getOpcode() == ISD::FMUL && 11903 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 11904 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 11905 if (CFP1) { 11906 APFloat CVal = CFP1->getValueAPF(); 11907 CVal.changeSign(); 11908 if (Level >= AfterLegalizeDAG && 11909 (TLI.isFPImmLegal(CVal, VT) || 11910 TLI.isOperationLegal(ISD::ConstantFP, VT))) 11911 return DAG.getNode( 11912 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 11913 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 11914 N0->getFlags()); 11915 } 11916 } 11917 11918 return SDValue(); 11919 } 11920 11921 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 11922 SDValue N0 = N->getOperand(0); 11923 SDValue N1 = N->getOperand(1); 11924 EVT VT = N->getValueType(0); 11925 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11926 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11927 11928 if (N0CFP && N1CFP) { 11929 const APFloat &C0 = N0CFP->getValueAPF(); 11930 const APFloat &C1 = N1CFP->getValueAPF(); 11931 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 11932 } 11933 11934 // Canonicalize to constant on RHS. 11935 if (isConstantFPBuildVectorOrConstantFP(N0) && 11936 !isConstantFPBuildVectorOrConstantFP(N1)) 11937 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 11938 11939 return SDValue(); 11940 } 11941 11942 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 11943 SDValue N0 = N->getOperand(0); 11944 SDValue N1 = N->getOperand(1); 11945 EVT VT = N->getValueType(0); 11946 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 11947 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 11948 11949 if (N0CFP && N1CFP) { 11950 const APFloat &C0 = N0CFP->getValueAPF(); 11951 const APFloat &C1 = N1CFP->getValueAPF(); 11952 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 11953 } 11954 11955 // Canonicalize to constant on RHS. 11956 if (isConstantFPBuildVectorOrConstantFP(N0) && 11957 !isConstantFPBuildVectorOrConstantFP(N1)) 11958 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 11959 11960 return SDValue(); 11961 } 11962 11963 SDValue DAGCombiner::visitFABS(SDNode *N) { 11964 SDValue N0 = N->getOperand(0); 11965 EVT VT = N->getValueType(0); 11966 11967 // fold (fabs c1) -> fabs(c1) 11968 if (isConstantFPBuildVectorOrConstantFP(N0)) 11969 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11970 11971 // fold (fabs (fabs x)) -> (fabs x) 11972 if (N0.getOpcode() == ISD::FABS) 11973 return N->getOperand(0); 11974 11975 // fold (fabs (fneg x)) -> (fabs x) 11976 // fold (fabs (fcopysign x, y)) -> (fabs x) 11977 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 11978 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 11979 11980 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 11981 // constant pool values. 11982 if (!TLI.isFAbsFree(VT) && 11983 N0.getOpcode() == ISD::BITCAST && 11984 N0.getNode()->hasOneUse()) { 11985 SDValue Int = N0.getOperand(0); 11986 EVT IntVT = Int.getValueType(); 11987 if (IntVT.isInteger() && !IntVT.isVector()) { 11988 APInt SignMask; 11989 if (N0.getValueType().isVector()) { 11990 // For a vector, get a mask such as 0x7f... per scalar element 11991 // and splat it. 11992 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 11993 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 11994 } else { 11995 // For a scalar, just generate 0x7f... 11996 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 11997 } 11998 SDLoc DL(N0); 11999 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 12000 DAG.getConstant(SignMask, DL, IntVT)); 12001 AddToWorklist(Int.getNode()); 12002 return DAG.getBitcast(N->getValueType(0), Int); 12003 } 12004 } 12005 12006 return SDValue(); 12007 } 12008 12009 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 12010 SDValue Chain = N->getOperand(0); 12011 SDValue N1 = N->getOperand(1); 12012 SDValue N2 = N->getOperand(2); 12013 12014 // If N is a constant we could fold this into a fallthrough or unconditional 12015 // branch. However that doesn't happen very often in normal code, because 12016 // Instcombine/SimplifyCFG should have handled the available opportunities. 12017 // If we did this folding here, it would be necessary to update the 12018 // MachineBasicBlock CFG, which is awkward. 12019 12020 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 12021 // on the target. 12022 if (N1.getOpcode() == ISD::SETCC && 12023 TLI.isOperationLegalOrCustom(ISD::BR_CC, 12024 N1.getOperand(0).getValueType())) { 12025 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12026 Chain, N1.getOperand(2), 12027 N1.getOperand(0), N1.getOperand(1), N2); 12028 } 12029 12030 if (N1.hasOneUse()) { 12031 if (SDValue NewN1 = rebuildSetCC(N1)) 12032 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2); 12033 } 12034 12035 return SDValue(); 12036 } 12037 12038 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 12039 if (N.getOpcode() == ISD::SRL || 12040 (N.getOpcode() == ISD::TRUNCATE && 12041 (N.getOperand(0).hasOneUse() && 12042 N.getOperand(0).getOpcode() == ISD::SRL))) { 12043 // Look pass the truncate. 12044 if (N.getOpcode() == ISD::TRUNCATE) 12045 N = N.getOperand(0); 12046 12047 // Match this pattern so that we can generate simpler code: 12048 // 12049 // %a = ... 12050 // %b = and i32 %a, 2 12051 // %c = srl i32 %b, 1 12052 // brcond i32 %c ... 12053 // 12054 // into 12055 // 12056 // %a = ... 12057 // %b = and i32 %a, 2 12058 // %c = setcc eq %b, 0 12059 // brcond %c ... 12060 // 12061 // This applies only when the AND constant value has one bit set and the 12062 // SRL constant is equal to the log2 of the AND constant. The back-end is 12063 // smart enough to convert the result into a TEST/JMP sequence. 12064 SDValue Op0 = N.getOperand(0); 12065 SDValue Op1 = N.getOperand(1); 12066 12067 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 12068 SDValue AndOp1 = Op0.getOperand(1); 12069 12070 if (AndOp1.getOpcode() == ISD::Constant) { 12071 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 12072 12073 if (AndConst.isPowerOf2() && 12074 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 12075 SDLoc DL(N); 12076 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 12077 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 12078 ISD::SETNE); 12079 } 12080 } 12081 } 12082 } 12083 12084 // Transform br(xor(x, y)) -> br(x != y) 12085 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 12086 if (N.getOpcode() == ISD::XOR) { 12087 // Because we may call this on a speculatively constructed 12088 // SimplifiedSetCC Node, we need to simplify this node first. 12089 // Ideally this should be folded into SimplifySetCC and not 12090 // here. For now, grab a handle to N so we don't lose it from 12091 // replacements interal to the visit. 12092 HandleSDNode XORHandle(N); 12093 while (N.getOpcode() == ISD::XOR) { 12094 SDValue Tmp = visitXOR(N.getNode()); 12095 // No simplification done. 12096 if (!Tmp.getNode()) 12097 break; 12098 // Returning N is form in-visit replacement that may invalidated 12099 // N. Grab value from Handle. 12100 if (Tmp.getNode() == N.getNode()) 12101 N = XORHandle.getValue(); 12102 else // Node simplified. Try simplifying again. 12103 N = Tmp; 12104 } 12105 12106 if (N.getOpcode() != ISD::XOR) 12107 return N; 12108 12109 SDNode *TheXor = N.getNode(); 12110 12111 SDValue Op0 = TheXor->getOperand(0); 12112 SDValue Op1 = TheXor->getOperand(1); 12113 12114 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 12115 bool Equal = false; 12116 if (isOneConstant(Op0) && Op0.hasOneUse() && 12117 Op0.getOpcode() == ISD::XOR) { 12118 TheXor = Op0.getNode(); 12119 Equal = true; 12120 } 12121 12122 EVT SetCCVT = N.getValueType(); 12123 if (LegalTypes) 12124 SetCCVT = getSetCCResultType(SetCCVT); 12125 // Replace the uses of XOR with SETCC 12126 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1, 12127 Equal ? ISD::SETEQ : ISD::SETNE); 12128 } 12129 } 12130 12131 return SDValue(); 12132 } 12133 12134 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 12135 // 12136 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 12137 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 12138 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 12139 12140 // If N is a constant we could fold this into a fallthrough or unconditional 12141 // branch. However that doesn't happen very often in normal code, because 12142 // Instcombine/SimplifyCFG should have handled the available opportunities. 12143 // If we did this folding here, it would be necessary to update the 12144 // MachineBasicBlock CFG, which is awkward. 12145 12146 // Use SimplifySetCC to simplify SETCC's. 12147 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 12148 CondLHS, CondRHS, CC->get(), SDLoc(N), 12149 false); 12150 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 12151 12152 // fold to a simpler setcc 12153 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 12154 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12155 N->getOperand(0), Simp.getOperand(2), 12156 Simp.getOperand(0), Simp.getOperand(1), 12157 N->getOperand(4)); 12158 12159 return SDValue(); 12160 } 12161 12162 /// Return true if 'Use' is a load or a store that uses N as its base pointer 12163 /// and that N may be folded in the load / store addressing mode. 12164 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 12165 SelectionDAG &DAG, 12166 const TargetLowering &TLI) { 12167 EVT VT; 12168 unsigned AS; 12169 12170 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 12171 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 12172 return false; 12173 VT = LD->getMemoryVT(); 12174 AS = LD->getAddressSpace(); 12175 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 12176 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 12177 return false; 12178 VT = ST->getMemoryVT(); 12179 AS = ST->getAddressSpace(); 12180 } else 12181 return false; 12182 12183 TargetLowering::AddrMode AM; 12184 if (N->getOpcode() == ISD::ADD) { 12185 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12186 if (Offset) 12187 // [reg +/- imm] 12188 AM.BaseOffs = Offset->getSExtValue(); 12189 else 12190 // [reg +/- reg] 12191 AM.Scale = 1; 12192 } else if (N->getOpcode() == ISD::SUB) { 12193 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12194 if (Offset) 12195 // [reg +/- imm] 12196 AM.BaseOffs = -Offset->getSExtValue(); 12197 else 12198 // [reg +/- reg] 12199 AM.Scale = 1; 12200 } else 12201 return false; 12202 12203 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 12204 VT.getTypeForEVT(*DAG.getContext()), AS); 12205 } 12206 12207 /// Try turning a load/store into a pre-indexed load/store when the base 12208 /// pointer is an add or subtract and it has other uses besides the load/store. 12209 /// After the transformation, the new indexed load/store has effectively folded 12210 /// the add/subtract in and all of its other uses are redirected to the 12211 /// new load/store. 12212 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 12213 if (Level < AfterLegalizeDAG) 12214 return false; 12215 12216 bool isLoad = true; 12217 SDValue Ptr; 12218 EVT VT; 12219 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12220 if (LD->isIndexed()) 12221 return false; 12222 VT = LD->getMemoryVT(); 12223 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 12224 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 12225 return false; 12226 Ptr = LD->getBasePtr(); 12227 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12228 if (ST->isIndexed()) 12229 return false; 12230 VT = ST->getMemoryVT(); 12231 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 12232 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 12233 return false; 12234 Ptr = ST->getBasePtr(); 12235 isLoad = false; 12236 } else { 12237 return false; 12238 } 12239 12240 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 12241 // out. There is no reason to make this a preinc/predec. 12242 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 12243 Ptr.getNode()->hasOneUse()) 12244 return false; 12245 12246 // Ask the target to do addressing mode selection. 12247 SDValue BasePtr; 12248 SDValue Offset; 12249 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12250 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 12251 return false; 12252 12253 // Backends without true r+i pre-indexed forms may need to pass a 12254 // constant base with a variable offset so that constant coercion 12255 // will work with the patterns in canonical form. 12256 bool Swapped = false; 12257 if (isa<ConstantSDNode>(BasePtr)) { 12258 std::swap(BasePtr, Offset); 12259 Swapped = true; 12260 } 12261 12262 // Don't create a indexed load / store with zero offset. 12263 if (isNullConstant(Offset)) 12264 return false; 12265 12266 // Try turning it into a pre-indexed load / store except when: 12267 // 1) The new base ptr is a frame index. 12268 // 2) If N is a store and the new base ptr is either the same as or is a 12269 // predecessor of the value being stored. 12270 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 12271 // that would create a cycle. 12272 // 4) All uses are load / store ops that use it as old base ptr. 12273 12274 // Check #1. Preinc'ing a frame index would require copying the stack pointer 12275 // (plus the implicit offset) to a register to preinc anyway. 12276 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12277 return false; 12278 12279 // Check #2. 12280 if (!isLoad) { 12281 SDValue Val = cast<StoreSDNode>(N)->getValue(); 12282 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 12283 return false; 12284 } 12285 12286 // Caches for hasPredecessorHelper. 12287 SmallPtrSet<const SDNode *, 32> Visited; 12288 SmallVector<const SDNode *, 16> Worklist; 12289 Worklist.push_back(N); 12290 12291 // If the offset is a constant, there may be other adds of constants that 12292 // can be folded with this one. We should do this to avoid having to keep 12293 // a copy of the original base pointer. 12294 SmallVector<SDNode *, 16> OtherUses; 12295 if (isa<ConstantSDNode>(Offset)) 12296 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 12297 UE = BasePtr.getNode()->use_end(); 12298 UI != UE; ++UI) { 12299 SDUse &Use = UI.getUse(); 12300 // Skip the use that is Ptr and uses of other results from BasePtr's 12301 // node (important for nodes that return multiple results). 12302 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 12303 continue; 12304 12305 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 12306 continue; 12307 12308 if (Use.getUser()->getOpcode() != ISD::ADD && 12309 Use.getUser()->getOpcode() != ISD::SUB) { 12310 OtherUses.clear(); 12311 break; 12312 } 12313 12314 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 12315 if (!isa<ConstantSDNode>(Op1)) { 12316 OtherUses.clear(); 12317 break; 12318 } 12319 12320 // FIXME: In some cases, we can be smarter about this. 12321 if (Op1.getValueType() != Offset.getValueType()) { 12322 OtherUses.clear(); 12323 break; 12324 } 12325 12326 OtherUses.push_back(Use.getUser()); 12327 } 12328 12329 if (Swapped) 12330 std::swap(BasePtr, Offset); 12331 12332 // Now check for #3 and #4. 12333 bool RealUse = false; 12334 12335 for (SDNode *Use : Ptr.getNode()->uses()) { 12336 if (Use == N) 12337 continue; 12338 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 12339 return false; 12340 12341 // If Ptr may be folded in addressing mode of other use, then it's 12342 // not profitable to do this transformation. 12343 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 12344 RealUse = true; 12345 } 12346 12347 if (!RealUse) 12348 return false; 12349 12350 SDValue Result; 12351 if (isLoad) 12352 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12353 BasePtr, Offset, AM); 12354 else 12355 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12356 BasePtr, Offset, AM); 12357 ++PreIndexedNodes; 12358 ++NodesCombined; 12359 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 12360 Result.getNode()->dump(&DAG); dbgs() << '\n'); 12361 WorklistRemover DeadNodes(*this); 12362 if (isLoad) { 12363 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12364 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12365 } else { 12366 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12367 } 12368 12369 // Finally, since the node is now dead, remove it from the graph. 12370 deleteAndRecombine(N); 12371 12372 if (Swapped) 12373 std::swap(BasePtr, Offset); 12374 12375 // Replace other uses of BasePtr that can be updated to use Ptr 12376 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 12377 unsigned OffsetIdx = 1; 12378 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 12379 OffsetIdx = 0; 12380 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 12381 BasePtr.getNode() && "Expected BasePtr operand"); 12382 12383 // We need to replace ptr0 in the following expression: 12384 // x0 * offset0 + y0 * ptr0 = t0 12385 // knowing that 12386 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 12387 // 12388 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 12389 // indexed load/store and the expression that needs to be re-written. 12390 // 12391 // Therefore, we have: 12392 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 12393 12394 ConstantSDNode *CN = 12395 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 12396 int X0, X1, Y0, Y1; 12397 const APInt &Offset0 = CN->getAPIntValue(); 12398 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 12399 12400 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 12401 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 12402 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 12403 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 12404 12405 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 12406 12407 APInt CNV = Offset0; 12408 if (X0 < 0) CNV = -CNV; 12409 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 12410 else CNV = CNV - Offset1; 12411 12412 SDLoc DL(OtherUses[i]); 12413 12414 // We can now generate the new expression. 12415 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 12416 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 12417 12418 SDValue NewUse = DAG.getNode(Opcode, 12419 DL, 12420 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 12421 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 12422 deleteAndRecombine(OtherUses[i]); 12423 } 12424 12425 // Replace the uses of Ptr with uses of the updated base value. 12426 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 12427 deleteAndRecombine(Ptr.getNode()); 12428 AddToWorklist(Result.getNode()); 12429 12430 return true; 12431 } 12432 12433 /// Try to combine a load/store with a add/sub of the base pointer node into a 12434 /// post-indexed load/store. The transformation folded the add/subtract into the 12435 /// new indexed load/store effectively and all of its uses are redirected to the 12436 /// new load/store. 12437 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 12438 if (Level < AfterLegalizeDAG) 12439 return false; 12440 12441 bool isLoad = true; 12442 SDValue Ptr; 12443 EVT VT; 12444 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12445 if (LD->isIndexed()) 12446 return false; 12447 VT = LD->getMemoryVT(); 12448 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 12449 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 12450 return false; 12451 Ptr = LD->getBasePtr(); 12452 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12453 if (ST->isIndexed()) 12454 return false; 12455 VT = ST->getMemoryVT(); 12456 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 12457 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 12458 return false; 12459 Ptr = ST->getBasePtr(); 12460 isLoad = false; 12461 } else { 12462 return false; 12463 } 12464 12465 if (Ptr.getNode()->hasOneUse()) 12466 return false; 12467 12468 for (SDNode *Op : Ptr.getNode()->uses()) { 12469 if (Op == N || 12470 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 12471 continue; 12472 12473 SDValue BasePtr; 12474 SDValue Offset; 12475 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12476 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 12477 // Don't create a indexed load / store with zero offset. 12478 if (isNullConstant(Offset)) 12479 continue; 12480 12481 // Try turning it into a post-indexed load / store except when 12482 // 1) All uses are load / store ops that use it as base ptr (and 12483 // it may be folded as addressing mmode). 12484 // 2) Op must be independent of N, i.e. Op is neither a predecessor 12485 // nor a successor of N. Otherwise, if Op is folded that would 12486 // create a cycle. 12487 12488 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12489 continue; 12490 12491 // Check for #1. 12492 bool TryNext = false; 12493 for (SDNode *Use : BasePtr.getNode()->uses()) { 12494 if (Use == Ptr.getNode()) 12495 continue; 12496 12497 // If all the uses are load / store addresses, then don't do the 12498 // transformation. 12499 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 12500 bool RealUse = false; 12501 for (SDNode *UseUse : Use->uses()) { 12502 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 12503 RealUse = true; 12504 } 12505 12506 if (!RealUse) { 12507 TryNext = true; 12508 break; 12509 } 12510 } 12511 } 12512 12513 if (TryNext) 12514 continue; 12515 12516 // Check for #2 12517 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 12518 SDValue Result = isLoad 12519 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12520 BasePtr, Offset, AM) 12521 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12522 BasePtr, Offset, AM); 12523 ++PostIndexedNodes; 12524 ++NodesCombined; 12525 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 12526 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 12527 dbgs() << '\n'); 12528 WorklistRemover DeadNodes(*this); 12529 if (isLoad) { 12530 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12532 } else { 12533 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12534 } 12535 12536 // Finally, since the node is now dead, remove it from the graph. 12537 deleteAndRecombine(N); 12538 12539 // Replace the uses of Use with uses of the updated base value. 12540 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 12541 Result.getValue(isLoad ? 1 : 0)); 12542 deleteAndRecombine(Op); 12543 return true; 12544 } 12545 } 12546 } 12547 12548 return false; 12549 } 12550 12551 /// Return the base-pointer arithmetic from an indexed \p LD. 12552 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 12553 ISD::MemIndexedMode AM = LD->getAddressingMode(); 12554 assert(AM != ISD::UNINDEXED); 12555 SDValue BP = LD->getOperand(1); 12556 SDValue Inc = LD->getOperand(2); 12557 12558 // Some backends use TargetConstants for load offsets, but don't expect 12559 // TargetConstants in general ADD nodes. We can convert these constants into 12560 // regular Constants (if the constant is not opaque). 12561 assert((Inc.getOpcode() != ISD::TargetConstant || 12562 !cast<ConstantSDNode>(Inc)->isOpaque()) && 12563 "Cannot split out indexing using opaque target constants"); 12564 if (Inc.getOpcode() == ISD::TargetConstant) { 12565 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 12566 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 12567 ConstInc->getValueType(0)); 12568 } 12569 12570 unsigned Opc = 12571 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 12572 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 12573 } 12574 12575 SDValue DAGCombiner::visitLOAD(SDNode *N) { 12576 LoadSDNode *LD = cast<LoadSDNode>(N); 12577 SDValue Chain = LD->getChain(); 12578 SDValue Ptr = LD->getBasePtr(); 12579 12580 // If load is not volatile and there are no uses of the loaded value (and 12581 // the updated indexed value in case of indexed loads), change uses of the 12582 // chain value into uses of the chain input (i.e. delete the dead load). 12583 if (!LD->isVolatile()) { 12584 if (N->getValueType(1) == MVT::Other) { 12585 // Unindexed loads. 12586 if (!N->hasAnyUseOfValue(0)) { 12587 // It's not safe to use the two value CombineTo variant here. e.g. 12588 // v1, chain2 = load chain1, loc 12589 // v2, chain3 = load chain2, loc 12590 // v3 = add v2, c 12591 // Now we replace use of chain2 with chain1. This makes the second load 12592 // isomorphic to the one we are deleting, and thus makes this load live. 12593 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 12594 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 12595 dbgs() << "\n"); 12596 WorklistRemover DeadNodes(*this); 12597 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12598 AddUsersToWorklist(Chain.getNode()); 12599 if (N->use_empty()) 12600 deleteAndRecombine(N); 12601 12602 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12603 } 12604 } else { 12605 // Indexed loads. 12606 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 12607 12608 // If this load has an opaque TargetConstant offset, then we cannot split 12609 // the indexing into an add/sub directly (that TargetConstant may not be 12610 // valid for a different type of node, and we cannot convert an opaque 12611 // target constant into a regular constant). 12612 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 12613 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 12614 12615 if (!N->hasAnyUseOfValue(0) && 12616 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 12617 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 12618 SDValue Index; 12619 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 12620 Index = SplitIndexingFromLoad(LD); 12621 // Try to fold the base pointer arithmetic into subsequent loads and 12622 // stores. 12623 AddUsersToWorklist(N); 12624 } else 12625 Index = DAG.getUNDEF(N->getValueType(1)); 12626 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 12627 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 12628 dbgs() << " and 2 other values\n"); 12629 WorklistRemover DeadNodes(*this); 12630 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 12631 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 12632 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 12633 deleteAndRecombine(N); 12634 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12635 } 12636 } 12637 } 12638 12639 // If this load is directly stored, replace the load value with the stored 12640 // value. 12641 // TODO: Handle store large -> read small portion. 12642 // TODO: Handle TRUNCSTORE/LOADEXT 12643 if (OptLevel != CodeGenOpt::None && 12644 ISD::isNormalLoad(N) && !LD->isVolatile()) { 12645 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 12646 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 12647 if (PrevST->getBasePtr() == Ptr && 12648 PrevST->getValue().getValueType() == N->getValueType(0)) 12649 return CombineTo(N, PrevST->getOperand(1), Chain); 12650 } 12651 } 12652 12653 // Try to infer better alignment information than the load already has. 12654 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 12655 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12656 if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) { 12657 SDValue NewLoad = DAG.getExtLoad( 12658 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 12659 LD->getPointerInfo(), LD->getMemoryVT(), Align, 12660 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12661 // NewLoad will always be N as we are only refining the alignment 12662 assert(NewLoad.getNode() == N); 12663 (void)NewLoad; 12664 } 12665 } 12666 } 12667 12668 if (LD->isUnindexed()) { 12669 // Walk up chain skipping non-aliasing memory nodes. 12670 SDValue BetterChain = FindBetterChain(N, Chain); 12671 12672 // If there is a better chain. 12673 if (Chain != BetterChain) { 12674 SDValue ReplLoad; 12675 12676 // Replace the chain to void dependency. 12677 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 12678 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 12679 BetterChain, Ptr, LD->getMemOperand()); 12680 } else { 12681 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 12682 LD->getValueType(0), 12683 BetterChain, Ptr, LD->getMemoryVT(), 12684 LD->getMemOperand()); 12685 } 12686 12687 // Create token factor to keep old chain connected. 12688 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 12689 MVT::Other, Chain, ReplLoad.getValue(1)); 12690 12691 // Replace uses with load result and token factor 12692 return CombineTo(N, ReplLoad.getValue(0), Token); 12693 } 12694 } 12695 12696 // Try transforming N to an indexed load. 12697 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12698 return SDValue(N, 0); 12699 12700 // Try to slice up N to more direct loads if the slices are mapped to 12701 // different register banks or pairing can take place. 12702 if (SliceUpLoad(N)) 12703 return SDValue(N, 0); 12704 12705 return SDValue(); 12706 } 12707 12708 namespace { 12709 12710 /// Helper structure used to slice a load in smaller loads. 12711 /// Basically a slice is obtained from the following sequence: 12712 /// Origin = load Ty1, Base 12713 /// Shift = srl Ty1 Origin, CstTy Amount 12714 /// Inst = trunc Shift to Ty2 12715 /// 12716 /// Then, it will be rewritten into: 12717 /// Slice = load SliceTy, Base + SliceOffset 12718 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 12719 /// 12720 /// SliceTy is deduced from the number of bits that are actually used to 12721 /// build Inst. 12722 struct LoadedSlice { 12723 /// Helper structure used to compute the cost of a slice. 12724 struct Cost { 12725 /// Are we optimizing for code size. 12726 bool ForCodeSize; 12727 12728 /// Various cost. 12729 unsigned Loads = 0; 12730 unsigned Truncates = 0; 12731 unsigned CrossRegisterBanksCopies = 0; 12732 unsigned ZExts = 0; 12733 unsigned Shift = 0; 12734 12735 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 12736 12737 /// Get the cost of one isolated slice. 12738 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 12739 : ForCodeSize(ForCodeSize), Loads(1) { 12740 EVT TruncType = LS.Inst->getValueType(0); 12741 EVT LoadedType = LS.getLoadedType(); 12742 if (TruncType != LoadedType && 12743 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 12744 ZExts = 1; 12745 } 12746 12747 /// Account for slicing gain in the current cost. 12748 /// Slicing provide a few gains like removing a shift or a 12749 /// truncate. This method allows to grow the cost of the original 12750 /// load with the gain from this slice. 12751 void addSliceGain(const LoadedSlice &LS) { 12752 // Each slice saves a truncate. 12753 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 12754 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 12755 LS.Inst->getValueType(0))) 12756 ++Truncates; 12757 // If there is a shift amount, this slice gets rid of it. 12758 if (LS.Shift) 12759 ++Shift; 12760 // If this slice can merge a cross register bank copy, account for it. 12761 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 12762 ++CrossRegisterBanksCopies; 12763 } 12764 12765 Cost &operator+=(const Cost &RHS) { 12766 Loads += RHS.Loads; 12767 Truncates += RHS.Truncates; 12768 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 12769 ZExts += RHS.ZExts; 12770 Shift += RHS.Shift; 12771 return *this; 12772 } 12773 12774 bool operator==(const Cost &RHS) const { 12775 return Loads == RHS.Loads && Truncates == RHS.Truncates && 12776 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 12777 ZExts == RHS.ZExts && Shift == RHS.Shift; 12778 } 12779 12780 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 12781 12782 bool operator<(const Cost &RHS) const { 12783 // Assume cross register banks copies are as expensive as loads. 12784 // FIXME: Do we want some more target hooks? 12785 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 12786 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 12787 // Unless we are optimizing for code size, consider the 12788 // expensive operation first. 12789 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 12790 return ExpensiveOpsLHS < ExpensiveOpsRHS; 12791 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 12792 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 12793 } 12794 12795 bool operator>(const Cost &RHS) const { return RHS < *this; } 12796 12797 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 12798 12799 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 12800 }; 12801 12802 // The last instruction that represent the slice. This should be a 12803 // truncate instruction. 12804 SDNode *Inst; 12805 12806 // The original load instruction. 12807 LoadSDNode *Origin; 12808 12809 // The right shift amount in bits from the original load. 12810 unsigned Shift; 12811 12812 // The DAG from which Origin came from. 12813 // This is used to get some contextual information about legal types, etc. 12814 SelectionDAG *DAG; 12815 12816 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 12817 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 12818 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 12819 12820 /// Get the bits used in a chunk of bits \p BitWidth large. 12821 /// \return Result is \p BitWidth and has used bits set to 1 and 12822 /// not used bits set to 0. 12823 APInt getUsedBits() const { 12824 // Reproduce the trunc(lshr) sequence: 12825 // - Start from the truncated value. 12826 // - Zero extend to the desired bit width. 12827 // - Shift left. 12828 assert(Origin && "No original load to compare against."); 12829 unsigned BitWidth = Origin->getValueSizeInBits(0); 12830 assert(Inst && "This slice is not bound to an instruction"); 12831 assert(Inst->getValueSizeInBits(0) <= BitWidth && 12832 "Extracted slice is bigger than the whole type!"); 12833 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 12834 UsedBits.setAllBits(); 12835 UsedBits = UsedBits.zext(BitWidth); 12836 UsedBits <<= Shift; 12837 return UsedBits; 12838 } 12839 12840 /// Get the size of the slice to be loaded in bytes. 12841 unsigned getLoadedSize() const { 12842 unsigned SliceSize = getUsedBits().countPopulation(); 12843 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 12844 return SliceSize / 8; 12845 } 12846 12847 /// Get the type that will be loaded for this slice. 12848 /// Note: This may not be the final type for the slice. 12849 EVT getLoadedType() const { 12850 assert(DAG && "Missing context"); 12851 LLVMContext &Ctxt = *DAG->getContext(); 12852 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 12853 } 12854 12855 /// Get the alignment of the load used for this slice. 12856 unsigned getAlignment() const { 12857 unsigned Alignment = Origin->getAlignment(); 12858 unsigned Offset = getOffsetFromBase(); 12859 if (Offset != 0) 12860 Alignment = MinAlign(Alignment, Alignment + Offset); 12861 return Alignment; 12862 } 12863 12864 /// Check if this slice can be rewritten with legal operations. 12865 bool isLegal() const { 12866 // An invalid slice is not legal. 12867 if (!Origin || !Inst || !DAG) 12868 return false; 12869 12870 // Offsets are for indexed load only, we do not handle that. 12871 if (!Origin->getOffset().isUndef()) 12872 return false; 12873 12874 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12875 12876 // Check that the type is legal. 12877 EVT SliceType = getLoadedType(); 12878 if (!TLI.isTypeLegal(SliceType)) 12879 return false; 12880 12881 // Check that the load is legal for this type. 12882 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 12883 return false; 12884 12885 // Check that the offset can be computed. 12886 // 1. Check its type. 12887 EVT PtrType = Origin->getBasePtr().getValueType(); 12888 if (PtrType == MVT::Untyped || PtrType.isExtended()) 12889 return false; 12890 12891 // 2. Check that it fits in the immediate. 12892 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 12893 return false; 12894 12895 // 3. Check that the computation is legal. 12896 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 12897 return false; 12898 12899 // Check that the zext is legal if it needs one. 12900 EVT TruncateType = Inst->getValueType(0); 12901 if (TruncateType != SliceType && 12902 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 12903 return false; 12904 12905 return true; 12906 } 12907 12908 /// Get the offset in bytes of this slice in the original chunk of 12909 /// bits. 12910 /// \pre DAG != nullptr. 12911 uint64_t getOffsetFromBase() const { 12912 assert(DAG && "Missing context."); 12913 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 12914 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 12915 uint64_t Offset = Shift / 8; 12916 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 12917 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 12918 "The size of the original loaded type is not a multiple of a" 12919 " byte."); 12920 // If Offset is bigger than TySizeInBytes, it means we are loading all 12921 // zeros. This should have been optimized before in the process. 12922 assert(TySizeInBytes > Offset && 12923 "Invalid shift amount for given loaded size"); 12924 if (IsBigEndian) 12925 Offset = TySizeInBytes - Offset - getLoadedSize(); 12926 return Offset; 12927 } 12928 12929 /// Generate the sequence of instructions to load the slice 12930 /// represented by this object and redirect the uses of this slice to 12931 /// this new sequence of instructions. 12932 /// \pre this->Inst && this->Origin are valid Instructions and this 12933 /// object passed the legal check: LoadedSlice::isLegal returned true. 12934 /// \return The last instruction of the sequence used to load the slice. 12935 SDValue loadSlice() const { 12936 assert(Inst && Origin && "Unable to replace a non-existing slice."); 12937 const SDValue &OldBaseAddr = Origin->getBasePtr(); 12938 SDValue BaseAddr = OldBaseAddr; 12939 // Get the offset in that chunk of bytes w.r.t. the endianness. 12940 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 12941 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 12942 if (Offset) { 12943 // BaseAddr = BaseAddr + Offset. 12944 EVT ArithType = BaseAddr.getValueType(); 12945 SDLoc DL(Origin); 12946 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 12947 DAG->getConstant(Offset, DL, ArithType)); 12948 } 12949 12950 // Create the type of the loaded slice according to its size. 12951 EVT SliceType = getLoadedType(); 12952 12953 // Create the load for the slice. 12954 SDValue LastInst = 12955 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 12956 Origin->getPointerInfo().getWithOffset(Offset), 12957 getAlignment(), Origin->getMemOperand()->getFlags()); 12958 // If the final type is not the same as the loaded type, this means that 12959 // we have to pad with zero. Create a zero extend for that. 12960 EVT FinalType = Inst->getValueType(0); 12961 if (SliceType != FinalType) 12962 LastInst = 12963 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 12964 return LastInst; 12965 } 12966 12967 /// Check if this slice can be merged with an expensive cross register 12968 /// bank copy. E.g., 12969 /// i = load i32 12970 /// f = bitcast i32 i to float 12971 bool canMergeExpensiveCrossRegisterBankCopy() const { 12972 if (!Inst || !Inst->hasOneUse()) 12973 return false; 12974 SDNode *Use = *Inst->use_begin(); 12975 if (Use->getOpcode() != ISD::BITCAST) 12976 return false; 12977 assert(DAG && "Missing context"); 12978 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 12979 EVT ResVT = Use->getValueType(0); 12980 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 12981 const TargetRegisterClass *ArgRC = 12982 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 12983 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 12984 return false; 12985 12986 // At this point, we know that we perform a cross-register-bank copy. 12987 // Check if it is expensive. 12988 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 12989 // Assume bitcasts are cheap, unless both register classes do not 12990 // explicitly share a common sub class. 12991 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 12992 return false; 12993 12994 // Check if it will be merged with the load. 12995 // 1. Check the alignment constraint. 12996 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 12997 ResVT.getTypeForEVT(*DAG->getContext())); 12998 12999 if (RequiredAlignment > getAlignment()) 13000 return false; 13001 13002 // 2. Check that the load is a legal operation for that type. 13003 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 13004 return false; 13005 13006 // 3. Check that we do not have a zext in the way. 13007 if (Inst->getValueType(0) != getLoadedType()) 13008 return false; 13009 13010 return true; 13011 } 13012 }; 13013 13014 } // end anonymous namespace 13015 13016 /// Check that all bits set in \p UsedBits form a dense region, i.e., 13017 /// \p UsedBits looks like 0..0 1..1 0..0. 13018 static bool areUsedBitsDense(const APInt &UsedBits) { 13019 // If all the bits are one, this is dense! 13020 if (UsedBits.isAllOnesValue()) 13021 return true; 13022 13023 // Get rid of the unused bits on the right. 13024 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 13025 // Get rid of the unused bits on the left. 13026 if (NarrowedUsedBits.countLeadingZeros()) 13027 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 13028 // Check that the chunk of bits is completely used. 13029 return NarrowedUsedBits.isAllOnesValue(); 13030 } 13031 13032 /// Check whether or not \p First and \p Second are next to each other 13033 /// in memory. This means that there is no hole between the bits loaded 13034 /// by \p First and the bits loaded by \p Second. 13035 static bool areSlicesNextToEachOther(const LoadedSlice &First, 13036 const LoadedSlice &Second) { 13037 assert(First.Origin == Second.Origin && First.Origin && 13038 "Unable to match different memory origins."); 13039 APInt UsedBits = First.getUsedBits(); 13040 assert((UsedBits & Second.getUsedBits()) == 0 && 13041 "Slices are not supposed to overlap."); 13042 UsedBits |= Second.getUsedBits(); 13043 return areUsedBitsDense(UsedBits); 13044 } 13045 13046 /// Adjust the \p GlobalLSCost according to the target 13047 /// paring capabilities and the layout of the slices. 13048 /// \pre \p GlobalLSCost should account for at least as many loads as 13049 /// there is in the slices in \p LoadedSlices. 13050 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13051 LoadedSlice::Cost &GlobalLSCost) { 13052 unsigned NumberOfSlices = LoadedSlices.size(); 13053 // If there is less than 2 elements, no pairing is possible. 13054 if (NumberOfSlices < 2) 13055 return; 13056 13057 // Sort the slices so that elements that are likely to be next to each 13058 // other in memory are next to each other in the list. 13059 llvm::sort(LoadedSlices.begin(), LoadedSlices.end(), 13060 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 13061 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 13062 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 13063 }); 13064 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 13065 // First (resp. Second) is the first (resp. Second) potentially candidate 13066 // to be placed in a paired load. 13067 const LoadedSlice *First = nullptr; 13068 const LoadedSlice *Second = nullptr; 13069 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 13070 // Set the beginning of the pair. 13071 First = Second) { 13072 Second = &LoadedSlices[CurrSlice]; 13073 13074 // If First is NULL, it means we start a new pair. 13075 // Get to the next slice. 13076 if (!First) 13077 continue; 13078 13079 EVT LoadedType = First->getLoadedType(); 13080 13081 // If the types of the slices are different, we cannot pair them. 13082 if (LoadedType != Second->getLoadedType()) 13083 continue; 13084 13085 // Check if the target supplies paired loads for this type. 13086 unsigned RequiredAlignment = 0; 13087 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 13088 // move to the next pair, this type is hopeless. 13089 Second = nullptr; 13090 continue; 13091 } 13092 // Check if we meet the alignment requirement. 13093 if (RequiredAlignment > First->getAlignment()) 13094 continue; 13095 13096 // Check that both loads are next to each other in memory. 13097 if (!areSlicesNextToEachOther(*First, *Second)) 13098 continue; 13099 13100 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 13101 --GlobalLSCost.Loads; 13102 // Move to the next pair. 13103 Second = nullptr; 13104 } 13105 } 13106 13107 /// Check the profitability of all involved LoadedSlice. 13108 /// Currently, it is considered profitable if there is exactly two 13109 /// involved slices (1) which are (2) next to each other in memory, and 13110 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 13111 /// 13112 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 13113 /// the elements themselves. 13114 /// 13115 /// FIXME: When the cost model will be mature enough, we can relax 13116 /// constraints (1) and (2). 13117 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13118 const APInt &UsedBits, bool ForCodeSize) { 13119 unsigned NumberOfSlices = LoadedSlices.size(); 13120 if (StressLoadSlicing) 13121 return NumberOfSlices > 1; 13122 13123 // Check (1). 13124 if (NumberOfSlices != 2) 13125 return false; 13126 13127 // Check (2). 13128 if (!areUsedBitsDense(UsedBits)) 13129 return false; 13130 13131 // Check (3). 13132 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 13133 // The original code has one big load. 13134 OrigCost.Loads = 1; 13135 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 13136 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 13137 // Accumulate the cost of all the slices. 13138 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 13139 GlobalSlicingCost += SliceCost; 13140 13141 // Account as cost in the original configuration the gain obtained 13142 // with the current slices. 13143 OrigCost.addSliceGain(LS); 13144 } 13145 13146 // If the target supports paired load, adjust the cost accordingly. 13147 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 13148 return OrigCost > GlobalSlicingCost; 13149 } 13150 13151 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 13152 /// operations, split it in the various pieces being extracted. 13153 /// 13154 /// This sort of thing is introduced by SROA. 13155 /// This slicing takes care not to insert overlapping loads. 13156 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 13157 bool DAGCombiner::SliceUpLoad(SDNode *N) { 13158 if (Level < AfterLegalizeDAG) 13159 return false; 13160 13161 LoadSDNode *LD = cast<LoadSDNode>(N); 13162 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 13163 !LD->getValueType(0).isInteger()) 13164 return false; 13165 13166 // Keep track of already used bits to detect overlapping values. 13167 // In that case, we will just abort the transformation. 13168 APInt UsedBits(LD->getValueSizeInBits(0), 0); 13169 13170 SmallVector<LoadedSlice, 4> LoadedSlices; 13171 13172 // Check if this load is used as several smaller chunks of bits. 13173 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 13174 // of computation for each trunc. 13175 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 13176 UI != UIEnd; ++UI) { 13177 // Skip the uses of the chain. 13178 if (UI.getUse().getResNo() != 0) 13179 continue; 13180 13181 SDNode *User = *UI; 13182 unsigned Shift = 0; 13183 13184 // Check if this is a trunc(lshr). 13185 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 13186 isa<ConstantSDNode>(User->getOperand(1))) { 13187 Shift = User->getConstantOperandVal(1); 13188 User = *User->use_begin(); 13189 } 13190 13191 // At this point, User is a Truncate, iff we encountered, trunc or 13192 // trunc(lshr). 13193 if (User->getOpcode() != ISD::TRUNCATE) 13194 return false; 13195 13196 // The width of the type must be a power of 2 and greater than 8-bits. 13197 // Otherwise the load cannot be represented in LLVM IR. 13198 // Moreover, if we shifted with a non-8-bits multiple, the slice 13199 // will be across several bytes. We do not support that. 13200 unsigned Width = User->getValueSizeInBits(0); 13201 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 13202 return false; 13203 13204 // Build the slice for this chain of computations. 13205 LoadedSlice LS(User, LD, Shift, &DAG); 13206 APInt CurrentUsedBits = LS.getUsedBits(); 13207 13208 // Check if this slice overlaps with another. 13209 if ((CurrentUsedBits & UsedBits) != 0) 13210 return false; 13211 // Update the bits used globally. 13212 UsedBits |= CurrentUsedBits; 13213 13214 // Check if the new slice would be legal. 13215 if (!LS.isLegal()) 13216 return false; 13217 13218 // Record the slice. 13219 LoadedSlices.push_back(LS); 13220 } 13221 13222 // Abort slicing if it does not seem to be profitable. 13223 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 13224 return false; 13225 13226 ++SlicedLoads; 13227 13228 // Rewrite each chain to use an independent load. 13229 // By construction, each chain can be represented by a unique load. 13230 13231 // Prepare the argument for the new token factor for all the slices. 13232 SmallVector<SDValue, 8> ArgChains; 13233 for (SmallVectorImpl<LoadedSlice>::const_iterator 13234 LSIt = LoadedSlices.begin(), 13235 LSItEnd = LoadedSlices.end(); 13236 LSIt != LSItEnd; ++LSIt) { 13237 SDValue SliceInst = LSIt->loadSlice(); 13238 CombineTo(LSIt->Inst, SliceInst, true); 13239 if (SliceInst.getOpcode() != ISD::LOAD) 13240 SliceInst = SliceInst.getOperand(0); 13241 assert(SliceInst->getOpcode() == ISD::LOAD && 13242 "It takes more than a zext to get to the loaded slice!!"); 13243 ArgChains.push_back(SliceInst.getValue(1)); 13244 } 13245 13246 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 13247 ArgChains); 13248 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 13249 AddToWorklist(Chain.getNode()); 13250 return true; 13251 } 13252 13253 /// Check to see if V is (and load (ptr), imm), where the load is having 13254 /// specific bytes cleared out. If so, return the byte size being masked out 13255 /// and the shift amount. 13256 static std::pair<unsigned, unsigned> 13257 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 13258 std::pair<unsigned, unsigned> Result(0, 0); 13259 13260 // Check for the structure we're looking for. 13261 if (V->getOpcode() != ISD::AND || 13262 !isa<ConstantSDNode>(V->getOperand(1)) || 13263 !ISD::isNormalLoad(V->getOperand(0).getNode())) 13264 return Result; 13265 13266 // Check the chain and pointer. 13267 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 13268 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 13269 13270 // This only handles simple types. 13271 if (V.getValueType() != MVT::i16 && 13272 V.getValueType() != MVT::i32 && 13273 V.getValueType() != MVT::i64) 13274 return Result; 13275 13276 // Check the constant mask. Invert it so that the bits being masked out are 13277 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 13278 // follow the sign bit for uniformity. 13279 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 13280 unsigned NotMaskLZ = countLeadingZeros(NotMask); 13281 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 13282 unsigned NotMaskTZ = countTrailingZeros(NotMask); 13283 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 13284 if (NotMaskLZ == 64) return Result; // All zero mask. 13285 13286 // See if we have a continuous run of bits. If so, we have 0*1+0* 13287 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 13288 return Result; 13289 13290 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 13291 if (V.getValueType() != MVT::i64 && NotMaskLZ) 13292 NotMaskLZ -= 64-V.getValueSizeInBits(); 13293 13294 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 13295 switch (MaskedBytes) { 13296 case 1: 13297 case 2: 13298 case 4: break; 13299 default: return Result; // All one mask, or 5-byte mask. 13300 } 13301 13302 // Verify that the first bit starts at a multiple of mask so that the access 13303 // is aligned the same as the access width. 13304 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 13305 13306 // For narrowing to be valid, it must be the case that the load the 13307 // immediately preceeding memory operation before the store. 13308 if (LD == Chain.getNode()) 13309 ; // ok. 13310 else if (Chain->getOpcode() == ISD::TokenFactor && 13311 SDValue(LD, 1).hasOneUse()) { 13312 // LD has only 1 chain use so they are no indirect dependencies. 13313 bool isOk = false; 13314 for (const SDValue &ChainOp : Chain->op_values()) 13315 if (ChainOp.getNode() == LD) { 13316 isOk = true; 13317 break; 13318 } 13319 if (!isOk) 13320 return Result; 13321 } else 13322 return Result; // Fail. 13323 13324 Result.first = MaskedBytes; 13325 Result.second = NotMaskTZ/8; 13326 return Result; 13327 } 13328 13329 /// Check to see if IVal is something that provides a value as specified by 13330 /// MaskInfo. If so, replace the specified store with a narrower store of 13331 /// truncated IVal. 13332 static SDNode * 13333 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 13334 SDValue IVal, StoreSDNode *St, 13335 DAGCombiner *DC) { 13336 unsigned NumBytes = MaskInfo.first; 13337 unsigned ByteShift = MaskInfo.second; 13338 SelectionDAG &DAG = DC->getDAG(); 13339 13340 // Check to see if IVal is all zeros in the part being masked in by the 'or' 13341 // that uses this. If not, this is not a replacement. 13342 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 13343 ByteShift*8, (ByteShift+NumBytes)*8); 13344 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 13345 13346 // Check that it is legal on the target to do this. It is legal if the new 13347 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 13348 // legalization. 13349 MVT VT = MVT::getIntegerVT(NumBytes*8); 13350 if (!DC->isTypeLegal(VT)) 13351 return nullptr; 13352 13353 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 13354 // shifted by ByteShift and truncated down to NumBytes. 13355 if (ByteShift) { 13356 SDLoc DL(IVal); 13357 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 13358 DAG.getConstant(ByteShift*8, DL, 13359 DC->getShiftAmountTy(IVal.getValueType()))); 13360 } 13361 13362 // Figure out the offset for the store and the alignment of the access. 13363 unsigned StOffset; 13364 unsigned NewAlign = St->getAlignment(); 13365 13366 if (DAG.getDataLayout().isLittleEndian()) 13367 StOffset = ByteShift; 13368 else 13369 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 13370 13371 SDValue Ptr = St->getBasePtr(); 13372 if (StOffset) { 13373 SDLoc DL(IVal); 13374 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 13375 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 13376 NewAlign = MinAlign(NewAlign, StOffset); 13377 } 13378 13379 // Truncate down to the new size. 13380 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 13381 13382 ++OpsNarrowed; 13383 return DAG 13384 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 13385 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 13386 .getNode(); 13387 } 13388 13389 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 13390 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 13391 /// narrowing the load and store if it would end up being a win for performance 13392 /// or code size. 13393 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 13394 StoreSDNode *ST = cast<StoreSDNode>(N); 13395 if (ST->isVolatile()) 13396 return SDValue(); 13397 13398 SDValue Chain = ST->getChain(); 13399 SDValue Value = ST->getValue(); 13400 SDValue Ptr = ST->getBasePtr(); 13401 EVT VT = Value.getValueType(); 13402 13403 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 13404 return SDValue(); 13405 13406 unsigned Opc = Value.getOpcode(); 13407 13408 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 13409 // is a byte mask indicating a consecutive number of bytes, check to see if 13410 // Y is known to provide just those bytes. If so, we try to replace the 13411 // load + replace + store sequence with a single (narrower) store, which makes 13412 // the load dead. 13413 if (Opc == ISD::OR) { 13414 std::pair<unsigned, unsigned> MaskedLoad; 13415 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 13416 if (MaskedLoad.first) 13417 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13418 Value.getOperand(1), ST,this)) 13419 return SDValue(NewST, 0); 13420 13421 // Or is commutative, so try swapping X and Y. 13422 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 13423 if (MaskedLoad.first) 13424 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13425 Value.getOperand(0), ST,this)) 13426 return SDValue(NewST, 0); 13427 } 13428 13429 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 13430 Value.getOperand(1).getOpcode() != ISD::Constant) 13431 return SDValue(); 13432 13433 SDValue N0 = Value.getOperand(0); 13434 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 13435 Chain == SDValue(N0.getNode(), 1)) { 13436 LoadSDNode *LD = cast<LoadSDNode>(N0); 13437 if (LD->getBasePtr() != Ptr || 13438 LD->getPointerInfo().getAddrSpace() != 13439 ST->getPointerInfo().getAddrSpace()) 13440 return SDValue(); 13441 13442 // Find the type to narrow it the load / op / store to. 13443 SDValue N1 = Value.getOperand(1); 13444 unsigned BitWidth = N1.getValueSizeInBits(); 13445 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 13446 if (Opc == ISD::AND) 13447 Imm ^= APInt::getAllOnesValue(BitWidth); 13448 if (Imm == 0 || Imm.isAllOnesValue()) 13449 return SDValue(); 13450 unsigned ShAmt = Imm.countTrailingZeros(); 13451 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 13452 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 13453 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13454 // The narrowing should be profitable, the load/store operation should be 13455 // legal (or custom) and the store size should be equal to the NewVT width. 13456 while (NewBW < BitWidth && 13457 (NewVT.getStoreSizeInBits() != NewBW || 13458 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 13459 !TLI.isNarrowingProfitable(VT, NewVT))) { 13460 NewBW = NextPowerOf2(NewBW); 13461 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13462 } 13463 if (NewBW >= BitWidth) 13464 return SDValue(); 13465 13466 // If the lsb changed does not start at the type bitwidth boundary, 13467 // start at the previous one. 13468 if (ShAmt % NewBW) 13469 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 13470 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 13471 std::min(BitWidth, ShAmt + NewBW)); 13472 if ((Imm & Mask) == Imm) { 13473 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 13474 if (Opc == ISD::AND) 13475 NewImm ^= APInt::getAllOnesValue(NewBW); 13476 uint64_t PtrOff = ShAmt / 8; 13477 // For big endian targets, we need to adjust the offset to the pointer to 13478 // load the correct bytes. 13479 if (DAG.getDataLayout().isBigEndian()) 13480 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 13481 13482 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 13483 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 13484 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 13485 return SDValue(); 13486 13487 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 13488 Ptr.getValueType(), Ptr, 13489 DAG.getConstant(PtrOff, SDLoc(LD), 13490 Ptr.getValueType())); 13491 SDValue NewLD = 13492 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 13493 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 13494 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 13495 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 13496 DAG.getConstant(NewImm, SDLoc(Value), 13497 NewVT)); 13498 SDValue NewST = 13499 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 13500 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 13501 13502 AddToWorklist(NewPtr.getNode()); 13503 AddToWorklist(NewLD.getNode()); 13504 AddToWorklist(NewVal.getNode()); 13505 WorklistRemover DeadNodes(*this); 13506 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 13507 ++OpsNarrowed; 13508 return NewST; 13509 } 13510 } 13511 13512 return SDValue(); 13513 } 13514 13515 /// For a given floating point load / store pair, if the load value isn't used 13516 /// by any other operations, then consider transforming the pair to integer 13517 /// load / store operations if the target deems the transformation profitable. 13518 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 13519 StoreSDNode *ST = cast<StoreSDNode>(N); 13520 SDValue Chain = ST->getChain(); 13521 SDValue Value = ST->getValue(); 13522 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 13523 Value.hasOneUse() && 13524 Chain == SDValue(Value.getNode(), 1)) { 13525 LoadSDNode *LD = cast<LoadSDNode>(Value); 13526 EVT VT = LD->getMemoryVT(); 13527 if (!VT.isFloatingPoint() || 13528 VT != ST->getMemoryVT() || 13529 LD->isNonTemporal() || 13530 ST->isNonTemporal() || 13531 LD->getPointerInfo().getAddrSpace() != 0 || 13532 ST->getPointerInfo().getAddrSpace() != 0) 13533 return SDValue(); 13534 13535 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 13536 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 13537 !TLI.isOperationLegal(ISD::STORE, IntVT) || 13538 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 13539 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 13540 return SDValue(); 13541 13542 unsigned LDAlign = LD->getAlignment(); 13543 unsigned STAlign = ST->getAlignment(); 13544 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 13545 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 13546 if (LDAlign < ABIAlign || STAlign < ABIAlign) 13547 return SDValue(); 13548 13549 SDValue NewLD = 13550 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 13551 LD->getPointerInfo(), LDAlign); 13552 13553 SDValue NewST = 13554 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 13555 ST->getPointerInfo(), STAlign); 13556 13557 AddToWorklist(NewLD.getNode()); 13558 AddToWorklist(NewST.getNode()); 13559 WorklistRemover DeadNodes(*this); 13560 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 13561 ++LdStFP2Int; 13562 return NewST; 13563 } 13564 13565 return SDValue(); 13566 } 13567 13568 // This is a helper function for visitMUL to check the profitability 13569 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 13570 // MulNode is the original multiply, AddNode is (add x, c1), 13571 // and ConstNode is c2. 13572 // 13573 // If the (add x, c1) has multiple uses, we could increase 13574 // the number of adds if we make this transformation. 13575 // It would only be worth doing this if we can remove a 13576 // multiply in the process. Check for that here. 13577 // To illustrate: 13578 // (A + c1) * c3 13579 // (A + c2) * c3 13580 // We're checking for cases where we have common "c3 * A" expressions. 13581 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 13582 SDValue &AddNode, 13583 SDValue &ConstNode) { 13584 APInt Val; 13585 13586 // If the add only has one use, this would be OK to do. 13587 if (AddNode.getNode()->hasOneUse()) 13588 return true; 13589 13590 // Walk all the users of the constant with which we're multiplying. 13591 for (SDNode *Use : ConstNode->uses()) { 13592 if (Use == MulNode) // This use is the one we're on right now. Skip it. 13593 continue; 13594 13595 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 13596 SDNode *OtherOp; 13597 SDNode *MulVar = AddNode.getOperand(0).getNode(); 13598 13599 // OtherOp is what we're multiplying against the constant. 13600 if (Use->getOperand(0) == ConstNode) 13601 OtherOp = Use->getOperand(1).getNode(); 13602 else 13603 OtherOp = Use->getOperand(0).getNode(); 13604 13605 // Check to see if multiply is with the same operand of our "add". 13606 // 13607 // ConstNode = CONST 13608 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 13609 // ... 13610 // AddNode = (A + c1) <-- MulVar is A. 13611 // = AddNode * ConstNode <-- current visiting instruction. 13612 // 13613 // If we make this transformation, we will have a common 13614 // multiply (ConstNode * A) that we can save. 13615 if (OtherOp == MulVar) 13616 return true; 13617 13618 // Now check to see if a future expansion will give us a common 13619 // multiply. 13620 // 13621 // ConstNode = CONST 13622 // AddNode = (A + c1) 13623 // ... = AddNode * ConstNode <-- current visiting instruction. 13624 // ... 13625 // OtherOp = (A + c2) 13626 // Use = OtherOp * ConstNode <-- visiting Use. 13627 // 13628 // If we make this transformation, we will have a common 13629 // multiply (CONST * A) after we also do the same transformation 13630 // to the "t2" instruction. 13631 if (OtherOp->getOpcode() == ISD::ADD && 13632 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 13633 OtherOp->getOperand(0).getNode() == MulVar) 13634 return true; 13635 } 13636 } 13637 13638 // Didn't find a case where this would be profitable. 13639 return false; 13640 } 13641 13642 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 13643 unsigned NumStores) { 13644 SmallVector<SDValue, 8> Chains; 13645 SmallPtrSet<const SDNode *, 8> Visited; 13646 SDLoc StoreDL(StoreNodes[0].MemNode); 13647 13648 for (unsigned i = 0; i < NumStores; ++i) { 13649 Visited.insert(StoreNodes[i].MemNode); 13650 } 13651 13652 // don't include nodes that are children 13653 for (unsigned i = 0; i < NumStores; ++i) { 13654 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 13655 Chains.push_back(StoreNodes[i].MemNode->getChain()); 13656 } 13657 13658 assert(Chains.size() > 0 && "Chain should have generated a chain"); 13659 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 13660 } 13661 13662 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 13663 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 13664 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 13665 // Make sure we have something to merge. 13666 if (NumStores < 2) 13667 return false; 13668 13669 // The latest Node in the DAG. 13670 SDLoc DL(StoreNodes[0].MemNode); 13671 13672 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 13673 unsigned SizeInBits = NumStores * ElementSizeBits; 13674 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 13675 13676 EVT StoreTy; 13677 if (UseVector) { 13678 unsigned Elts = NumStores * NumMemElts; 13679 // Get the type for the merged vector store. 13680 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13681 } else 13682 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 13683 13684 SDValue StoredVal; 13685 if (UseVector) { 13686 if (IsConstantSrc) { 13687 SmallVector<SDValue, 8> BuildVector; 13688 for (unsigned I = 0; I != NumStores; ++I) { 13689 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 13690 SDValue Val = St->getValue(); 13691 // If constant is of the wrong type, convert it now. 13692 if (MemVT != Val.getValueType()) { 13693 Val = peekThroughBitcast(Val); 13694 // Deal with constants of wrong size. 13695 if (ElementSizeBits != Val.getValueSizeInBits()) { 13696 EVT IntMemVT = 13697 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 13698 if (isa<ConstantFPSDNode>(Val)) { 13699 // Not clear how to truncate FP values. 13700 return false; 13701 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 13702 Val = DAG.getConstant(C->getAPIntValue() 13703 .zextOrTrunc(Val.getValueSizeInBits()) 13704 .zextOrTrunc(ElementSizeBits), 13705 SDLoc(C), IntMemVT); 13706 } 13707 // Make sure correctly size type is the correct type. 13708 Val = DAG.getBitcast(MemVT, Val); 13709 } 13710 BuildVector.push_back(Val); 13711 } 13712 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 13713 : ISD::BUILD_VECTOR, 13714 DL, StoreTy, BuildVector); 13715 } else { 13716 SmallVector<SDValue, 8> Ops; 13717 for (unsigned i = 0; i < NumStores; ++i) { 13718 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13719 SDValue Val = peekThroughBitcast(St->getValue()); 13720 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 13721 // type MemVT. If the underlying value is not the correct 13722 // type, but it is an extraction of an appropriate vector we 13723 // can recast Val to be of the correct type. This may require 13724 // converting between EXTRACT_VECTOR_ELT and 13725 // EXTRACT_SUBVECTOR. 13726 if ((MemVT != Val.getValueType()) && 13727 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13728 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 13729 SDValue Vec = Val.getOperand(0); 13730 EVT MemVTScalarTy = MemVT.getScalarType(); 13731 SDValue Idx = Val.getOperand(1); 13732 // We may need to add a bitcast here to get types to line up. 13733 if (MemVTScalarTy != Vec.getValueType()) { 13734 unsigned Elts = Vec.getValueType().getSizeInBits() / 13735 MemVTScalarTy.getSizeInBits(); 13736 if (Val.getValueType().isVector() && MemVT.isVector()) { 13737 unsigned IdxC = cast<ConstantSDNode>(Idx)->getZExtValue(); 13738 unsigned NewIdx = 13739 ((uint64_t)IdxC * MemVT.getVectorNumElements()) / Elts; 13740 Idx = DAG.getConstant(NewIdx, SDLoc(Val), Idx.getValueType()); 13741 } 13742 EVT NewVecTy = 13743 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 13744 Vec = DAG.getBitcast(NewVecTy, Vec); 13745 } 13746 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 13747 : ISD::EXTRACT_VECTOR_ELT; 13748 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); 13749 } 13750 Ops.push_back(Val); 13751 } 13752 13753 // Build the extracted vector elements back into a vector. 13754 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 13755 : ISD::BUILD_VECTOR, 13756 DL, StoreTy, Ops); 13757 } 13758 } else { 13759 // We should always use a vector store when merging extracted vector 13760 // elements, so this path implies a store of constants. 13761 assert(IsConstantSrc && "Merged vector elements should use vector store"); 13762 13763 APInt StoreInt(SizeInBits, 0); 13764 13765 // Construct a single integer constant which is made of the smaller 13766 // constant inputs. 13767 bool IsLE = DAG.getDataLayout().isLittleEndian(); 13768 for (unsigned i = 0; i < NumStores; ++i) { 13769 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 13770 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 13771 13772 SDValue Val = St->getValue(); 13773 Val = peekThroughBitcast(Val); 13774 StoreInt <<= ElementSizeBits; 13775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 13776 StoreInt |= C->getAPIntValue() 13777 .zextOrTrunc(ElementSizeBits) 13778 .zextOrTrunc(SizeInBits); 13779 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 13780 StoreInt |= C->getValueAPF() 13781 .bitcastToAPInt() 13782 .zextOrTrunc(ElementSizeBits) 13783 .zextOrTrunc(SizeInBits); 13784 // If fp truncation is necessary give up for now. 13785 if (MemVT.getSizeInBits() != ElementSizeBits) 13786 return false; 13787 } else { 13788 llvm_unreachable("Invalid constant element type"); 13789 } 13790 } 13791 13792 // Create the new Load and Store operations. 13793 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 13794 } 13795 13796 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13797 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 13798 13799 // make sure we use trunc store if it's necessary to be legal. 13800 SDValue NewStore; 13801 if (!UseTrunc) { 13802 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 13803 FirstInChain->getPointerInfo(), 13804 FirstInChain->getAlignment()); 13805 } else { // Must be realized as a trunc store 13806 EVT LegalizedStoredValTy = 13807 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 13808 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 13809 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 13810 SDValue ExtendedStoreVal = 13811 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 13812 LegalizedStoredValTy); 13813 NewStore = DAG.getTruncStore( 13814 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 13815 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 13816 FirstInChain->getAlignment(), 13817 FirstInChain->getMemOperand()->getFlags()); 13818 } 13819 13820 // Replace all merged stores with the new store. 13821 for (unsigned i = 0; i < NumStores; ++i) 13822 CombineTo(StoreNodes[i].MemNode, NewStore); 13823 13824 AddToWorklist(NewChain.getNode()); 13825 return true; 13826 } 13827 13828 void DAGCombiner::getStoreMergeCandidates( 13829 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 13830 SDNode *&RootNode) { 13831 // This holds the base pointer, index, and the offset in bytes from the base 13832 // pointer. 13833 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 13834 EVT MemVT = St->getMemoryVT(); 13835 13836 SDValue Val = peekThroughBitcast(St->getValue()); 13837 // We must have a base and an offset. 13838 if (!BasePtr.getBase().getNode()) 13839 return; 13840 13841 // Do not handle stores to undef base pointers. 13842 if (BasePtr.getBase().isUndef()) 13843 return; 13844 13845 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 13846 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 13847 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 13848 bool IsLoadSrc = isa<LoadSDNode>(Val); 13849 BaseIndexOffset LBasePtr; 13850 // Match on loadbaseptr if relevant. 13851 EVT LoadVT; 13852 if (IsLoadSrc) { 13853 auto *Ld = cast<LoadSDNode>(Val); 13854 LBasePtr = BaseIndexOffset::match(Ld, DAG); 13855 LoadVT = Ld->getMemoryVT(); 13856 // Load and store should be the same type. 13857 if (MemVT != LoadVT) 13858 return; 13859 // Loads must only have one use. 13860 if (!Ld->hasNUsesOfValue(1, 0)) 13861 return; 13862 // The memory operands must not be volatile. 13863 if (Ld->isVolatile() || Ld->isIndexed()) 13864 return; 13865 } 13866 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 13867 int64_t &Offset) -> bool { 13868 if (Other->isVolatile() || Other->isIndexed()) 13869 return false; 13870 SDValue Val = peekThroughBitcast(Other->getValue()); 13871 // Allow merging constants of different types as integers. 13872 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 13873 : Other->getMemoryVT() != MemVT; 13874 if (IsLoadSrc) { 13875 if (NoTypeMatch) 13876 return false; 13877 // The Load's Base Ptr must also match 13878 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 13879 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 13880 if (LoadVT != OtherLd->getMemoryVT()) 13881 return false; 13882 // Loads must only have one use. 13883 if (!OtherLd->hasNUsesOfValue(1, 0)) 13884 return false; 13885 // The memory operands must not be volatile. 13886 if (OtherLd->isVolatile() || OtherLd->isIndexed()) 13887 return false; 13888 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 13889 return false; 13890 } else 13891 return false; 13892 } 13893 if (IsConstantSrc) { 13894 if (NoTypeMatch) 13895 return false; 13896 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 13897 return false; 13898 } 13899 if (IsExtractVecSrc) { 13900 // Do not merge truncated stores here. 13901 if (Other->isTruncatingStore()) 13902 return false; 13903 if (!MemVT.bitsEq(Val.getValueType())) 13904 return false; 13905 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13906 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13907 return false; 13908 } 13909 Ptr = BaseIndexOffset::match(Other, DAG); 13910 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 13911 }; 13912 13913 // We looking for a root node which is an ancestor to all mergable 13914 // stores. We search up through a load, to our root and then down 13915 // through all children. For instance we will find Store{1,2,3} if 13916 // St is Store1, Store2. or Store3 where the root is not a load 13917 // which always true for nonvolatile ops. TODO: Expand 13918 // the search to find all valid candidates through multiple layers of loads. 13919 // 13920 // Root 13921 // |-------|-------| 13922 // Load Load Store3 13923 // | | 13924 // Store1 Store2 13925 // 13926 // FIXME: We should be able to climb and 13927 // descend TokenFactors to find candidates as well. 13928 13929 RootNode = St->getChain().getNode(); 13930 13931 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 13932 RootNode = Ldn->getChain().getNode(); 13933 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13934 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 13935 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 13936 if (I2.getOperandNo() == 0) 13937 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 13938 BaseIndexOffset Ptr; 13939 int64_t PtrDiff; 13940 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13941 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13942 } 13943 } else 13944 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 13945 if (I.getOperandNo() == 0) 13946 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 13947 BaseIndexOffset Ptr; 13948 int64_t PtrDiff; 13949 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 13950 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 13951 } 13952 } 13953 13954 // We need to check that merging these stores does not cause a loop in 13955 // the DAG. Any store candidate may depend on another candidate 13956 // indirectly through its operand (we already consider dependencies 13957 // through the chain). Check in parallel by searching up from 13958 // non-chain operands of candidates. 13959 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 13960 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 13961 SDNode *RootNode) { 13962 // FIXME: We should be able to truncate a full search of 13963 // predecessors by doing a BFS and keeping tabs the originating 13964 // stores from which worklist nodes come from in a similar way to 13965 // TokenFactor simplfication. 13966 13967 SmallPtrSet<const SDNode *, 32> Visited; 13968 SmallVector<const SDNode *, 8> Worklist; 13969 13970 // RootNode is a predecessor to all candidates so we need not search 13971 // past it. Add RootNode (peeking through TokenFactors). Do not count 13972 // these towards size check. 13973 13974 Worklist.push_back(RootNode); 13975 while (!Worklist.empty()) { 13976 auto N = Worklist.pop_back_val(); 13977 if (N->getOpcode() == ISD::TokenFactor) { 13978 for (SDValue Op : N->ops()) 13979 Worklist.push_back(Op.getNode()); 13980 } 13981 Visited.insert(N); 13982 } 13983 13984 // Don't count pruning nodes towards max. 13985 unsigned int Max = 1024 + Visited.size(); 13986 // Search Ops of store candidates. 13987 for (unsigned i = 0; i < NumStores; ++i) { 13988 SDNode *N = StoreNodes[i].MemNode; 13989 // Of the 4 Store Operands: 13990 // * Chain (Op 0) -> We have already considered these 13991 // in candidate selection and can be 13992 // safely ignored 13993 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 13994 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant 13995 // and so no cycles are possible. 13996 // * (Op 3) -> appears to always be undef. Cannot be source of cycle. 13997 // 13998 // Thus we need only check predecessors of the value operands. 13999 auto *Op = N->getOperand(1).getNode(); 14000 if (Visited.insert(Op).second) 14001 Worklist.push_back(Op); 14002 } 14003 // Search through DAG. We can stop early if we find a store node. 14004 for (unsigned i = 0; i < NumStores; ++i) 14005 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 14006 Max)) 14007 return false; 14008 return true; 14009 } 14010 14011 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 14012 if (OptLevel == CodeGenOpt::None) 14013 return false; 14014 14015 EVT MemVT = St->getMemoryVT(); 14016 int64_t ElementSizeBytes = MemVT.getStoreSize(); 14017 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14018 14019 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 14020 return false; 14021 14022 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 14023 Attribute::NoImplicitFloat); 14024 14025 // This function cannot currently deal with non-byte-sized memory sizes. 14026 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 14027 return false; 14028 14029 if (!MemVT.isSimple()) 14030 return false; 14031 14032 // Perform an early exit check. Do not bother looking at stored values that 14033 // are not constants, loads, or extracted vector elements. 14034 SDValue StoredVal = peekThroughBitcast(St->getValue()); 14035 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 14036 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 14037 isa<ConstantFPSDNode>(StoredVal); 14038 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14039 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14040 14041 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 14042 return false; 14043 14044 SmallVector<MemOpLink, 8> StoreNodes; 14045 SDNode *RootNode; 14046 // Find potential store merge candidates by searching through chain sub-DAG 14047 getStoreMergeCandidates(St, StoreNodes, RootNode); 14048 14049 // Check if there is anything to merge. 14050 if (StoreNodes.size() < 2) 14051 return false; 14052 14053 // Sort the memory operands according to their distance from the 14054 // base pointer. 14055 llvm::sort(StoreNodes.begin(), StoreNodes.end(), 14056 [](MemOpLink LHS, MemOpLink RHS) { 14057 return LHS.OffsetFromBase < RHS.OffsetFromBase; 14058 }); 14059 14060 // Store Merge attempts to merge the lowest stores. This generally 14061 // works out as if successful, as the remaining stores are checked 14062 // after the first collection of stores is merged. However, in the 14063 // case that a non-mergeable store is found first, e.g., {p[-2], 14064 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 14065 // mergeable cases. To prevent this, we prune such stores from the 14066 // front of StoreNodes here. 14067 14068 bool RV = false; 14069 while (StoreNodes.size() > 1) { 14070 unsigned StartIdx = 0; 14071 while ((StartIdx + 1 < StoreNodes.size()) && 14072 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 14073 StoreNodes[StartIdx + 1].OffsetFromBase) 14074 ++StartIdx; 14075 14076 // Bail if we don't have enough candidates to merge. 14077 if (StartIdx + 1 >= StoreNodes.size()) 14078 return RV; 14079 14080 if (StartIdx) 14081 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 14082 14083 // Scan the memory operations on the chain and find the first 14084 // non-consecutive store memory address. 14085 unsigned NumConsecutiveStores = 1; 14086 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 14087 // Check that the addresses are consecutive starting from the second 14088 // element in the list of stores. 14089 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 14090 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 14091 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14092 break; 14093 NumConsecutiveStores = i + 1; 14094 } 14095 14096 if (NumConsecutiveStores < 2) { 14097 StoreNodes.erase(StoreNodes.begin(), 14098 StoreNodes.begin() + NumConsecutiveStores); 14099 continue; 14100 } 14101 14102 // The node with the lowest store address. 14103 LLVMContext &Context = *DAG.getContext(); 14104 const DataLayout &DL = DAG.getDataLayout(); 14105 14106 // Store the constants into memory as one consecutive store. 14107 if (IsConstantSrc) { 14108 while (NumConsecutiveStores >= 2) { 14109 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14110 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14111 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14112 unsigned LastLegalType = 1; 14113 unsigned LastLegalVectorType = 1; 14114 bool LastIntegerTrunc = false; 14115 bool NonZero = false; 14116 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 14117 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14118 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 14119 SDValue StoredVal = ST->getValue(); 14120 bool IsElementZero = false; 14121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 14122 IsElementZero = C->isNullValue(); 14123 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 14124 IsElementZero = C->getConstantFPValue()->isNullValue(); 14125 if (IsElementZero) { 14126 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 14127 FirstZeroAfterNonZero = i; 14128 } 14129 NonZero |= !IsElementZero; 14130 14131 // Find a legal type for the constant store. 14132 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14133 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14134 bool IsFast = false; 14135 14136 // Break early when size is too large to be legal. 14137 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14138 break; 14139 14140 if (TLI.isTypeLegal(StoreTy) && 14141 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14142 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14143 FirstStoreAlign, &IsFast) && 14144 IsFast) { 14145 LastIntegerTrunc = false; 14146 LastLegalType = i + 1; 14147 // Or check whether a truncstore is legal. 14148 } else if (TLI.getTypeAction(Context, StoreTy) == 14149 TargetLowering::TypePromoteInteger) { 14150 EVT LegalizedStoredValTy = 14151 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 14152 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14153 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14154 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14155 FirstStoreAlign, &IsFast) && 14156 IsFast) { 14157 LastIntegerTrunc = true; 14158 LastLegalType = i + 1; 14159 } 14160 } 14161 14162 // We only use vectors if the constant is known to be zero or the 14163 // target allows it and the function is not marked with the 14164 // noimplicitfloat attribute. 14165 if ((!NonZero || 14166 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 14167 !NoVectors) { 14168 // Find a legal type for the vector store. 14169 unsigned Elts = (i + 1) * NumMemElts; 14170 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14171 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 14172 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14173 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14174 FirstStoreAlign, &IsFast) && 14175 IsFast) 14176 LastLegalVectorType = i + 1; 14177 } 14178 } 14179 14180 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 14181 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 14182 14183 // Check if we found a legal integer type that creates a meaningful 14184 // merge. 14185 if (NumElem < 2) { 14186 // We know that candidate stores are in order and of correct 14187 // shape. While there is no mergeable sequence from the 14188 // beginning one may start later in the sequence. The only 14189 // reason a merge of size N could have failed where another of 14190 // the same size would not have, is if the alignment has 14191 // improved or we've dropped a non-zero value. Drop as many 14192 // candidates as we can here. 14193 unsigned NumSkip = 1; 14194 while ( 14195 (NumSkip < NumConsecutiveStores) && 14196 (NumSkip < FirstZeroAfterNonZero) && 14197 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14198 NumSkip++; 14199 14200 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14201 NumConsecutiveStores -= NumSkip; 14202 continue; 14203 } 14204 14205 // Check that we can merge these candidates without causing a cycle. 14206 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14207 RootNode)) { 14208 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14209 NumConsecutiveStores -= NumElem; 14210 continue; 14211 } 14212 14213 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true, 14214 UseVector, LastIntegerTrunc); 14215 14216 // Remove merged stores for next iteration. 14217 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14218 NumConsecutiveStores -= NumElem; 14219 } 14220 continue; 14221 } 14222 14223 // When extracting multiple vector elements, try to store them 14224 // in one vector store rather than a sequence of scalar stores. 14225 if (IsExtractVecSrc) { 14226 // Loop on Consecutive Stores on success. 14227 while (NumConsecutiveStores >= 2) { 14228 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14229 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14230 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14231 unsigned NumStoresToMerge = 1; 14232 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14233 // Find a legal type for the vector store. 14234 unsigned Elts = (i + 1) * NumMemElts; 14235 EVT Ty = 14236 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 14237 bool IsFast; 14238 14239 // Break early when size is too large to be legal. 14240 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 14241 break; 14242 14243 if (TLI.isTypeLegal(Ty) && 14244 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14245 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14246 FirstStoreAlign, &IsFast) && 14247 IsFast) 14248 NumStoresToMerge = i + 1; 14249 } 14250 14251 // Check if we found a legal integer type creating a meaningful 14252 // merge. 14253 if (NumStoresToMerge < 2) { 14254 // We know that candidate stores are in order and of correct 14255 // shape. While there is no mergeable sequence from the 14256 // beginning one may start later in the sequence. The only 14257 // reason a merge of size N could have failed where another of 14258 // the same size would not have, is if the alignment has 14259 // improved. Drop as many candidates as we can here. 14260 unsigned NumSkip = 1; 14261 while ( 14262 (NumSkip < NumConsecutiveStores) && 14263 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14264 NumSkip++; 14265 14266 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14267 NumConsecutiveStores -= NumSkip; 14268 continue; 14269 } 14270 14271 // Check that we can merge these candidates without causing a cycle. 14272 if (!checkMergeStoreCandidatesForDependencies( 14273 StoreNodes, NumStoresToMerge, RootNode)) { 14274 StoreNodes.erase(StoreNodes.begin(), 14275 StoreNodes.begin() + NumStoresToMerge); 14276 NumConsecutiveStores -= NumStoresToMerge; 14277 continue; 14278 } 14279 14280 RV |= MergeStoresOfConstantsOrVecElts( 14281 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 14282 14283 StoreNodes.erase(StoreNodes.begin(), 14284 StoreNodes.begin() + NumStoresToMerge); 14285 NumConsecutiveStores -= NumStoresToMerge; 14286 } 14287 continue; 14288 } 14289 14290 // Below we handle the case of multiple consecutive stores that 14291 // come from multiple consecutive loads. We merge them into a single 14292 // wide load and a single wide store. 14293 14294 // Look for load nodes which are used by the stored values. 14295 SmallVector<MemOpLink, 8> LoadNodes; 14296 14297 // Find acceptable loads. Loads need to have the same chain (token factor), 14298 // must not be zext, volatile, indexed, and they must be consecutive. 14299 BaseIndexOffset LdBasePtr; 14300 14301 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14302 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 14303 SDValue Val = peekThroughBitcast(St->getValue()); 14304 LoadSDNode *Ld = cast<LoadSDNode>(Val); 14305 14306 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 14307 // If this is not the first ptr that we check. 14308 int64_t LdOffset = 0; 14309 if (LdBasePtr.getBase().getNode()) { 14310 // The base ptr must be the same. 14311 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 14312 break; 14313 } else { 14314 // Check that all other base pointers are the same as this one. 14315 LdBasePtr = LdPtr; 14316 } 14317 14318 // We found a potential memory operand to merge. 14319 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 14320 } 14321 14322 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 14323 // If we have load/store pair instructions and we only have two values, 14324 // don't bother merging. 14325 unsigned RequiredAlignment; 14326 if (LoadNodes.size() == 2 && 14327 TLI.hasPairedLoad(MemVT, RequiredAlignment) && 14328 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 14329 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 14330 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 14331 break; 14332 } 14333 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14334 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14335 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14336 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 14337 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 14338 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 14339 14340 // Scan the memory operations on the chain and find the first 14341 // non-consecutive load memory address. These variables hold the index in 14342 // the store node array. 14343 14344 unsigned LastConsecutiveLoad = 1; 14345 14346 // This variable refers to the size and not index in the array. 14347 unsigned LastLegalVectorType = 1; 14348 unsigned LastLegalIntegerType = 1; 14349 bool isDereferenceable = true; 14350 bool DoIntegerTruncate = false; 14351 StartAddress = LoadNodes[0].OffsetFromBase; 14352 SDValue FirstChain = FirstLoad->getChain(); 14353 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 14354 // All loads must share the same chain. 14355 if (LoadNodes[i].MemNode->getChain() != FirstChain) 14356 break; 14357 14358 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 14359 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14360 break; 14361 LastConsecutiveLoad = i; 14362 14363 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 14364 isDereferenceable = false; 14365 14366 // Find a legal type for the vector store. 14367 unsigned Elts = (i + 1) * NumMemElts; 14368 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14369 14370 // Break early when size is too large to be legal. 14371 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14372 break; 14373 14374 bool IsFastSt, IsFastLd; 14375 if (TLI.isTypeLegal(StoreTy) && 14376 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14377 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14378 FirstStoreAlign, &IsFastSt) && 14379 IsFastSt && 14380 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14381 FirstLoadAlign, &IsFastLd) && 14382 IsFastLd) { 14383 LastLegalVectorType = i + 1; 14384 } 14385 14386 // Find a legal type for the integer store. 14387 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14388 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14389 if (TLI.isTypeLegal(StoreTy) && 14390 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14391 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14392 FirstStoreAlign, &IsFastSt) && 14393 IsFastSt && 14394 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14395 FirstLoadAlign, &IsFastLd) && 14396 IsFastLd) { 14397 LastLegalIntegerType = i + 1; 14398 DoIntegerTruncate = false; 14399 // Or check whether a truncstore and extload is legal. 14400 } else if (TLI.getTypeAction(Context, StoreTy) == 14401 TargetLowering::TypePromoteInteger) { 14402 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 14403 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14404 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14405 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, 14406 StoreTy) && 14407 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, 14408 StoreTy) && 14409 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 14410 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14411 FirstStoreAlign, &IsFastSt) && 14412 IsFastSt && 14413 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14414 FirstLoadAlign, &IsFastLd) && 14415 IsFastLd) { 14416 LastLegalIntegerType = i + 1; 14417 DoIntegerTruncate = true; 14418 } 14419 } 14420 } 14421 14422 // Only use vector types if the vector type is larger than the integer 14423 // type. If they are the same, use integers. 14424 bool UseVectorTy = 14425 LastLegalVectorType > LastLegalIntegerType && !NoVectors; 14426 unsigned LastLegalType = 14427 std::max(LastLegalVectorType, LastLegalIntegerType); 14428 14429 // We add +1 here because the LastXXX variables refer to location while 14430 // the NumElem refers to array/index size. 14431 unsigned NumElem = 14432 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 14433 NumElem = std::min(LastLegalType, NumElem); 14434 14435 if (NumElem < 2) { 14436 // We know that candidate stores are in order and of correct 14437 // shape. While there is no mergeable sequence from the 14438 // beginning one may start later in the sequence. The only 14439 // reason a merge of size N could have failed where another of 14440 // the same size would not have is if the alignment or either 14441 // the load or store has improved. Drop as many candidates as we 14442 // can here. 14443 unsigned NumSkip = 1; 14444 while ((NumSkip < LoadNodes.size()) && 14445 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 14446 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14447 NumSkip++; 14448 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14449 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 14450 NumConsecutiveStores -= NumSkip; 14451 continue; 14452 } 14453 14454 // Check that we can merge these candidates without causing a cycle. 14455 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14456 RootNode)) { 14457 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14458 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14459 NumConsecutiveStores -= NumElem; 14460 continue; 14461 } 14462 14463 // Find if it is better to use vectors or integers to load and store 14464 // to memory. 14465 EVT JointMemOpVT; 14466 if (UseVectorTy) { 14467 // Find a legal type for the vector store. 14468 unsigned Elts = NumElem * NumMemElts; 14469 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14470 } else { 14471 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 14472 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 14473 } 14474 14475 SDLoc LoadDL(LoadNodes[0].MemNode); 14476 SDLoc StoreDL(StoreNodes[0].MemNode); 14477 14478 // The merged loads are required to have the same incoming chain, so 14479 // using the first's chain is acceptable. 14480 14481 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 14482 AddToWorklist(NewStoreChain.getNode()); 14483 14484 MachineMemOperand::Flags MMOFlags = 14485 isDereferenceable ? MachineMemOperand::MODereferenceable 14486 : MachineMemOperand::MONone; 14487 14488 SDValue NewLoad, NewStore; 14489 if (UseVectorTy || !DoIntegerTruncate) { 14490 NewLoad = 14491 DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 14492 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 14493 FirstLoadAlign, MMOFlags); 14494 NewStore = DAG.getStore( 14495 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 14496 FirstInChain->getPointerInfo(), FirstStoreAlign); 14497 } else { // This must be the truncstore/extload case 14498 EVT ExtendedTy = 14499 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 14500 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 14501 FirstLoad->getChain(), FirstLoad->getBasePtr(), 14502 FirstLoad->getPointerInfo(), JointMemOpVT, 14503 FirstLoadAlign, MMOFlags); 14504 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 14505 FirstInChain->getBasePtr(), 14506 FirstInChain->getPointerInfo(), 14507 JointMemOpVT, FirstInChain->getAlignment(), 14508 FirstInChain->getMemOperand()->getFlags()); 14509 } 14510 14511 // Transfer chain users from old loads to the new load. 14512 for (unsigned i = 0; i < NumElem; ++i) { 14513 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 14514 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 14515 SDValue(NewLoad.getNode(), 1)); 14516 } 14517 14518 // Replace the all stores with the new store. Recursively remove 14519 // corresponding value if its no longer used. 14520 for (unsigned i = 0; i < NumElem; ++i) { 14521 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 14522 CombineTo(StoreNodes[i].MemNode, NewStore); 14523 if (Val.getNode()->use_empty()) 14524 recursivelyDeleteUnusedNodes(Val.getNode()); 14525 } 14526 14527 RV = true; 14528 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14529 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14530 NumConsecutiveStores -= NumElem; 14531 } 14532 } 14533 return RV; 14534 } 14535 14536 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 14537 SDLoc SL(ST); 14538 SDValue ReplStore; 14539 14540 // Replace the chain to avoid dependency. 14541 if (ST->isTruncatingStore()) { 14542 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 14543 ST->getBasePtr(), ST->getMemoryVT(), 14544 ST->getMemOperand()); 14545 } else { 14546 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 14547 ST->getMemOperand()); 14548 } 14549 14550 // Create token to keep both nodes around. 14551 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 14552 MVT::Other, ST->getChain(), ReplStore); 14553 14554 // Make sure the new and old chains are cleaned up. 14555 AddToWorklist(Token.getNode()); 14556 14557 // Don't add users to work list. 14558 return CombineTo(ST, Token, false); 14559 } 14560 14561 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 14562 SDValue Value = ST->getValue(); 14563 if (Value.getOpcode() == ISD::TargetConstantFP) 14564 return SDValue(); 14565 14566 SDLoc DL(ST); 14567 14568 SDValue Chain = ST->getChain(); 14569 SDValue Ptr = ST->getBasePtr(); 14570 14571 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 14572 14573 // NOTE: If the original store is volatile, this transform must not increase 14574 // the number of stores. For example, on x86-32 an f64 can be stored in one 14575 // processor operation but an i64 (which is not legal) requires two. So the 14576 // transform should not be done in this case. 14577 14578 SDValue Tmp; 14579 switch (CFP->getSimpleValueType(0).SimpleTy) { 14580 default: 14581 llvm_unreachable("Unknown FP type"); 14582 case MVT::f16: // We don't do this for these yet. 14583 case MVT::f80: 14584 case MVT::f128: 14585 case MVT::ppcf128: 14586 return SDValue(); 14587 case MVT::f32: 14588 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 14589 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14590 ; 14591 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 14592 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 14593 MVT::i32); 14594 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 14595 } 14596 14597 return SDValue(); 14598 case MVT::f64: 14599 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 14600 !ST->isVolatile()) || 14601 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 14602 ; 14603 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 14604 getZExtValue(), SDLoc(CFP), MVT::i64); 14605 return DAG.getStore(Chain, DL, Tmp, 14606 Ptr, ST->getMemOperand()); 14607 } 14608 14609 if (!ST->isVolatile() && 14610 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14611 // Many FP stores are not made apparent until after legalize, e.g. for 14612 // argument passing. Since this is so common, custom legalize the 14613 // 64-bit integer store into two 32-bit stores. 14614 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 14615 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 14616 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 14617 if (DAG.getDataLayout().isBigEndian()) 14618 std::swap(Lo, Hi); 14619 14620 unsigned Alignment = ST->getAlignment(); 14621 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 14622 AAMDNodes AAInfo = ST->getAAInfo(); 14623 14624 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14625 ST->getAlignment(), MMOFlags, AAInfo); 14626 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14627 DAG.getConstant(4, DL, Ptr.getValueType())); 14628 Alignment = MinAlign(Alignment, 4U); 14629 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 14630 ST->getPointerInfo().getWithOffset(4), 14631 Alignment, MMOFlags, AAInfo); 14632 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 14633 St0, St1); 14634 } 14635 14636 return SDValue(); 14637 } 14638 } 14639 14640 SDValue DAGCombiner::visitSTORE(SDNode *N) { 14641 StoreSDNode *ST = cast<StoreSDNode>(N); 14642 SDValue Chain = ST->getChain(); 14643 SDValue Value = ST->getValue(); 14644 SDValue Ptr = ST->getBasePtr(); 14645 14646 // If this is a store of a bit convert, store the input value if the 14647 // resultant store does not need a higher alignment than the original. 14648 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 14649 ST->isUnindexed()) { 14650 EVT SVT = Value.getOperand(0).getValueType(); 14651 if (((!LegalOperations && !ST->isVolatile()) || 14652 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 14653 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 14654 unsigned OrigAlign = ST->getAlignment(); 14655 bool Fast = false; 14656 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 14657 ST->getAddressSpace(), OrigAlign, &Fast) && 14658 Fast) { 14659 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 14660 ST->getPointerInfo(), OrigAlign, 14661 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 14662 } 14663 } 14664 } 14665 14666 // Turn 'store undef, Ptr' -> nothing. 14667 if (Value.isUndef() && ST->isUnindexed()) 14668 return Chain; 14669 14670 // Try to infer better alignment information than the store already has. 14671 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 14672 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 14673 if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) { 14674 SDValue NewStore = 14675 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 14676 ST->getMemoryVT(), Align, 14677 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 14678 // NewStore will always be N as we are only refining the alignment 14679 assert(NewStore.getNode() == N); 14680 (void)NewStore; 14681 } 14682 } 14683 } 14684 14685 // Try transforming a pair floating point load / store ops to integer 14686 // load / store ops. 14687 if (SDValue NewST = TransformFPLoadStorePair(N)) 14688 return NewST; 14689 14690 if (ST->isUnindexed()) { 14691 // Walk up chain skipping non-aliasing memory nodes, on this store and any 14692 // adjacent stores. 14693 if (findBetterNeighborChains(ST)) { 14694 // replaceStoreChain uses CombineTo, which handled all of the worklist 14695 // manipulation. Return the original node to not do anything else. 14696 return SDValue(ST, 0); 14697 } 14698 Chain = ST->getChain(); 14699 } 14700 14701 // FIXME: is there such a thing as a truncating indexed store? 14702 if (ST->isTruncatingStore() && ST->isUnindexed() && 14703 Value.getValueType().isInteger()) { 14704 // See if we can simplify the input to this truncstore with knowledge that 14705 // only the low bits are being used. For example: 14706 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 14707 SDValue Shorter = DAG.GetDemandedBits( 14708 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 14709 ST->getMemoryVT().getScalarSizeInBits())); 14710 AddToWorklist(Value.getNode()); 14711 if (Shorter.getNode()) 14712 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 14713 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 14714 14715 // Otherwise, see if we can simplify the operation with 14716 // SimplifyDemandedBits, which only works if the value has a single use. 14717 if (SimplifyDemandedBits( 14718 Value, 14719 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 14720 ST->getMemoryVT().getScalarSizeInBits()))) { 14721 // Re-visit the store if anything changed and the store hasn't been merged 14722 // with another node (N is deleted) SimplifyDemandedBits will add Value's 14723 // node back to the worklist if necessary, but we also need to re-visit 14724 // the Store node itself. 14725 if (N->getOpcode() != ISD::DELETED_NODE) 14726 AddToWorklist(N); 14727 return SDValue(N, 0); 14728 } 14729 } 14730 14731 // If this is a load followed by a store to the same location, then the store 14732 // is dead/noop. 14733 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 14734 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 14735 ST->isUnindexed() && !ST->isVolatile() && 14736 // There can't be any side effects between the load and store, such as 14737 // a call or store. 14738 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 14739 // The store is dead, remove it. 14740 return Chain; 14741 } 14742 } 14743 14744 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 14745 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 14746 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 14747 ST->getMemoryVT() == ST1->getMemoryVT()) { 14748 // If this is a store followed by a store with the same value to the same 14749 // location, then the store is dead/noop. 14750 if (ST1->getValue() == Value) { 14751 // The store is dead, remove it. 14752 return Chain; 14753 } 14754 14755 // If this is a store who's preceeding store to the same location 14756 // and no one other node is chained to that store we can effectively 14757 // drop the store. Do not remove stores to undef as they may be used as 14758 // data sinks. 14759 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 14760 !ST1->getBasePtr().isUndef()) { 14761 // ST1 is fully overwritten and can be elided. Combine with it's chain 14762 // value. 14763 CombineTo(ST1, ST1->getChain()); 14764 return SDValue(); 14765 } 14766 } 14767 } 14768 14769 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 14770 // truncating store. We can do this even if this is already a truncstore. 14771 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 14772 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 14773 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 14774 ST->getMemoryVT())) { 14775 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 14776 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 14777 } 14778 14779 // Always perform this optimization before types are legal. If the target 14780 // prefers, also try this after legalization to catch stores that were created 14781 // by intrinsics or other nodes. 14782 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 14783 while (true) { 14784 // There can be multiple store sequences on the same chain. 14785 // Keep trying to merge store sequences until we are unable to do so 14786 // or until we merge the last store on the chain. 14787 bool Changed = MergeConsecutiveStores(ST); 14788 if (!Changed) break; 14789 // Return N as merge only uses CombineTo and no worklist clean 14790 // up is necessary. 14791 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 14792 return SDValue(N, 0); 14793 } 14794 } 14795 14796 // Try transforming N to an indexed store. 14797 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 14798 return SDValue(N, 0); 14799 14800 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 14801 // 14802 // Make sure to do this only after attempting to merge stores in order to 14803 // avoid changing the types of some subset of stores due to visit order, 14804 // preventing their merging. 14805 if (isa<ConstantFPSDNode>(ST->getValue())) { 14806 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 14807 return NewSt; 14808 } 14809 14810 if (SDValue NewSt = splitMergedValStore(ST)) 14811 return NewSt; 14812 14813 return ReduceLoadOpStoreWidth(N); 14814 } 14815 14816 /// For the instruction sequence of store below, F and I values 14817 /// are bundled together as an i64 value before being stored into memory. 14818 /// Sometimes it is more efficent to generate separate stores for F and I, 14819 /// which can remove the bitwise instructions or sink them to colder places. 14820 /// 14821 /// (store (or (zext (bitcast F to i32) to i64), 14822 /// (shl (zext I to i64), 32)), addr) --> 14823 /// (store F, addr) and (store I, addr+4) 14824 /// 14825 /// Similarly, splitting for other merged store can also be beneficial, like: 14826 /// For pair of {i32, i32}, i64 store --> two i32 stores. 14827 /// For pair of {i32, i16}, i64 store --> two i32 stores. 14828 /// For pair of {i16, i16}, i32 store --> two i16 stores. 14829 /// For pair of {i16, i8}, i32 store --> two i16 stores. 14830 /// For pair of {i8, i8}, i16 store --> two i8 stores. 14831 /// 14832 /// We allow each target to determine specifically which kind of splitting is 14833 /// supported. 14834 /// 14835 /// The store patterns are commonly seen from the simple code snippet below 14836 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 14837 /// void goo(const std::pair<int, float> &); 14838 /// hoo() { 14839 /// ... 14840 /// goo(std::make_pair(tmp, ftmp)); 14841 /// ... 14842 /// } 14843 /// 14844 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 14845 if (OptLevel == CodeGenOpt::None) 14846 return SDValue(); 14847 14848 SDValue Val = ST->getValue(); 14849 SDLoc DL(ST); 14850 14851 // Match OR operand. 14852 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 14853 return SDValue(); 14854 14855 // Match SHL operand and get Lower and Higher parts of Val. 14856 SDValue Op1 = Val.getOperand(0); 14857 SDValue Op2 = Val.getOperand(1); 14858 SDValue Lo, Hi; 14859 if (Op1.getOpcode() != ISD::SHL) { 14860 std::swap(Op1, Op2); 14861 if (Op1.getOpcode() != ISD::SHL) 14862 return SDValue(); 14863 } 14864 Lo = Op2; 14865 Hi = Op1.getOperand(0); 14866 if (!Op1.hasOneUse()) 14867 return SDValue(); 14868 14869 // Match shift amount to HalfValBitSize. 14870 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 14871 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 14872 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 14873 return SDValue(); 14874 14875 // Lo and Hi are zero-extended from int with size less equal than 32 14876 // to i64. 14877 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 14878 !Lo.getOperand(0).getValueType().isScalarInteger() || 14879 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 14880 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 14881 !Hi.getOperand(0).getValueType().isScalarInteger() || 14882 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 14883 return SDValue(); 14884 14885 // Use the EVT of low and high parts before bitcast as the input 14886 // of target query. 14887 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 14888 ? Lo.getOperand(0).getValueType() 14889 : Lo.getValueType(); 14890 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 14891 ? Hi.getOperand(0).getValueType() 14892 : Hi.getValueType(); 14893 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 14894 return SDValue(); 14895 14896 // Start to split store. 14897 unsigned Alignment = ST->getAlignment(); 14898 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 14899 AAMDNodes AAInfo = ST->getAAInfo(); 14900 14901 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 14902 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 14903 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 14904 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 14905 14906 SDValue Chain = ST->getChain(); 14907 SDValue Ptr = ST->getBasePtr(); 14908 // Lower value store. 14909 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14910 ST->getAlignment(), MMOFlags, AAInfo); 14911 Ptr = 14912 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14913 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 14914 // Higher value store. 14915 SDValue St1 = 14916 DAG.getStore(St0, DL, Hi, Ptr, 14917 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 14918 Alignment / 2, MMOFlags, AAInfo); 14919 return St1; 14920 } 14921 14922 /// Convert a disguised subvector insertion into a shuffle: 14923 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 14924 /// bitcast(shuffle (bitcast V), (extended X), Mask) 14925 /// Note: We do not use an insert_subvector node because that requires a legal 14926 /// subvector type. 14927 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 14928 SDValue InsertVal = N->getOperand(1); 14929 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 14930 !InsertVal.getOperand(0).getValueType().isVector()) 14931 return SDValue(); 14932 14933 SDValue SubVec = InsertVal.getOperand(0); 14934 SDValue DestVec = N->getOperand(0); 14935 EVT SubVecVT = SubVec.getValueType(); 14936 EVT VT = DestVec.getValueType(); 14937 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 14938 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 14939 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 14940 14941 // Step 1: Create a shuffle mask that implements this insert operation. The 14942 // vector that we are inserting into will be operand 0 of the shuffle, so 14943 // those elements are just 'i'. The inserted subvector is in the first 14944 // positions of operand 1 of the shuffle. Example: 14945 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 14946 SmallVector<int, 16> Mask(NumMaskVals); 14947 for (unsigned i = 0; i != NumMaskVals; ++i) { 14948 if (i / NumSrcElts == InsIndex) 14949 Mask[i] = (i % NumSrcElts) + NumMaskVals; 14950 else 14951 Mask[i] = i; 14952 } 14953 14954 // Bail out if the target can not handle the shuffle we want to create. 14955 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 14956 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 14957 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 14958 return SDValue(); 14959 14960 // Step 2: Create a wide vector from the inserted source vector by appending 14961 // undefined elements. This is the same size as our destination vector. 14962 SDLoc DL(N); 14963 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 14964 ConcatOps[0] = SubVec; 14965 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 14966 14967 // Step 3: Shuffle in the padded subvector. 14968 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 14969 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 14970 AddToWorklist(PaddedSubV.getNode()); 14971 AddToWorklist(DestVecBC.getNode()); 14972 AddToWorklist(Shuf.getNode()); 14973 return DAG.getBitcast(VT, Shuf); 14974 } 14975 14976 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 14977 SDValue InVec = N->getOperand(0); 14978 SDValue InVal = N->getOperand(1); 14979 SDValue EltNo = N->getOperand(2); 14980 SDLoc DL(N); 14981 14982 // If the inserted element is an UNDEF, just use the input vector. 14983 if (InVal.isUndef()) 14984 return InVec; 14985 14986 EVT VT = InVec.getValueType(); 14987 14988 // Remove redundant insertions: 14989 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 14990 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 14991 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 14992 return InVec; 14993 14994 // We must know which element is being inserted for folds below here. 14995 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 14996 if (!IndexC) 14997 return SDValue(); 14998 unsigned Elt = IndexC->getZExtValue(); 14999 15000 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 15001 return Shuf; 15002 15003 // Canonicalize insert_vector_elt dag nodes. 15004 // Example: 15005 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 15006 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 15007 // 15008 // Do this only if the child insert_vector node has one use; also 15009 // do this only if indices are both constants and Idx1 < Idx0. 15010 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 15011 && isa<ConstantSDNode>(InVec.getOperand(2))) { 15012 unsigned OtherElt = InVec.getConstantOperandVal(2); 15013 if (Elt < OtherElt) { 15014 // Swap nodes. 15015 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 15016 InVec.getOperand(0), InVal, EltNo); 15017 AddToWorklist(NewOp.getNode()); 15018 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 15019 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 15020 } 15021 } 15022 15023 // If we can't generate a legal BUILD_VECTOR, exit 15024 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 15025 return SDValue(); 15026 15027 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 15028 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 15029 // vector elements. 15030 SmallVector<SDValue, 8> Ops; 15031 // Do not combine these two vectors if the output vector will not replace 15032 // the input vector. 15033 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 15034 Ops.append(InVec.getNode()->op_begin(), 15035 InVec.getNode()->op_end()); 15036 } else if (InVec.isUndef()) { 15037 unsigned NElts = VT.getVectorNumElements(); 15038 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 15039 } else { 15040 return SDValue(); 15041 } 15042 15043 // Insert the element 15044 if (Elt < Ops.size()) { 15045 // All the operands of BUILD_VECTOR must have the same type; 15046 // we enforce that here. 15047 EVT OpVT = Ops[0].getValueType(); 15048 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 15049 } 15050 15051 // Return the new vector 15052 return DAG.getBuildVector(VT, DL, Ops); 15053 } 15054 15055 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 15056 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 15057 assert(!OriginalLoad->isVolatile()); 15058 15059 EVT ResultVT = EVE->getValueType(0); 15060 EVT VecEltVT = InVecVT.getVectorElementType(); 15061 unsigned Align = OriginalLoad->getAlignment(); 15062 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 15063 VecEltVT.getTypeForEVT(*DAG.getContext())); 15064 15065 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 15066 return SDValue(); 15067 15068 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 15069 ISD::NON_EXTLOAD : ISD::EXTLOAD; 15070 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 15071 return SDValue(); 15072 15073 Align = NewAlign; 15074 15075 SDValue NewPtr = OriginalLoad->getBasePtr(); 15076 SDValue Offset; 15077 EVT PtrType = NewPtr.getValueType(); 15078 MachinePointerInfo MPI; 15079 SDLoc DL(EVE); 15080 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 15081 int Elt = ConstEltNo->getZExtValue(); 15082 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 15083 Offset = DAG.getConstant(PtrOff, DL, PtrType); 15084 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 15085 } else { 15086 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 15087 Offset = DAG.getNode( 15088 ISD::MUL, DL, PtrType, Offset, 15089 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 15090 MPI = OriginalLoad->getPointerInfo(); 15091 } 15092 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 15093 15094 // The replacement we need to do here is a little tricky: we need to 15095 // replace an extractelement of a load with a load. 15096 // Use ReplaceAllUsesOfValuesWith to do the replacement. 15097 // Note that this replacement assumes that the extractvalue is the only 15098 // use of the load; that's okay because we don't want to perform this 15099 // transformation in other cases anyway. 15100 SDValue Load; 15101 SDValue Chain; 15102 if (ResultVT.bitsGT(VecEltVT)) { 15103 // If the result type of vextract is wider than the load, then issue an 15104 // extending load instead. 15105 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 15106 VecEltVT) 15107 ? ISD::ZEXTLOAD 15108 : ISD::EXTLOAD; 15109 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 15110 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 15111 Align, OriginalLoad->getMemOperand()->getFlags(), 15112 OriginalLoad->getAAInfo()); 15113 Chain = Load.getValue(1); 15114 } else { 15115 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 15116 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 15117 OriginalLoad->getAAInfo()); 15118 Chain = Load.getValue(1); 15119 if (ResultVT.bitsLT(VecEltVT)) 15120 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 15121 else 15122 Load = DAG.getBitcast(ResultVT, Load); 15123 } 15124 WorklistRemover DeadNodes(*this); 15125 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 15126 SDValue To[] = { Load, Chain }; 15127 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 15128 // Since we're explicitly calling ReplaceAllUses, add the new node to the 15129 // worklist explicitly as well. 15130 AddToWorklist(Load.getNode()); 15131 AddUsersToWorklist(Load.getNode()); // Add users too 15132 // Make sure to revisit this node to clean it up; it will usually be dead. 15133 AddToWorklist(EVE); 15134 ++OpsNarrowed; 15135 return SDValue(EVE, 0); 15136 } 15137 15138 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 15139 // (vextract (scalar_to_vector val, 0) -> val 15140 SDValue InVec = N->getOperand(0); 15141 EVT VT = InVec.getValueType(); 15142 EVT NVT = N->getValueType(0); 15143 15144 if (InVec.isUndef()) 15145 return DAG.getUNDEF(NVT); 15146 15147 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15148 // Check if the result type doesn't match the inserted element type. A 15149 // SCALAR_TO_VECTOR may truncate the inserted element and the 15150 // EXTRACT_VECTOR_ELT may widen the extracted vector. 15151 SDValue InOp = InVec.getOperand(0); 15152 if (InOp.getValueType() != NVT) { 15153 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15154 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 15155 } 15156 return InOp; 15157 } 15158 15159 SDValue EltNo = N->getOperand(1); 15160 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 15161 15162 // extract_vector_elt of out-of-bounds element -> UNDEF 15163 if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements())) 15164 return DAG.getUNDEF(NVT); 15165 15166 // extract_vector_elt (build_vector x, y), 1 -> y 15167 if (ConstEltNo && 15168 InVec.getOpcode() == ISD::BUILD_VECTOR && 15169 TLI.isTypeLegal(VT) && 15170 (InVec.hasOneUse() || 15171 TLI.aggressivelyPreferBuildVectorSources(VT))) { 15172 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 15173 EVT InEltVT = Elt.getValueType(); 15174 15175 // Sometimes build_vector's scalar input types do not match result type. 15176 if (NVT == InEltVT) 15177 return Elt; 15178 15179 // TODO: It may be useful to truncate if free if the build_vector implicitly 15180 // converts. 15181 } 15182 15183 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 15184 bool isLE = DAG.getDataLayout().isLittleEndian(); 15185 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 15186 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 15187 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 15188 SDValue BCSrc = InVec.getOperand(0); 15189 if (BCSrc.getValueType().isScalarInteger()) 15190 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 15191 } 15192 15193 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 15194 // 15195 // This only really matters if the index is non-constant since other combines 15196 // on the constant elements already work. 15197 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 15198 EltNo == InVec.getOperand(2)) { 15199 SDValue Elt = InVec.getOperand(1); 15200 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 15201 } 15202 15203 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 15204 // We only perform this optimization before the op legalization phase because 15205 // we may introduce new vector instructions which are not backed by TD 15206 // patterns. For example on AVX, extracting elements from a wide vector 15207 // without using extract_subvector. However, if we can find an underlying 15208 // scalar value, then we can always use that. 15209 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 15210 int NumElem = VT.getVectorNumElements(); 15211 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 15212 // Find the new index to extract from. 15213 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 15214 15215 // Extracting an undef index is undef. 15216 if (OrigElt == -1) 15217 return DAG.getUNDEF(NVT); 15218 15219 // Select the right vector half to extract from. 15220 SDValue SVInVec; 15221 if (OrigElt < NumElem) { 15222 SVInVec = InVec->getOperand(0); 15223 } else { 15224 SVInVec = InVec->getOperand(1); 15225 OrigElt -= NumElem; 15226 } 15227 15228 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 15229 SDValue InOp = SVInVec.getOperand(OrigElt); 15230 if (InOp.getValueType() != NVT) { 15231 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15232 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 15233 } 15234 15235 return InOp; 15236 } 15237 15238 // FIXME: We should handle recursing on other vector shuffles and 15239 // scalar_to_vector here as well. 15240 15241 if (!LegalOperations || 15242 // FIXME: Should really be just isOperationLegalOrCustom. 15243 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 15244 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 15245 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15246 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 15247 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 15248 } 15249 } 15250 15251 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 15252 // simplify it based on the (valid) extraction indices. 15253 if (llvm::all_of(InVec->uses(), [&](SDNode *Use) { 15254 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15255 Use->getOperand(0) == InVec && 15256 isa<ConstantSDNode>(Use->getOperand(1)); 15257 })) { 15258 APInt DemandedElts = APInt::getNullValue(VT.getVectorNumElements()); 15259 for (SDNode *Use : InVec->uses()) { 15260 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 15261 if (CstElt->getAPIntValue().ult(VT.getVectorNumElements())) 15262 DemandedElts.setBit(CstElt->getZExtValue()); 15263 } 15264 if (SimplifyDemandedVectorElts(InVec, DemandedElts, true)) 15265 return SDValue(N, 0); 15266 } 15267 15268 bool BCNumEltsChanged = false; 15269 EVT ExtVT = VT.getVectorElementType(); 15270 EVT LVT = ExtVT; 15271 15272 // If the result of load has to be truncated, then it's not necessarily 15273 // profitable. 15274 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 15275 return SDValue(); 15276 15277 if (InVec.getOpcode() == ISD::BITCAST) { 15278 // Don't duplicate a load with other uses. 15279 if (!InVec.hasOneUse()) 15280 return SDValue(); 15281 15282 EVT BCVT = InVec.getOperand(0).getValueType(); 15283 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 15284 return SDValue(); 15285 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 15286 BCNumEltsChanged = true; 15287 InVec = InVec.getOperand(0); 15288 ExtVT = BCVT.getVectorElementType(); 15289 } 15290 15291 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 15292 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 15293 ISD::isNormalLoad(InVec.getNode()) && 15294 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 15295 SDValue Index = N->getOperand(1); 15296 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 15297 if (!OrigLoad->isVolatile()) { 15298 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 15299 OrigLoad); 15300 } 15301 } 15302 } 15303 15304 // Perform only after legalization to ensure build_vector / vector_shuffle 15305 // optimizations have already been done. 15306 if (!LegalOperations) return SDValue(); 15307 15308 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 15309 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 15310 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 15311 15312 if (ConstEltNo) { 15313 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 15314 15315 LoadSDNode *LN0 = nullptr; 15316 const ShuffleVectorSDNode *SVN = nullptr; 15317 if (ISD::isNormalLoad(InVec.getNode())) { 15318 LN0 = cast<LoadSDNode>(InVec); 15319 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 15320 InVec.getOperand(0).getValueType() == ExtVT && 15321 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 15322 // Don't duplicate a load with other uses. 15323 if (!InVec.hasOneUse()) 15324 return SDValue(); 15325 15326 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 15327 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 15328 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 15329 // => 15330 // (load $addr+1*size) 15331 15332 // Don't duplicate a load with other uses. 15333 if (!InVec.hasOneUse()) 15334 return SDValue(); 15335 15336 // If the bit convert changed the number of elements, it is unsafe 15337 // to examine the mask. 15338 if (BCNumEltsChanged) 15339 return SDValue(); 15340 15341 // Select the input vector, guarding against out of range extract vector. 15342 unsigned NumElems = VT.getVectorNumElements(); 15343 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 15344 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 15345 15346 if (InVec.getOpcode() == ISD::BITCAST) { 15347 // Don't duplicate a load with other uses. 15348 if (!InVec.hasOneUse()) 15349 return SDValue(); 15350 15351 InVec = InVec.getOperand(0); 15352 } 15353 if (ISD::isNormalLoad(InVec.getNode())) { 15354 LN0 = cast<LoadSDNode>(InVec); 15355 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 15356 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 15357 } 15358 } 15359 15360 // Make sure we found a non-volatile load and the extractelement is 15361 // the only use. 15362 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 15363 return SDValue(); 15364 15365 // If Idx was -1 above, Elt is going to be -1, so just return undef. 15366 if (Elt == -1) 15367 return DAG.getUNDEF(LVT); 15368 15369 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 15370 } 15371 15372 return SDValue(); 15373 } 15374 15375 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 15376 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 15377 // We perform this optimization post type-legalization because 15378 // the type-legalizer often scalarizes integer-promoted vectors. 15379 // Performing this optimization before may create bit-casts which 15380 // will be type-legalized to complex code sequences. 15381 // We perform this optimization only before the operation legalizer because we 15382 // may introduce illegal operations. 15383 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 15384 return SDValue(); 15385 15386 unsigned NumInScalars = N->getNumOperands(); 15387 SDLoc DL(N); 15388 EVT VT = N->getValueType(0); 15389 15390 // Check to see if this is a BUILD_VECTOR of a bunch of values 15391 // which come from any_extend or zero_extend nodes. If so, we can create 15392 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 15393 // optimizations. We do not handle sign-extend because we can't fill the sign 15394 // using shuffles. 15395 EVT SourceType = MVT::Other; 15396 bool AllAnyExt = true; 15397 15398 for (unsigned i = 0; i != NumInScalars; ++i) { 15399 SDValue In = N->getOperand(i); 15400 // Ignore undef inputs. 15401 if (In.isUndef()) continue; 15402 15403 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 15404 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 15405 15406 // Abort if the element is not an extension. 15407 if (!ZeroExt && !AnyExt) { 15408 SourceType = MVT::Other; 15409 break; 15410 } 15411 15412 // The input is a ZeroExt or AnyExt. Check the original type. 15413 EVT InTy = In.getOperand(0).getValueType(); 15414 15415 // Check that all of the widened source types are the same. 15416 if (SourceType == MVT::Other) 15417 // First time. 15418 SourceType = InTy; 15419 else if (InTy != SourceType) { 15420 // Multiple income types. Abort. 15421 SourceType = MVT::Other; 15422 break; 15423 } 15424 15425 // Check if all of the extends are ANY_EXTENDs. 15426 AllAnyExt &= AnyExt; 15427 } 15428 15429 // In order to have valid types, all of the inputs must be extended from the 15430 // same source type and all of the inputs must be any or zero extend. 15431 // Scalar sizes must be a power of two. 15432 EVT OutScalarTy = VT.getScalarType(); 15433 bool ValidTypes = SourceType != MVT::Other && 15434 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 15435 isPowerOf2_32(SourceType.getSizeInBits()); 15436 15437 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 15438 // turn into a single shuffle instruction. 15439 if (!ValidTypes) 15440 return SDValue(); 15441 15442 bool isLE = DAG.getDataLayout().isLittleEndian(); 15443 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 15444 assert(ElemRatio > 1 && "Invalid element size ratio"); 15445 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 15446 DAG.getConstant(0, DL, SourceType); 15447 15448 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 15449 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 15450 15451 // Populate the new build_vector 15452 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15453 SDValue Cast = N->getOperand(i); 15454 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 15455 Cast.getOpcode() == ISD::ZERO_EXTEND || 15456 Cast.isUndef()) && "Invalid cast opcode"); 15457 SDValue In; 15458 if (Cast.isUndef()) 15459 In = DAG.getUNDEF(SourceType); 15460 else 15461 In = Cast->getOperand(0); 15462 unsigned Index = isLE ? (i * ElemRatio) : 15463 (i * ElemRatio + (ElemRatio - 1)); 15464 15465 assert(Index < Ops.size() && "Invalid index"); 15466 Ops[Index] = In; 15467 } 15468 15469 // The type of the new BUILD_VECTOR node. 15470 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 15471 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 15472 "Invalid vector size"); 15473 // Check if the new vector type is legal. 15474 if (!isTypeLegal(VecVT) || 15475 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 15476 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 15477 return SDValue(); 15478 15479 // Make the new BUILD_VECTOR. 15480 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 15481 15482 // The new BUILD_VECTOR node has the potential to be further optimized. 15483 AddToWorklist(BV.getNode()); 15484 // Bitcast to the desired type. 15485 return DAG.getBitcast(VT, BV); 15486 } 15487 15488 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 15489 EVT VT = N->getValueType(0); 15490 15491 unsigned NumInScalars = N->getNumOperands(); 15492 SDLoc DL(N); 15493 15494 EVT SrcVT = MVT::Other; 15495 unsigned Opcode = ISD::DELETED_NODE; 15496 unsigned NumDefs = 0; 15497 15498 for (unsigned i = 0; i != NumInScalars; ++i) { 15499 SDValue In = N->getOperand(i); 15500 unsigned Opc = In.getOpcode(); 15501 15502 if (Opc == ISD::UNDEF) 15503 continue; 15504 15505 // If all scalar values are floats and converted from integers. 15506 if (Opcode == ISD::DELETED_NODE && 15507 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 15508 Opcode = Opc; 15509 } 15510 15511 if (Opc != Opcode) 15512 return SDValue(); 15513 15514 EVT InVT = In.getOperand(0).getValueType(); 15515 15516 // If all scalar values are typed differently, bail out. It's chosen to 15517 // simplify BUILD_VECTOR of integer types. 15518 if (SrcVT == MVT::Other) 15519 SrcVT = InVT; 15520 if (SrcVT != InVT) 15521 return SDValue(); 15522 NumDefs++; 15523 } 15524 15525 // If the vector has just one element defined, it's not worth to fold it into 15526 // a vectorized one. 15527 if (NumDefs < 2) 15528 return SDValue(); 15529 15530 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 15531 && "Should only handle conversion from integer to float."); 15532 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 15533 15534 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 15535 15536 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 15537 return SDValue(); 15538 15539 // Just because the floating-point vector type is legal does not necessarily 15540 // mean that the corresponding integer vector type is. 15541 if (!isTypeLegal(NVT)) 15542 return SDValue(); 15543 15544 SmallVector<SDValue, 8> Opnds; 15545 for (unsigned i = 0; i != NumInScalars; ++i) { 15546 SDValue In = N->getOperand(i); 15547 15548 if (In.isUndef()) 15549 Opnds.push_back(DAG.getUNDEF(SrcVT)); 15550 else 15551 Opnds.push_back(In.getOperand(0)); 15552 } 15553 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 15554 AddToWorklist(BV.getNode()); 15555 15556 return DAG.getNode(Opcode, DL, VT, BV); 15557 } 15558 15559 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 15560 ArrayRef<int> VectorMask, 15561 SDValue VecIn1, SDValue VecIn2, 15562 unsigned LeftIdx) { 15563 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15564 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 15565 15566 EVT VT = N->getValueType(0); 15567 EVT InVT1 = VecIn1.getValueType(); 15568 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 15569 15570 unsigned Vec2Offset = 0; 15571 unsigned NumElems = VT.getVectorNumElements(); 15572 unsigned ShuffleNumElems = NumElems; 15573 15574 // In case both the input vectors are extracted from same base 15575 // vector we do not need extra addend (Vec2Offset) while 15576 // computing shuffle mask. 15577 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15578 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15579 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 15580 Vec2Offset = InVT1.getVectorNumElements(); 15581 15582 // We can't generate a shuffle node with mismatched input and output types. 15583 // Try to make the types match the type of the output. 15584 if (InVT1 != VT || InVT2 != VT) { 15585 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 15586 // If the output vector length is a multiple of both input lengths, 15587 // we can concatenate them and pad the rest with undefs. 15588 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 15589 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 15590 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 15591 ConcatOps[0] = VecIn1; 15592 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 15593 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 15594 VecIn2 = SDValue(); 15595 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 15596 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 15597 return SDValue(); 15598 15599 if (!VecIn2.getNode()) { 15600 // If we only have one input vector, and it's twice the size of the 15601 // output, split it in two. 15602 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 15603 DAG.getConstant(NumElems, DL, IdxTy)); 15604 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 15605 // Since we now have shorter input vectors, adjust the offset of the 15606 // second vector's start. 15607 Vec2Offset = NumElems; 15608 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 15609 // VecIn1 is wider than the output, and we have another, possibly 15610 // smaller input. Pad the smaller input with undefs, shuffle at the 15611 // input vector width, and extract the output. 15612 // The shuffle type is different than VT, so check legality again. 15613 if (LegalOperations && 15614 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 15615 return SDValue(); 15616 15617 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 15618 // lower it back into a BUILD_VECTOR. So if the inserted type is 15619 // illegal, don't even try. 15620 if (InVT1 != InVT2) { 15621 if (!TLI.isTypeLegal(InVT2)) 15622 return SDValue(); 15623 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 15624 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 15625 } 15626 ShuffleNumElems = NumElems * 2; 15627 } else { 15628 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 15629 // than VecIn1. We can't handle this for now - this case will disappear 15630 // when we start sorting the vectors by type. 15631 return SDValue(); 15632 } 15633 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 15634 InVT1.getSizeInBits() == VT.getSizeInBits()) { 15635 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 15636 ConcatOps[0] = VecIn2; 15637 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 15638 } else { 15639 // TODO: Support cases where the length mismatch isn't exactly by a 15640 // factor of 2. 15641 // TODO: Move this check upwards, so that if we have bad type 15642 // mismatches, we don't create any DAG nodes. 15643 return SDValue(); 15644 } 15645 } 15646 15647 // Initialize mask to undef. 15648 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 15649 15650 // Only need to run up to the number of elements actually used, not the 15651 // total number of elements in the shuffle - if we are shuffling a wider 15652 // vector, the high lanes should be set to undef. 15653 for (unsigned i = 0; i != NumElems; ++i) { 15654 if (VectorMask[i] <= 0) 15655 continue; 15656 15657 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 15658 if (VectorMask[i] == (int)LeftIdx) { 15659 Mask[i] = ExtIndex; 15660 } else if (VectorMask[i] == (int)LeftIdx + 1) { 15661 Mask[i] = Vec2Offset + ExtIndex; 15662 } 15663 } 15664 15665 // The type the input vectors may have changed above. 15666 InVT1 = VecIn1.getValueType(); 15667 15668 // If we already have a VecIn2, it should have the same type as VecIn1. 15669 // If we don't, get an undef/zero vector of the appropriate type. 15670 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 15671 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 15672 15673 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 15674 if (ShuffleNumElems > NumElems) 15675 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 15676 15677 return Shuffle; 15678 } 15679 15680 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 15681 // operations. If the types of the vectors we're extracting from allow it, 15682 // turn this into a vector_shuffle node. 15683 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 15684 SDLoc DL(N); 15685 EVT VT = N->getValueType(0); 15686 15687 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 15688 if (!isTypeLegal(VT)) 15689 return SDValue(); 15690 15691 // May only combine to shuffle after legalize if shuffle is legal. 15692 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 15693 return SDValue(); 15694 15695 bool UsesZeroVector = false; 15696 unsigned NumElems = N->getNumOperands(); 15697 15698 // Record, for each element of the newly built vector, which input vector 15699 // that element comes from. -1 stands for undef, 0 for the zero vector, 15700 // and positive values for the input vectors. 15701 // VectorMask maps each element to its vector number, and VecIn maps vector 15702 // numbers to their initial SDValues. 15703 15704 SmallVector<int, 8> VectorMask(NumElems, -1); 15705 SmallVector<SDValue, 8> VecIn; 15706 VecIn.push_back(SDValue()); 15707 15708 for (unsigned i = 0; i != NumElems; ++i) { 15709 SDValue Op = N->getOperand(i); 15710 15711 if (Op.isUndef()) 15712 continue; 15713 15714 // See if we can use a blend with a zero vector. 15715 // TODO: Should we generalize this to a blend with an arbitrary constant 15716 // vector? 15717 if (isNullConstant(Op) || isNullFPConstant(Op)) { 15718 UsesZeroVector = true; 15719 VectorMask[i] = 0; 15720 continue; 15721 } 15722 15723 // Not an undef or zero. If the input is something other than an 15724 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 15725 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 15726 !isa<ConstantSDNode>(Op.getOperand(1))) 15727 return SDValue(); 15728 SDValue ExtractedFromVec = Op.getOperand(0); 15729 15730 APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue(); 15731 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 15732 return SDValue(); 15733 15734 // All inputs must have the same element type as the output. 15735 if (VT.getVectorElementType() != 15736 ExtractedFromVec.getValueType().getVectorElementType()) 15737 return SDValue(); 15738 15739 // Have we seen this input vector before? 15740 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 15741 // a map back from SDValues to numbers isn't worth it. 15742 unsigned Idx = std::distance( 15743 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 15744 if (Idx == VecIn.size()) 15745 VecIn.push_back(ExtractedFromVec); 15746 15747 VectorMask[i] = Idx; 15748 } 15749 15750 // If we didn't find at least one input vector, bail out. 15751 if (VecIn.size() < 2) 15752 return SDValue(); 15753 15754 // If all the Operands of BUILD_VECTOR extract from same 15755 // vector, then split the vector efficiently based on the maximum 15756 // vector access index and adjust the VectorMask and 15757 // VecIn accordingly. 15758 if (VecIn.size() == 2) { 15759 unsigned MaxIndex = 0; 15760 unsigned NearestPow2 = 0; 15761 SDValue Vec = VecIn.back(); 15762 EVT InVT = Vec.getValueType(); 15763 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15764 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 15765 15766 for (unsigned i = 0; i < NumElems; i++) { 15767 if (VectorMask[i] <= 0) 15768 continue; 15769 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 15770 IndexVec[i] = Index; 15771 MaxIndex = std::max(MaxIndex, Index); 15772 } 15773 15774 NearestPow2 = PowerOf2Ceil(MaxIndex); 15775 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 15776 NumElems * 2 < NearestPow2) { 15777 unsigned SplitSize = NearestPow2 / 2; 15778 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 15779 InVT.getVectorElementType(), SplitSize); 15780 if (TLI.isTypeLegal(SplitVT)) { 15781 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 15782 DAG.getConstant(SplitSize, DL, IdxTy)); 15783 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 15784 DAG.getConstant(0, DL, IdxTy)); 15785 VecIn.pop_back(); 15786 VecIn.push_back(VecIn1); 15787 VecIn.push_back(VecIn2); 15788 15789 for (unsigned i = 0; i < NumElems; i++) { 15790 if (VectorMask[i] <= 0) 15791 continue; 15792 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 15793 } 15794 } 15795 } 15796 } 15797 15798 // TODO: We want to sort the vectors by descending length, so that adjacent 15799 // pairs have similar length, and the longer vector is always first in the 15800 // pair. 15801 15802 // TODO: Should this fire if some of the input vectors has illegal type (like 15803 // it does now), or should we let legalization run its course first? 15804 15805 // Shuffle phase: 15806 // Take pairs of vectors, and shuffle them so that the result has elements 15807 // from these vectors in the correct places. 15808 // For example, given: 15809 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 15810 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 15811 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 15812 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 15813 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 15814 // We will generate: 15815 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 15816 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 15817 SmallVector<SDValue, 4> Shuffles; 15818 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 15819 unsigned LeftIdx = 2 * In + 1; 15820 SDValue VecLeft = VecIn[LeftIdx]; 15821 SDValue VecRight = 15822 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 15823 15824 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 15825 VecRight, LeftIdx)) 15826 Shuffles.push_back(Shuffle); 15827 else 15828 return SDValue(); 15829 } 15830 15831 // If we need the zero vector as an "ingredient" in the blend tree, add it 15832 // to the list of shuffles. 15833 if (UsesZeroVector) 15834 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 15835 : DAG.getConstantFP(0.0, DL, VT)); 15836 15837 // If we only have one shuffle, we're done. 15838 if (Shuffles.size() == 1) 15839 return Shuffles[0]; 15840 15841 // Update the vector mask to point to the post-shuffle vectors. 15842 for (int &Vec : VectorMask) 15843 if (Vec == 0) 15844 Vec = Shuffles.size() - 1; 15845 else 15846 Vec = (Vec - 1) / 2; 15847 15848 // More than one shuffle. Generate a binary tree of blends, e.g. if from 15849 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 15850 // generate: 15851 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 15852 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 15853 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 15854 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 15855 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 15856 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 15857 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 15858 15859 // Make sure the initial size of the shuffle list is even. 15860 if (Shuffles.size() % 2) 15861 Shuffles.push_back(DAG.getUNDEF(VT)); 15862 15863 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 15864 if (CurSize % 2) { 15865 Shuffles[CurSize] = DAG.getUNDEF(VT); 15866 CurSize++; 15867 } 15868 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 15869 int Left = 2 * In; 15870 int Right = 2 * In + 1; 15871 SmallVector<int, 8> Mask(NumElems, -1); 15872 for (unsigned i = 0; i != NumElems; ++i) { 15873 if (VectorMask[i] == Left) { 15874 Mask[i] = i; 15875 VectorMask[i] = In; 15876 } else if (VectorMask[i] == Right) { 15877 Mask[i] = i + NumElems; 15878 VectorMask[i] = In; 15879 } 15880 } 15881 15882 Shuffles[In] = 15883 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 15884 } 15885 } 15886 return Shuffles[0]; 15887 } 15888 15889 // Try to turn a build vector of zero extends of extract vector elts into a 15890 // a vector zero extend and possibly an extract subvector. 15891 // TODO: Support sign extend or any extend? 15892 // TODO: Allow undef elements? 15893 // TODO: Don't require the extracts to start at element 0. 15894 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 15895 if (LegalOperations) 15896 return SDValue(); 15897 15898 EVT VT = N->getValueType(0); 15899 15900 SDValue Op0 = N->getOperand(0); 15901 auto checkElem = [&](SDValue Op) -> int64_t { 15902 if (Op.getOpcode() == ISD::ZERO_EXTEND && 15903 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15904 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 15905 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 15906 return C->getZExtValue(); 15907 return -1; 15908 }; 15909 15910 // Make sure the first element matches 15911 // (zext (extract_vector_elt X, C)) 15912 int64_t Offset = checkElem(Op0); 15913 if (Offset < 0) 15914 return SDValue(); 15915 15916 unsigned NumElems = N->getNumOperands(); 15917 SDValue In = Op0.getOperand(0).getOperand(0); 15918 EVT InSVT = In.getValueType().getScalarType(); 15919 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 15920 15921 // Don't create an illegal input type after type legalization. 15922 if (LegalTypes && !TLI.isTypeLegal(InVT)) 15923 return SDValue(); 15924 15925 // Ensure all the elements come from the same vector and are adjacent. 15926 for (unsigned i = 1; i != NumElems; ++i) { 15927 if ((Offset + i) != checkElem(N->getOperand(i))) 15928 return SDValue(); 15929 } 15930 15931 SDLoc DL(N); 15932 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 15933 Op0.getOperand(0).getOperand(1)); 15934 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In); 15935 } 15936 15937 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 15938 EVT VT = N->getValueType(0); 15939 15940 // A vector built entirely of undefs is undef. 15941 if (ISD::allOperandsUndef(N)) 15942 return DAG.getUNDEF(VT); 15943 15944 // If this is a splat of a bitcast from another vector, change to a 15945 // concat_vector. 15946 // For example: 15947 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 15948 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 15949 // 15950 // If X is a build_vector itself, the concat can become a larger build_vector. 15951 // TODO: Maybe this is useful for non-splat too? 15952 if (!LegalOperations) { 15953 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 15954 Splat = peekThroughBitcast(Splat); 15955 EVT SrcVT = Splat.getValueType(); 15956 if (SrcVT.isVector()) { 15957 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 15958 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 15959 SrcVT.getVectorElementType(), NumElts); 15960 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 15961 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 15962 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 15963 NewVT, Ops); 15964 return DAG.getBitcast(VT, Concat); 15965 } 15966 } 15967 } 15968 } 15969 15970 // Check if we can express BUILD VECTOR via subvector extract. 15971 if (!LegalTypes && (N->getNumOperands() > 1)) { 15972 SDValue Op0 = N->getOperand(0); 15973 auto checkElem = [&](SDValue Op) -> uint64_t { 15974 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 15975 (Op0.getOperand(0) == Op.getOperand(0))) 15976 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 15977 return CNode->getZExtValue(); 15978 return -1; 15979 }; 15980 15981 int Offset = checkElem(Op0); 15982 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 15983 if (Offset + i != checkElem(N->getOperand(i))) { 15984 Offset = -1; 15985 break; 15986 } 15987 } 15988 15989 if ((Offset == 0) && 15990 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 15991 return Op0.getOperand(0); 15992 if ((Offset != -1) && 15993 ((Offset % N->getValueType(0).getVectorNumElements()) == 15994 0)) // IDX must be multiple of output size. 15995 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 15996 Op0.getOperand(0), Op0.getOperand(1)); 15997 } 15998 15999 if (SDValue V = convertBuildVecZextToZext(N)) 16000 return V; 16001 16002 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 16003 return V; 16004 16005 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 16006 return V; 16007 16008 if (SDValue V = reduceBuildVecToShuffle(N)) 16009 return V; 16010 16011 return SDValue(); 16012 } 16013 16014 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 16015 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16016 EVT OpVT = N->getOperand(0).getValueType(); 16017 16018 // If the operands are legal vectors, leave them alone. 16019 if (TLI.isTypeLegal(OpVT)) 16020 return SDValue(); 16021 16022 SDLoc DL(N); 16023 EVT VT = N->getValueType(0); 16024 SmallVector<SDValue, 8> Ops; 16025 16026 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 16027 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16028 16029 // Keep track of what we encounter. 16030 bool AnyInteger = false; 16031 bool AnyFP = false; 16032 for (const SDValue &Op : N->ops()) { 16033 if (ISD::BITCAST == Op.getOpcode() && 16034 !Op.getOperand(0).getValueType().isVector()) 16035 Ops.push_back(Op.getOperand(0)); 16036 else if (ISD::UNDEF == Op.getOpcode()) 16037 Ops.push_back(ScalarUndef); 16038 else 16039 return SDValue(); 16040 16041 // Note whether we encounter an integer or floating point scalar. 16042 // If it's neither, bail out, it could be something weird like x86mmx. 16043 EVT LastOpVT = Ops.back().getValueType(); 16044 if (LastOpVT.isFloatingPoint()) 16045 AnyFP = true; 16046 else if (LastOpVT.isInteger()) 16047 AnyInteger = true; 16048 else 16049 return SDValue(); 16050 } 16051 16052 // If any of the operands is a floating point scalar bitcast to a vector, 16053 // use floating point types throughout, and bitcast everything. 16054 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 16055 if (AnyFP) { 16056 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 16057 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16058 if (AnyInteger) { 16059 for (SDValue &Op : Ops) { 16060 if (Op.getValueType() == SVT) 16061 continue; 16062 if (Op.isUndef()) 16063 Op = ScalarUndef; 16064 else 16065 Op = DAG.getBitcast(SVT, Op); 16066 } 16067 } 16068 } 16069 16070 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 16071 VT.getSizeInBits() / SVT.getSizeInBits()); 16072 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 16073 } 16074 16075 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 16076 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 16077 // most two distinct vectors the same size as the result, attempt to turn this 16078 // into a legal shuffle. 16079 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 16080 EVT VT = N->getValueType(0); 16081 EVT OpVT = N->getOperand(0).getValueType(); 16082 int NumElts = VT.getVectorNumElements(); 16083 int NumOpElts = OpVT.getVectorNumElements(); 16084 16085 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 16086 SmallVector<int, 8> Mask; 16087 16088 for (SDValue Op : N->ops()) { 16089 // Peek through any bitcast. 16090 Op = peekThroughBitcast(Op); 16091 16092 // UNDEF nodes convert to UNDEF shuffle mask values. 16093 if (Op.isUndef()) { 16094 Mask.append((unsigned)NumOpElts, -1); 16095 continue; 16096 } 16097 16098 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16099 return SDValue(); 16100 16101 // What vector are we extracting the subvector from and at what index? 16102 SDValue ExtVec = Op.getOperand(0); 16103 16104 // We want the EVT of the original extraction to correctly scale the 16105 // extraction index. 16106 EVT ExtVT = ExtVec.getValueType(); 16107 16108 // Peek through any bitcast. 16109 ExtVec = peekThroughBitcast(ExtVec); 16110 16111 // UNDEF nodes convert to UNDEF shuffle mask values. 16112 if (ExtVec.isUndef()) { 16113 Mask.append((unsigned)NumOpElts, -1); 16114 continue; 16115 } 16116 16117 if (!isa<ConstantSDNode>(Op.getOperand(1))) 16118 return SDValue(); 16119 int ExtIdx = Op.getConstantOperandVal(1); 16120 16121 // Ensure that we are extracting a subvector from a vector the same 16122 // size as the result. 16123 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 16124 return SDValue(); 16125 16126 // Scale the subvector index to account for any bitcast. 16127 int NumExtElts = ExtVT.getVectorNumElements(); 16128 if (0 == (NumExtElts % NumElts)) 16129 ExtIdx /= (NumExtElts / NumElts); 16130 else if (0 == (NumElts % NumExtElts)) 16131 ExtIdx *= (NumElts / NumExtElts); 16132 else 16133 return SDValue(); 16134 16135 // At most we can reference 2 inputs in the final shuffle. 16136 if (SV0.isUndef() || SV0 == ExtVec) { 16137 SV0 = ExtVec; 16138 for (int i = 0; i != NumOpElts; ++i) 16139 Mask.push_back(i + ExtIdx); 16140 } else if (SV1.isUndef() || SV1 == ExtVec) { 16141 SV1 = ExtVec; 16142 for (int i = 0; i != NumOpElts; ++i) 16143 Mask.push_back(i + ExtIdx + NumElts); 16144 } else { 16145 return SDValue(); 16146 } 16147 } 16148 16149 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 16150 return SDValue(); 16151 16152 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 16153 DAG.getBitcast(VT, SV1), Mask); 16154 } 16155 16156 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 16157 // If we only have one input vector, we don't need to do any concatenation. 16158 if (N->getNumOperands() == 1) 16159 return N->getOperand(0); 16160 16161 // Check if all of the operands are undefs. 16162 EVT VT = N->getValueType(0); 16163 if (ISD::allOperandsUndef(N)) 16164 return DAG.getUNDEF(VT); 16165 16166 // Optimize concat_vectors where all but the first of the vectors are undef. 16167 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 16168 return Op.isUndef(); 16169 })) { 16170 SDValue In = N->getOperand(0); 16171 assert(In.getValueType().isVector() && "Must concat vectors"); 16172 16173 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 16174 if (In->getOpcode() == ISD::BITCAST && 16175 !In->getOperand(0).getValueType().isVector()) { 16176 SDValue Scalar = In->getOperand(0); 16177 16178 // If the bitcast type isn't legal, it might be a trunc of a legal type; 16179 // look through the trunc so we can still do the transform: 16180 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 16181 if (Scalar->getOpcode() == ISD::TRUNCATE && 16182 !TLI.isTypeLegal(Scalar.getValueType()) && 16183 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 16184 Scalar = Scalar->getOperand(0); 16185 16186 EVT SclTy = Scalar->getValueType(0); 16187 16188 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 16189 return SDValue(); 16190 16191 // Bail out if the vector size is not a multiple of the scalar size. 16192 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 16193 return SDValue(); 16194 16195 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 16196 if (VNTNumElms < 2) 16197 return SDValue(); 16198 16199 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 16200 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 16201 return SDValue(); 16202 16203 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 16204 return DAG.getBitcast(VT, Res); 16205 } 16206 } 16207 16208 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 16209 // We have already tested above for an UNDEF only concatenation. 16210 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 16211 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 16212 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 16213 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 16214 }; 16215 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 16216 SmallVector<SDValue, 8> Opnds; 16217 EVT SVT = VT.getScalarType(); 16218 16219 EVT MinVT = SVT; 16220 if (!SVT.isFloatingPoint()) { 16221 // If BUILD_VECTOR are from built from integer, they may have different 16222 // operand types. Get the smallest type and truncate all operands to it. 16223 bool FoundMinVT = false; 16224 for (const SDValue &Op : N->ops()) 16225 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16226 EVT OpSVT = Op.getOperand(0).getValueType(); 16227 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 16228 FoundMinVT = true; 16229 } 16230 assert(FoundMinVT && "Concat vector type mismatch"); 16231 } 16232 16233 for (const SDValue &Op : N->ops()) { 16234 EVT OpVT = Op.getValueType(); 16235 unsigned NumElts = OpVT.getVectorNumElements(); 16236 16237 if (ISD::UNDEF == Op.getOpcode()) 16238 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 16239 16240 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16241 if (SVT.isFloatingPoint()) { 16242 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 16243 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 16244 } else { 16245 for (unsigned i = 0; i != NumElts; ++i) 16246 Opnds.push_back( 16247 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 16248 } 16249 } 16250 } 16251 16252 assert(VT.getVectorNumElements() == Opnds.size() && 16253 "Concat vector type mismatch"); 16254 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 16255 } 16256 16257 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 16258 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 16259 return V; 16260 16261 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 16262 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16263 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 16264 return V; 16265 16266 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 16267 // nodes often generate nop CONCAT_VECTOR nodes. 16268 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 16269 // place the incoming vectors at the exact same location. 16270 SDValue SingleSource = SDValue(); 16271 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 16272 16273 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16274 SDValue Op = N->getOperand(i); 16275 16276 if (Op.isUndef()) 16277 continue; 16278 16279 // Check if this is the identity extract: 16280 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16281 return SDValue(); 16282 16283 // Find the single incoming vector for the extract_subvector. 16284 if (SingleSource.getNode()) { 16285 if (Op.getOperand(0) != SingleSource) 16286 return SDValue(); 16287 } else { 16288 SingleSource = Op.getOperand(0); 16289 16290 // Check the source type is the same as the type of the result. 16291 // If not, this concat may extend the vector, so we can not 16292 // optimize it away. 16293 if (SingleSource.getValueType() != N->getValueType(0)) 16294 return SDValue(); 16295 } 16296 16297 unsigned IdentityIndex = i * PartNumElem; 16298 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 16299 // The extract index must be constant. 16300 if (!CS) 16301 return SDValue(); 16302 16303 // Check that we are reading from the identity index. 16304 if (CS->getZExtValue() != IdentityIndex) 16305 return SDValue(); 16306 } 16307 16308 if (SingleSource.getNode()) 16309 return SingleSource; 16310 16311 return SDValue(); 16312 } 16313 16314 /// If we are extracting a subvector produced by a wide binary operator with at 16315 /// at least one operand that was the result of a vector concatenation, then try 16316 /// to use the narrow vector operands directly to avoid the concatenation and 16317 /// extraction. 16318 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 16319 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 16320 // some of these bailouts with other transforms. 16321 16322 // The extract index must be a constant, so we can map it to a concat operand. 16323 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16324 if (!ExtractIndex) 16325 return SDValue(); 16326 16327 // Only handle the case where we are doubling and then halving. A larger ratio 16328 // may require more than two narrow binops to replace the wide binop. 16329 EVT VT = Extract->getValueType(0); 16330 unsigned NumElems = VT.getVectorNumElements(); 16331 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 16332 "Extract index is not a multiple of the vector length."); 16333 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 16334 return SDValue(); 16335 16336 // We are looking for an optionally bitcasted wide vector binary operator 16337 // feeding an extract subvector. 16338 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 16339 16340 // TODO: The motivating case for this transform is an x86 AVX1 target. That 16341 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 16342 // flavors, but no other 256-bit integer support. This could be extended to 16343 // handle any binop, but that may require fixing/adding other folds to avoid 16344 // codegen regressions. 16345 unsigned BOpcode = BinOp.getOpcode(); 16346 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 16347 return SDValue(); 16348 16349 // The binop must be a vector type, so we can chop it in half. 16350 EVT WideBVT = BinOp.getValueType(); 16351 if (!WideBVT.isVector()) 16352 return SDValue(); 16353 16354 // Bail out if the target does not support a narrower version of the binop. 16355 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 16356 WideBVT.getVectorNumElements() / 2); 16357 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16358 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 16359 return SDValue(); 16360 16361 // Peek through bitcasts of the binary operator operands if needed. 16362 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 16363 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 16364 16365 // We need at least one concatenation operation of a binop operand to make 16366 // this transform worthwhile. The concat must double the input vector sizes. 16367 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 16368 bool ConcatL = 16369 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 16370 bool ConcatR = 16371 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 16372 if (!ConcatL && !ConcatR) 16373 return SDValue(); 16374 16375 // If one of the binop operands was not the result of a concat, we must 16376 // extract a half-sized operand for our new narrow binop. We can't just reuse 16377 // the original extract index operand because we may have bitcasted. 16378 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 16379 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 16380 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 16381 SDLoc DL(Extract); 16382 16383 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 16384 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 16385 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 16386 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 16387 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16388 BinOp.getOperand(0), 16389 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16390 16391 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 16392 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16393 BinOp.getOperand(1), 16394 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16395 16396 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 16397 return DAG.getBitcast(VT, NarrowBinOp); 16398 } 16399 16400 /// If we are extracting a subvector from a wide vector load, convert to a 16401 /// narrow load to eliminate the extraction: 16402 /// (extract_subvector (load wide vector)) --> (load narrow vector) 16403 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 16404 // TODO: Add support for big-endian. The offset calculation must be adjusted. 16405 if (DAG.getDataLayout().isBigEndian()) 16406 return SDValue(); 16407 16408 // TODO: The one-use check is overly conservative. Check the cost of the 16409 // extract instead or remove that condition entirely. 16410 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 16411 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16412 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 16413 !ExtIdx) 16414 return SDValue(); 16415 16416 // The narrow load will be offset from the base address of the old load if 16417 // we are extracting from something besides index 0 (little-endian). 16418 EVT VT = Extract->getValueType(0); 16419 SDLoc DL(Extract); 16420 SDValue BaseAddr = Ld->getOperand(1); 16421 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 16422 16423 // TODO: Use "BaseIndexOffset" to make this more effective. 16424 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 16425 MachineFunction &MF = DAG.getMachineFunction(); 16426 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 16427 VT.getStoreSize()); 16428 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 16429 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 16430 return NewLd; 16431 } 16432 16433 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 16434 EVT NVT = N->getValueType(0); 16435 SDValue V = N->getOperand(0); 16436 16437 // Extract from UNDEF is UNDEF. 16438 if (V.isUndef()) 16439 return DAG.getUNDEF(NVT); 16440 16441 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 16442 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 16443 return NarrowLoad; 16444 16445 // Combine: 16446 // (extract_subvec (concat V1, V2, ...), i) 16447 // Into: 16448 // Vi if possible 16449 // Only operand 0 is checked as 'concat' assumes all inputs of the same 16450 // type. 16451 if (V->getOpcode() == ISD::CONCAT_VECTORS && 16452 isa<ConstantSDNode>(N->getOperand(1)) && 16453 V->getOperand(0).getValueType() == NVT) { 16454 unsigned Idx = N->getConstantOperandVal(1); 16455 unsigned NumElems = NVT.getVectorNumElements(); 16456 assert((Idx % NumElems) == 0 && 16457 "IDX in concat is not a multiple of the result vector length."); 16458 return V->getOperand(Idx / NumElems); 16459 } 16460 16461 // Skip bitcasting 16462 V = peekThroughBitcast(V); 16463 16464 // If the input is a build vector. Try to make a smaller build vector. 16465 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16466 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 16467 EVT InVT = V->getValueType(0); 16468 unsigned ExtractSize = NVT.getSizeInBits(); 16469 unsigned EltSize = InVT.getScalarSizeInBits(); 16470 // Only do this if we won't split any elements. 16471 if (ExtractSize % EltSize == 0) { 16472 unsigned NumElems = ExtractSize / EltSize; 16473 EVT EltVT = InVT.getVectorElementType(); 16474 EVT ExtractVT = NumElems == 1 ? EltVT : 16475 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 16476 if ((Level < AfterLegalizeDAG || 16477 (NumElems == 1 || 16478 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 16479 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 16480 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 16481 EltSize; 16482 if (NumElems == 1) { 16483 SDValue Src = V->getOperand(IdxVal); 16484 if (EltVT != Src.getValueType()) 16485 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 16486 16487 return DAG.getBitcast(NVT, Src); 16488 } 16489 16490 // Extract the pieces from the original build_vector. 16491 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 16492 makeArrayRef(V->op_begin() + IdxVal, 16493 NumElems)); 16494 return DAG.getBitcast(NVT, BuildVec); 16495 } 16496 } 16497 } 16498 } 16499 16500 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 16501 // Handle only simple case where vector being inserted and vector 16502 // being extracted are of same size. 16503 EVT SmallVT = V->getOperand(1).getValueType(); 16504 if (!NVT.bitsEq(SmallVT)) 16505 return SDValue(); 16506 16507 // Only handle cases where both indexes are constants. 16508 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16509 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 16510 16511 if (InsIdx && ExtIdx) { 16512 // Combine: 16513 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 16514 // Into: 16515 // indices are equal or bit offsets are equal => V1 16516 // otherwise => (extract_subvec V1, ExtIdx) 16517 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 16518 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 16519 return DAG.getBitcast(NVT, V->getOperand(1)); 16520 return DAG.getNode( 16521 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 16522 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 16523 N->getOperand(1)); 16524 } 16525 } 16526 16527 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 16528 return NarrowBOp; 16529 16530 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 16531 return SDValue(N, 0); 16532 16533 return SDValue(); 16534 } 16535 16536 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 16537 // or turn a shuffle of a single concat into simpler shuffle then concat. 16538 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 16539 EVT VT = N->getValueType(0); 16540 unsigned NumElts = VT.getVectorNumElements(); 16541 16542 SDValue N0 = N->getOperand(0); 16543 SDValue N1 = N->getOperand(1); 16544 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 16545 16546 SmallVector<SDValue, 4> Ops; 16547 EVT ConcatVT = N0.getOperand(0).getValueType(); 16548 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 16549 unsigned NumConcats = NumElts / NumElemsPerConcat; 16550 16551 // Special case: shuffle(concat(A,B)) can be more efficiently represented 16552 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 16553 // half vector elements. 16554 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 16555 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 16556 SVN->getMask().end(), [](int i) { return i == -1; })) { 16557 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 16558 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 16559 N1 = DAG.getUNDEF(ConcatVT); 16560 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 16561 } 16562 16563 // Look at every vector that's inserted. We're looking for exact 16564 // subvector-sized copies from a concatenated vector 16565 for (unsigned I = 0; I != NumConcats; ++I) { 16566 // Make sure we're dealing with a copy. 16567 unsigned Begin = I * NumElemsPerConcat; 16568 bool AllUndef = true, NoUndef = true; 16569 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 16570 if (SVN->getMaskElt(J) >= 0) 16571 AllUndef = false; 16572 else 16573 NoUndef = false; 16574 } 16575 16576 if (NoUndef) { 16577 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 16578 return SDValue(); 16579 16580 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 16581 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 16582 return SDValue(); 16583 16584 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 16585 if (FirstElt < N0.getNumOperands()) 16586 Ops.push_back(N0.getOperand(FirstElt)); 16587 else 16588 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 16589 16590 } else if (AllUndef) { 16591 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 16592 } else { // Mixed with general masks and undefs, can't do optimization. 16593 return SDValue(); 16594 } 16595 } 16596 16597 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16598 } 16599 16600 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16601 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16602 // 16603 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 16604 // a simplification in some sense, but it isn't appropriate in general: some 16605 // BUILD_VECTORs are substantially cheaper than others. The general case 16606 // of a BUILD_VECTOR requires inserting each element individually (or 16607 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 16608 // all constants is a single constant pool load. A BUILD_VECTOR where each 16609 // element is identical is a splat. A BUILD_VECTOR where most of the operands 16610 // are undef lowers to a small number of element insertions. 16611 // 16612 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 16613 // We don't fold shuffles where one side is a non-zero constant, and we don't 16614 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 16615 // non-constant operands. This seems to work out reasonably well in practice. 16616 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 16617 SelectionDAG &DAG, 16618 const TargetLowering &TLI) { 16619 EVT VT = SVN->getValueType(0); 16620 unsigned NumElts = VT.getVectorNumElements(); 16621 SDValue N0 = SVN->getOperand(0); 16622 SDValue N1 = SVN->getOperand(1); 16623 16624 if (!N0->hasOneUse() || !N1->hasOneUse()) 16625 return SDValue(); 16626 16627 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 16628 // discussed above. 16629 if (!N1.isUndef()) { 16630 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 16631 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 16632 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 16633 return SDValue(); 16634 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 16635 return SDValue(); 16636 } 16637 16638 // If both inputs are splats of the same value then we can safely merge this 16639 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 16640 bool IsSplat = false; 16641 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 16642 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 16643 if (BV0 && BV1) 16644 if (SDValue Splat0 = BV0->getSplatValue()) 16645 IsSplat = (Splat0 == BV1->getSplatValue()); 16646 16647 SmallVector<SDValue, 8> Ops; 16648 SmallSet<SDValue, 16> DuplicateOps; 16649 for (int M : SVN->getMask()) { 16650 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 16651 if (M >= 0) { 16652 int Idx = M < (int)NumElts ? M : M - NumElts; 16653 SDValue &S = (M < (int)NumElts ? N0 : N1); 16654 if (S.getOpcode() == ISD::BUILD_VECTOR) { 16655 Op = S.getOperand(Idx); 16656 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 16657 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 16658 Op = S.getOperand(0); 16659 } else { 16660 // Operand can't be combined - bail out. 16661 return SDValue(); 16662 } 16663 } 16664 16665 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 16666 // generating a splat; semantically, this is fine, but it's likely to 16667 // generate low-quality code if the target can't reconstruct an appropriate 16668 // shuffle. 16669 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 16670 if (!IsSplat && !DuplicateOps.insert(Op).second) 16671 return SDValue(); 16672 16673 Ops.push_back(Op); 16674 } 16675 16676 // BUILD_VECTOR requires all inputs to be of the same type, find the 16677 // maximum type and extend them all. 16678 EVT SVT = VT.getScalarType(); 16679 if (SVT.isInteger()) 16680 for (SDValue &Op : Ops) 16681 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 16682 if (SVT != VT.getScalarType()) 16683 for (SDValue &Op : Ops) 16684 Op = TLI.isZExtFree(Op.getValueType(), SVT) 16685 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 16686 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 16687 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 16688 } 16689 16690 // Match shuffles that can be converted to any_vector_extend_in_reg. 16691 // This is often generated during legalization. 16692 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 16693 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 16694 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 16695 SelectionDAG &DAG, 16696 const TargetLowering &TLI, 16697 bool LegalOperations, 16698 bool LegalTypes) { 16699 EVT VT = SVN->getValueType(0); 16700 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 16701 16702 // TODO Add support for big-endian when we have a test case. 16703 if (!VT.isInteger() || IsBigEndian) 16704 return SDValue(); 16705 16706 unsigned NumElts = VT.getVectorNumElements(); 16707 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 16708 ArrayRef<int> Mask = SVN->getMask(); 16709 SDValue N0 = SVN->getOperand(0); 16710 16711 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 16712 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 16713 for (unsigned i = 0; i != NumElts; ++i) { 16714 if (Mask[i] < 0) 16715 continue; 16716 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 16717 continue; 16718 return false; 16719 } 16720 return true; 16721 }; 16722 16723 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 16724 // power-of-2 extensions as they are the most likely. 16725 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 16726 // Check for non power of 2 vector sizes 16727 if (NumElts % Scale != 0) 16728 continue; 16729 if (!isAnyExtend(Scale)) 16730 continue; 16731 16732 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 16733 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 16734 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 16735 if (!LegalOperations || 16736 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 16737 return DAG.getBitcast(VT, 16738 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 16739 } 16740 16741 return SDValue(); 16742 } 16743 16744 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 16745 // each source element of a large type into the lowest elements of a smaller 16746 // destination type. This is often generated during legalization. 16747 // If the source node itself was a '*_extend_vector_inreg' node then we should 16748 // then be able to remove it. 16749 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 16750 SelectionDAG &DAG) { 16751 EVT VT = SVN->getValueType(0); 16752 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 16753 16754 // TODO Add support for big-endian when we have a test case. 16755 if (!VT.isInteger() || IsBigEndian) 16756 return SDValue(); 16757 16758 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 16759 16760 unsigned Opcode = N0.getOpcode(); 16761 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 16762 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 16763 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 16764 return SDValue(); 16765 16766 SDValue N00 = N0.getOperand(0); 16767 ArrayRef<int> Mask = SVN->getMask(); 16768 unsigned NumElts = VT.getVectorNumElements(); 16769 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 16770 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 16771 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 16772 16773 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 16774 return SDValue(); 16775 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 16776 16777 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 16778 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 16779 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 16780 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 16781 for (unsigned i = 0; i != NumElts; ++i) { 16782 if (Mask[i] < 0) 16783 continue; 16784 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 16785 continue; 16786 return false; 16787 } 16788 return true; 16789 }; 16790 16791 // At the moment we just handle the case where we've truncated back to the 16792 // same size as before the extension. 16793 // TODO: handle more extension/truncation cases as cases arise. 16794 if (EltSizeInBits != ExtSrcSizeInBits) 16795 return SDValue(); 16796 16797 // We can remove *extend_vector_inreg only if the truncation happens at 16798 // the same scale as the extension. 16799 if (isTruncate(ExtScale)) 16800 return DAG.getBitcast(VT, N00); 16801 16802 return SDValue(); 16803 } 16804 16805 // Combine shuffles of splat-shuffles of the form: 16806 // shuffle (shuffle V, undef, splat-mask), undef, M 16807 // If splat-mask contains undef elements, we need to be careful about 16808 // introducing undef's in the folded mask which are not the result of composing 16809 // the masks of the shuffles. 16810 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 16811 ShuffleVectorSDNode *Splat, 16812 SelectionDAG &DAG) { 16813 ArrayRef<int> SplatMask = Splat->getMask(); 16814 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 16815 16816 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 16817 // every undef mask element in the splat-shuffle has a corresponding undef 16818 // element in the user-shuffle's mask or if the composition of mask elements 16819 // would result in undef. 16820 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 16821 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 16822 // In this case it is not legal to simplify to the splat-shuffle because we 16823 // may be exposing the users of the shuffle an undef element at index 1 16824 // which was not there before the combine. 16825 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 16826 // In this case the composition of masks yields SplatMask, so it's ok to 16827 // simplify to the splat-shuffle. 16828 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 16829 // In this case the composed mask includes all undef elements of SplatMask 16830 // and in addition sets element zero to undef. It is safe to simplify to 16831 // the splat-shuffle. 16832 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 16833 ArrayRef<int> SplatMask) { 16834 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 16835 if (UserMask[i] != -1 && SplatMask[i] == -1 && 16836 SplatMask[UserMask[i]] != -1) 16837 return false; 16838 return true; 16839 }; 16840 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 16841 return SDValue(Splat, 0); 16842 16843 // Create a new shuffle with a mask that is composed of the two shuffles' 16844 // masks. 16845 SmallVector<int, 32> NewMask; 16846 for (int Idx : UserMask) 16847 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 16848 16849 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 16850 Splat->getOperand(0), Splat->getOperand(1), 16851 NewMask); 16852 } 16853 16854 /// If the shuffle mask is taking exactly one element from the first vector 16855 /// operand and passing through all other elements from the second vector 16856 /// operand, return the index of the mask element that is choosing an element 16857 /// from the first operand. Otherwise, return -1. 16858 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 16859 int MaskSize = Mask.size(); 16860 int EltFromOp0 = -1; 16861 // TODO: This does not match if there are undef elements in the shuffle mask. 16862 // Should we ignore undefs in the shuffle mask instead? The trade-off is 16863 // removing an instruction (a shuffle), but losing the knowledge that some 16864 // vector lanes are not needed. 16865 for (int i = 0; i != MaskSize; ++i) { 16866 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 16867 // We're looking for a shuffle of exactly one element from operand 0. 16868 if (EltFromOp0 != -1) 16869 return -1; 16870 EltFromOp0 = i; 16871 } else if (Mask[i] != i + MaskSize) { 16872 // Nothing from operand 1 can change lanes. 16873 return -1; 16874 } 16875 } 16876 return EltFromOp0; 16877 } 16878 16879 /// If a shuffle inserts exactly one element from a source vector operand into 16880 /// another vector operand and we can access the specified element as a scalar, 16881 /// then we can eliminate the shuffle. 16882 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 16883 SelectionDAG &DAG) { 16884 // First, check if we are taking one element of a vector and shuffling that 16885 // element into another vector. 16886 ArrayRef<int> Mask = Shuf->getMask(); 16887 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 16888 SDValue Op0 = Shuf->getOperand(0); 16889 SDValue Op1 = Shuf->getOperand(1); 16890 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 16891 if (ShufOp0Index == -1) { 16892 // Commute mask and check again. 16893 ShuffleVectorSDNode::commuteMask(CommutedMask); 16894 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 16895 if (ShufOp0Index == -1) 16896 return SDValue(); 16897 // Commute operands to match the commuted shuffle mask. 16898 std::swap(Op0, Op1); 16899 Mask = CommutedMask; 16900 } 16901 16902 // The shuffle inserts exactly one element from operand 0 into operand 1. 16903 // Now see if we can access that element as a scalar via a real insert element 16904 // instruction. 16905 // TODO: We can try harder to locate the element as a scalar. Examples: it 16906 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 16907 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 16908 "Shuffle mask value must be from operand 0"); 16909 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 16910 return SDValue(); 16911 16912 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 16913 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 16914 return SDValue(); 16915 16916 // There's an existing insertelement with constant insertion index, so we 16917 // don't need to check the legality/profitability of a replacement operation 16918 // that differs at most in the constant value. The target should be able to 16919 // lower any of those in a similar way. If not, legalization will expand this 16920 // to a scalar-to-vector plus shuffle. 16921 // 16922 // Note that the shuffle may move the scalar from the position that the insert 16923 // element used. Therefore, our new insert element occurs at the shuffle's 16924 // mask index value, not the insert's index value. 16925 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 16926 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 16927 Op0.getOperand(2).getValueType()); 16928 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 16929 Op1, Op0.getOperand(1), NewInsIndex); 16930 } 16931 16932 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 16933 EVT VT = N->getValueType(0); 16934 unsigned NumElts = VT.getVectorNumElements(); 16935 16936 SDValue N0 = N->getOperand(0); 16937 SDValue N1 = N->getOperand(1); 16938 16939 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 16940 16941 // Canonicalize shuffle undef, undef -> undef 16942 if (N0.isUndef() && N1.isUndef()) 16943 return DAG.getUNDEF(VT); 16944 16945 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 16946 16947 // Canonicalize shuffle v, v -> v, undef 16948 if (N0 == N1) { 16949 SmallVector<int, 8> NewMask; 16950 for (unsigned i = 0; i != NumElts; ++i) { 16951 int Idx = SVN->getMaskElt(i); 16952 if (Idx >= (int)NumElts) Idx -= NumElts; 16953 NewMask.push_back(Idx); 16954 } 16955 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 16956 } 16957 16958 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 16959 if (N0.isUndef()) 16960 return DAG.getCommutedVectorShuffle(*SVN); 16961 16962 // Remove references to rhs if it is undef 16963 if (N1.isUndef()) { 16964 bool Changed = false; 16965 SmallVector<int, 8> NewMask; 16966 for (unsigned i = 0; i != NumElts; ++i) { 16967 int Idx = SVN->getMaskElt(i); 16968 if (Idx >= (int)NumElts) { 16969 Idx = -1; 16970 Changed = true; 16971 } 16972 NewMask.push_back(Idx); 16973 } 16974 if (Changed) 16975 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 16976 } 16977 16978 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 16979 return InsElt; 16980 16981 // A shuffle of a single vector that is a splat can always be folded. 16982 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 16983 if (N1->isUndef() && N0Shuf->isSplat()) 16984 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 16985 16986 // If it is a splat, check if the argument vector is another splat or a 16987 // build_vector. 16988 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 16989 SDNode *V = N0.getNode(); 16990 16991 // If this is a bit convert that changes the element type of the vector but 16992 // not the number of vector elements, look through it. Be careful not to 16993 // look though conversions that change things like v4f32 to v2f64. 16994 if (V->getOpcode() == ISD::BITCAST) { 16995 SDValue ConvInput = V->getOperand(0); 16996 if (ConvInput.getValueType().isVector() && 16997 ConvInput.getValueType().getVectorNumElements() == NumElts) 16998 V = ConvInput.getNode(); 16999 } 17000 17001 if (V->getOpcode() == ISD::BUILD_VECTOR) { 17002 assert(V->getNumOperands() == NumElts && 17003 "BUILD_VECTOR has wrong number of operands"); 17004 SDValue Base; 17005 bool AllSame = true; 17006 for (unsigned i = 0; i != NumElts; ++i) { 17007 if (!V->getOperand(i).isUndef()) { 17008 Base = V->getOperand(i); 17009 break; 17010 } 17011 } 17012 // Splat of <u, u, u, u>, return <u, u, u, u> 17013 if (!Base.getNode()) 17014 return N0; 17015 for (unsigned i = 0; i != NumElts; ++i) { 17016 if (V->getOperand(i) != Base) { 17017 AllSame = false; 17018 break; 17019 } 17020 } 17021 // Splat of <x, x, x, x>, return <x, x, x, x> 17022 if (AllSame) 17023 return N0; 17024 17025 // Canonicalize any other splat as a build_vector. 17026 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 17027 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 17028 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 17029 17030 // We may have jumped through bitcasts, so the type of the 17031 // BUILD_VECTOR may not match the type of the shuffle. 17032 if (V->getValueType(0) != VT) 17033 NewBV = DAG.getBitcast(VT, NewBV); 17034 return NewBV; 17035 } 17036 } 17037 17038 // Simplify source operands based on shuffle mask. 17039 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 17040 return SDValue(N, 0); 17041 17042 // Match shuffles that can be converted to any_vector_extend_in_reg. 17043 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 17044 return V; 17045 17046 // Combine "truncate_vector_in_reg" style shuffles. 17047 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 17048 return V; 17049 17050 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 17051 Level < AfterLegalizeVectorOps && 17052 (N1.isUndef() || 17053 (N1.getOpcode() == ISD::CONCAT_VECTORS && 17054 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 17055 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 17056 return V; 17057 } 17058 17059 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 17060 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 17061 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 17062 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 17063 return Res; 17064 17065 // If this shuffle only has a single input that is a bitcasted shuffle, 17066 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 17067 // back to their original types. 17068 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 17069 N1.isUndef() && Level < AfterLegalizeVectorOps && 17070 TLI.isTypeLegal(VT)) { 17071 17072 // Peek through the bitcast only if there is one user. 17073 SDValue BC0 = N0; 17074 while (BC0.getOpcode() == ISD::BITCAST) { 17075 if (!BC0.hasOneUse()) 17076 break; 17077 BC0 = BC0.getOperand(0); 17078 } 17079 17080 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 17081 if (Scale == 1) 17082 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 17083 17084 SmallVector<int, 8> NewMask; 17085 for (int M : Mask) 17086 for (int s = 0; s != Scale; ++s) 17087 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 17088 return NewMask; 17089 }; 17090 17091 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 17092 EVT SVT = VT.getScalarType(); 17093 EVT InnerVT = BC0->getValueType(0); 17094 EVT InnerSVT = InnerVT.getScalarType(); 17095 17096 // Determine which shuffle works with the smaller scalar type. 17097 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 17098 EVT ScaleSVT = ScaleVT.getScalarType(); 17099 17100 if (TLI.isTypeLegal(ScaleVT) && 17101 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 17102 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 17103 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17104 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17105 17106 // Scale the shuffle masks to the smaller scalar type. 17107 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 17108 SmallVector<int, 8> InnerMask = 17109 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 17110 SmallVector<int, 8> OuterMask = 17111 ScaleShuffleMask(SVN->getMask(), OuterScale); 17112 17113 // Merge the shuffle masks. 17114 SmallVector<int, 8> NewMask; 17115 for (int M : OuterMask) 17116 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 17117 17118 // Test for shuffle mask legality over both commutations. 17119 SDValue SV0 = BC0->getOperand(0); 17120 SDValue SV1 = BC0->getOperand(1); 17121 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17122 if (!LegalMask) { 17123 std::swap(SV0, SV1); 17124 ShuffleVectorSDNode::commuteMask(NewMask); 17125 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17126 } 17127 17128 if (LegalMask) { 17129 SV0 = DAG.getBitcast(ScaleVT, SV0); 17130 SV1 = DAG.getBitcast(ScaleVT, SV1); 17131 return DAG.getBitcast( 17132 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 17133 } 17134 } 17135 } 17136 } 17137 17138 // Canonicalize shuffles according to rules: 17139 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 17140 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 17141 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 17142 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 17143 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 17144 TLI.isTypeLegal(VT)) { 17145 // The incoming shuffle must be of the same type as the result of the 17146 // current shuffle. 17147 assert(N1->getOperand(0).getValueType() == VT && 17148 "Shuffle types don't match"); 17149 17150 SDValue SV0 = N1->getOperand(0); 17151 SDValue SV1 = N1->getOperand(1); 17152 bool HasSameOp0 = N0 == SV0; 17153 bool IsSV1Undef = SV1.isUndef(); 17154 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 17155 // Commute the operands of this shuffle so that next rule 17156 // will trigger. 17157 return DAG.getCommutedVectorShuffle(*SVN); 17158 } 17159 17160 // Try to fold according to rules: 17161 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17162 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17163 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17164 // Don't try to fold shuffles with illegal type. 17165 // Only fold if this shuffle is the only user of the other shuffle. 17166 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 17167 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 17168 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 17169 17170 // Don't try to fold splats; they're likely to simplify somehow, or they 17171 // might be free. 17172 if (OtherSV->isSplat()) 17173 return SDValue(); 17174 17175 // The incoming shuffle must be of the same type as the result of the 17176 // current shuffle. 17177 assert(OtherSV->getOperand(0).getValueType() == VT && 17178 "Shuffle types don't match"); 17179 17180 SDValue SV0, SV1; 17181 SmallVector<int, 4> Mask; 17182 // Compute the combined shuffle mask for a shuffle with SV0 as the first 17183 // operand, and SV1 as the second operand. 17184 for (unsigned i = 0; i != NumElts; ++i) { 17185 int Idx = SVN->getMaskElt(i); 17186 if (Idx < 0) { 17187 // Propagate Undef. 17188 Mask.push_back(Idx); 17189 continue; 17190 } 17191 17192 SDValue CurrentVec; 17193 if (Idx < (int)NumElts) { 17194 // This shuffle index refers to the inner shuffle N0. Lookup the inner 17195 // shuffle mask to identify which vector is actually referenced. 17196 Idx = OtherSV->getMaskElt(Idx); 17197 if (Idx < 0) { 17198 // Propagate Undef. 17199 Mask.push_back(Idx); 17200 continue; 17201 } 17202 17203 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 17204 : OtherSV->getOperand(1); 17205 } else { 17206 // This shuffle index references an element within N1. 17207 CurrentVec = N1; 17208 } 17209 17210 // Simple case where 'CurrentVec' is UNDEF. 17211 if (CurrentVec.isUndef()) { 17212 Mask.push_back(-1); 17213 continue; 17214 } 17215 17216 // Canonicalize the shuffle index. We don't know yet if CurrentVec 17217 // will be the first or second operand of the combined shuffle. 17218 Idx = Idx % NumElts; 17219 if (!SV0.getNode() || SV0 == CurrentVec) { 17220 // Ok. CurrentVec is the left hand side. 17221 // Update the mask accordingly. 17222 SV0 = CurrentVec; 17223 Mask.push_back(Idx); 17224 continue; 17225 } 17226 17227 // Bail out if we cannot convert the shuffle pair into a single shuffle. 17228 if (SV1.getNode() && SV1 != CurrentVec) 17229 return SDValue(); 17230 17231 // Ok. CurrentVec is the right hand side. 17232 // Update the mask accordingly. 17233 SV1 = CurrentVec; 17234 Mask.push_back(Idx + NumElts); 17235 } 17236 17237 // Check if all indices in Mask are Undef. In case, propagate Undef. 17238 bool isUndefMask = true; 17239 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 17240 isUndefMask &= Mask[i] < 0; 17241 17242 if (isUndefMask) 17243 return DAG.getUNDEF(VT); 17244 17245 if (!SV0.getNode()) 17246 SV0 = DAG.getUNDEF(VT); 17247 if (!SV1.getNode()) 17248 SV1 = DAG.getUNDEF(VT); 17249 17250 // Avoid introducing shuffles with illegal mask. 17251 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 17252 ShuffleVectorSDNode::commuteMask(Mask); 17253 17254 if (!TLI.isShuffleMaskLegal(Mask, VT)) 17255 return SDValue(); 17256 17257 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 17258 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 17259 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 17260 std::swap(SV0, SV1); 17261 } 17262 17263 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17264 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17265 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17266 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 17267 } 17268 17269 return SDValue(); 17270 } 17271 17272 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 17273 SDValue InVal = N->getOperand(0); 17274 EVT VT = N->getValueType(0); 17275 17276 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 17277 // with a VECTOR_SHUFFLE and possible truncate. 17278 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 17279 SDValue InVec = InVal->getOperand(0); 17280 SDValue EltNo = InVal->getOperand(1); 17281 auto InVecT = InVec.getValueType(); 17282 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 17283 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 17284 int Elt = C0->getZExtValue(); 17285 NewMask[0] = Elt; 17286 SDValue Val; 17287 // If we have an implict truncate do truncate here as long as it's legal. 17288 // if it's not legal, this should 17289 if (VT.getScalarType() != InVal.getValueType() && 17290 InVal.getValueType().isScalarInteger() && 17291 isTypeLegal(VT.getScalarType())) { 17292 Val = 17293 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 17294 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 17295 } 17296 if (VT.getScalarType() == InVecT.getScalarType() && 17297 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 17298 TLI.isShuffleMaskLegal(NewMask, VT)) { 17299 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 17300 DAG.getUNDEF(InVecT), NewMask); 17301 // If the initial vector is the correct size this shuffle is a 17302 // valid result. 17303 if (VT == InVecT) 17304 return Val; 17305 // If not we must truncate the vector. 17306 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 17307 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 17308 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 17309 EVT SubVT = 17310 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 17311 VT.getVectorNumElements()); 17312 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 17313 ZeroIdx); 17314 return Val; 17315 } 17316 } 17317 } 17318 } 17319 17320 return SDValue(); 17321 } 17322 17323 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 17324 EVT VT = N->getValueType(0); 17325 SDValue N0 = N->getOperand(0); 17326 SDValue N1 = N->getOperand(1); 17327 SDValue N2 = N->getOperand(2); 17328 17329 // If inserting an UNDEF, just return the original vector. 17330 if (N1.isUndef()) 17331 return N0; 17332 17333 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 17334 // us to pull BITCASTs from input to output. 17335 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 17336 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 17337 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 17338 17339 // If this is an insert of an extracted vector into an undef vector, we can 17340 // just use the input to the extract. 17341 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 17342 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 17343 return N1.getOperand(0); 17344 17345 // If we are inserting a bitcast value into an undef, with the same 17346 // number of elements, just use the bitcast input of the extract. 17347 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 17348 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 17349 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 17350 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 17351 N1.getOperand(0).getOperand(1) == N2 && 17352 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 17353 VT.getVectorNumElements() && 17354 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 17355 VT.getSizeInBits()) { 17356 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 17357 } 17358 17359 // If both N1 and N2 are bitcast values on which insert_subvector 17360 // would makes sense, pull the bitcast through. 17361 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 17362 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 17363 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 17364 SDValue CN0 = N0.getOperand(0); 17365 SDValue CN1 = N1.getOperand(0); 17366 EVT CN0VT = CN0.getValueType(); 17367 EVT CN1VT = CN1.getValueType(); 17368 if (CN0VT.isVector() && CN1VT.isVector() && 17369 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 17370 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) { 17371 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 17372 CN0.getValueType(), CN0, CN1, N2); 17373 return DAG.getBitcast(VT, NewINSERT); 17374 } 17375 } 17376 17377 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 17378 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 17379 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 17380 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 17381 N0.getOperand(1).getValueType() == N1.getValueType() && 17382 N0.getOperand(2) == N2) 17383 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 17384 N1, N2); 17385 17386 if (!isa<ConstantSDNode>(N2)) 17387 return SDValue(); 17388 17389 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 17390 17391 // Canonicalize insert_subvector dag nodes. 17392 // Example: 17393 // (insert_subvector (insert_subvector A, Idx0), Idx1) 17394 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 17395 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 17396 N1.getValueType() == N0.getOperand(1).getValueType() && 17397 isa<ConstantSDNode>(N0.getOperand(2))) { 17398 unsigned OtherIdx = N0.getConstantOperandVal(2); 17399 if (InsIdx < OtherIdx) { 17400 // Swap nodes. 17401 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 17402 N0.getOperand(0), N1, N2); 17403 AddToWorklist(NewOp.getNode()); 17404 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 17405 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 17406 } 17407 } 17408 17409 // If the input vector is a concatenation, and the insert replaces 17410 // one of the pieces, we can optimize into a single concat_vectors. 17411 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 17412 N0.getOperand(0).getValueType() == N1.getValueType()) { 17413 unsigned Factor = N1.getValueType().getVectorNumElements(); 17414 17415 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 17416 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 17417 17418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 17419 } 17420 17421 return SDValue(); 17422 } 17423 17424 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 17425 SDValue N0 = N->getOperand(0); 17426 17427 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 17428 if (N0->getOpcode() == ISD::FP16_TO_FP) 17429 return N0->getOperand(0); 17430 17431 return SDValue(); 17432 } 17433 17434 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 17435 SDValue N0 = N->getOperand(0); 17436 17437 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 17438 if (N0->getOpcode() == ISD::AND) { 17439 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 17440 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 17441 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 17442 N0.getOperand(0)); 17443 } 17444 } 17445 17446 return SDValue(); 17447 } 17448 17449 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 17450 /// with the destination vector and a zero vector. 17451 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 17452 /// vector_shuffle V, Zero, <0, 4, 2, 4> 17453 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 17454 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 17455 17456 EVT VT = N->getValueType(0); 17457 SDValue LHS = N->getOperand(0); 17458 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 17459 SDLoc DL(N); 17460 17461 // Make sure we're not running after operation legalization where it 17462 // may have custom lowered the vector shuffles. 17463 if (LegalOperations) 17464 return SDValue(); 17465 17466 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 17467 return SDValue(); 17468 17469 EVT RVT = RHS.getValueType(); 17470 unsigned NumElts = RHS.getNumOperands(); 17471 17472 // Attempt to create a valid clear mask, splitting the mask into 17473 // sub elements and checking to see if each is 17474 // all zeros or all ones - suitable for shuffle masking. 17475 auto BuildClearMask = [&](int Split) { 17476 int NumSubElts = NumElts * Split; 17477 int NumSubBits = RVT.getScalarSizeInBits() / Split; 17478 17479 SmallVector<int, 8> Indices; 17480 for (int i = 0; i != NumSubElts; ++i) { 17481 int EltIdx = i / Split; 17482 int SubIdx = i % Split; 17483 SDValue Elt = RHS.getOperand(EltIdx); 17484 if (Elt.isUndef()) { 17485 Indices.push_back(-1); 17486 continue; 17487 } 17488 17489 APInt Bits; 17490 if (isa<ConstantSDNode>(Elt)) 17491 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 17492 else if (isa<ConstantFPSDNode>(Elt)) 17493 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 17494 else 17495 return SDValue(); 17496 17497 // Extract the sub element from the constant bit mask. 17498 if (DAG.getDataLayout().isBigEndian()) { 17499 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 17500 } else { 17501 Bits.lshrInPlace(SubIdx * NumSubBits); 17502 } 17503 17504 if (Split > 1) 17505 Bits = Bits.trunc(NumSubBits); 17506 17507 if (Bits.isAllOnesValue()) 17508 Indices.push_back(i); 17509 else if (Bits == 0) 17510 Indices.push_back(i + NumSubElts); 17511 else 17512 return SDValue(); 17513 } 17514 17515 // Let's see if the target supports this vector_shuffle. 17516 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 17517 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 17518 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 17519 return SDValue(); 17520 17521 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 17522 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 17523 DAG.getBitcast(ClearVT, LHS), 17524 Zero, Indices)); 17525 }; 17526 17527 // Determine maximum split level (byte level masking). 17528 int MaxSplit = 1; 17529 if (RVT.getScalarSizeInBits() % 8 == 0) 17530 MaxSplit = RVT.getScalarSizeInBits() / 8; 17531 17532 for (int Split = 1; Split <= MaxSplit; ++Split) 17533 if (RVT.getScalarSizeInBits() % Split == 0) 17534 if (SDValue S = BuildClearMask(Split)) 17535 return S; 17536 17537 return SDValue(); 17538 } 17539 17540 /// Visit a binary vector operation, like ADD. 17541 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 17542 assert(N->getValueType(0).isVector() && 17543 "SimplifyVBinOp only works on vectors!"); 17544 17545 SDValue LHS = N->getOperand(0); 17546 SDValue RHS = N->getOperand(1); 17547 SDValue Ops[] = {LHS, RHS}; 17548 17549 // See if we can constant fold the vector operation. 17550 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 17551 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 17552 return Fold; 17553 17554 // Type legalization might introduce new shuffles in the DAG. 17555 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 17556 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 17557 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 17558 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 17559 LHS.getOperand(1).isUndef() && 17560 RHS.getOperand(1).isUndef()) { 17561 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 17562 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 17563 17564 if (SVN0->getMask().equals(SVN1->getMask())) { 17565 EVT VT = N->getValueType(0); 17566 SDValue UndefVector = LHS.getOperand(1); 17567 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 17568 LHS.getOperand(0), RHS.getOperand(0), 17569 N->getFlags()); 17570 AddUsersToWorklist(N); 17571 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 17572 SVN0->getMask()); 17573 } 17574 } 17575 17576 return SDValue(); 17577 } 17578 17579 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 17580 SDValue N2) { 17581 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 17582 17583 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 17584 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 17585 17586 // If we got a simplified select_cc node back from SimplifySelectCC, then 17587 // break it down into a new SETCC node, and a new SELECT node, and then return 17588 // the SELECT node, since we were called with a SELECT node. 17589 if (SCC.getNode()) { 17590 // Check to see if we got a select_cc back (to turn into setcc/select). 17591 // Otherwise, just return whatever node we got back, like fabs. 17592 if (SCC.getOpcode() == ISD::SELECT_CC) { 17593 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 17594 N0.getValueType(), 17595 SCC.getOperand(0), SCC.getOperand(1), 17596 SCC.getOperand(4)); 17597 AddToWorklist(SETCC.getNode()); 17598 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 17599 SCC.getOperand(2), SCC.getOperand(3)); 17600 } 17601 17602 return SCC; 17603 } 17604 return SDValue(); 17605 } 17606 17607 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 17608 /// being selected between, see if we can simplify the select. Callers of this 17609 /// should assume that TheSelect is deleted if this returns true. As such, they 17610 /// should return the appropriate thing (e.g. the node) back to the top-level of 17611 /// the DAG combiner loop to avoid it being looked at. 17612 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 17613 SDValue RHS) { 17614 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17615 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 17616 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 17617 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 17618 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 17619 SDValue Sqrt = RHS; 17620 ISD::CondCode CC; 17621 SDValue CmpLHS; 17622 const ConstantFPSDNode *Zero = nullptr; 17623 17624 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 17625 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 17626 CmpLHS = TheSelect->getOperand(0); 17627 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 17628 } else { 17629 // SELECT or VSELECT 17630 SDValue Cmp = TheSelect->getOperand(0); 17631 if (Cmp.getOpcode() == ISD::SETCC) { 17632 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 17633 CmpLHS = Cmp.getOperand(0); 17634 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 17635 } 17636 } 17637 if (Zero && Zero->isZero() && 17638 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 17639 CC == ISD::SETULT || CC == ISD::SETLT)) { 17640 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17641 CombineTo(TheSelect, Sqrt); 17642 return true; 17643 } 17644 } 17645 } 17646 // Cannot simplify select with vector condition 17647 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 17648 17649 // If this is a select from two identical things, try to pull the operation 17650 // through the select. 17651 if (LHS.getOpcode() != RHS.getOpcode() || 17652 !LHS.hasOneUse() || !RHS.hasOneUse()) 17653 return false; 17654 17655 // If this is a load and the token chain is identical, replace the select 17656 // of two loads with a load through a select of the address to load from. 17657 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 17658 // constants have been dropped into the constant pool. 17659 if (LHS.getOpcode() == ISD::LOAD) { 17660 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 17661 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 17662 17663 // Token chains must be identical. 17664 if (LHS.getOperand(0) != RHS.getOperand(0) || 17665 // Do not let this transformation reduce the number of volatile loads. 17666 LLD->isVolatile() || RLD->isVolatile() || 17667 // FIXME: If either is a pre/post inc/dec load, 17668 // we'd need to split out the address adjustment. 17669 LLD->isIndexed() || RLD->isIndexed() || 17670 // If this is an EXTLOAD, the VT's must match. 17671 LLD->getMemoryVT() != RLD->getMemoryVT() || 17672 // If this is an EXTLOAD, the kind of extension must match. 17673 (LLD->getExtensionType() != RLD->getExtensionType() && 17674 // The only exception is if one of the extensions is anyext. 17675 LLD->getExtensionType() != ISD::EXTLOAD && 17676 RLD->getExtensionType() != ISD::EXTLOAD) || 17677 // FIXME: this discards src value information. This is 17678 // over-conservative. It would be beneficial to be able to remember 17679 // both potential memory locations. Since we are discarding 17680 // src value info, don't do the transformation if the memory 17681 // locations are not in the default address space. 17682 LLD->getPointerInfo().getAddrSpace() != 0 || 17683 RLD->getPointerInfo().getAddrSpace() != 0 || 17684 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 17685 LLD->getBasePtr().getValueType())) 17686 return false; 17687 17688 // Check that the select condition doesn't reach either load. If so, 17689 // folding this will induce a cycle into the DAG. If not, this is safe to 17690 // xform, so create a select of the addresses. 17691 SDValue Addr; 17692 if (TheSelect->getOpcode() == ISD::SELECT) { 17693 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 17694 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 17695 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 17696 return false; 17697 // The loads must not depend on one another. 17698 if (LLD->isPredecessorOf(RLD) || 17699 RLD->isPredecessorOf(LLD)) 17700 return false; 17701 Addr = DAG.getSelect(SDLoc(TheSelect), 17702 LLD->getBasePtr().getValueType(), 17703 TheSelect->getOperand(0), LLD->getBasePtr(), 17704 RLD->getBasePtr()); 17705 } else { // Otherwise SELECT_CC 17706 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 17707 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 17708 17709 if ((LLD->hasAnyUseOfValue(1) && 17710 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 17711 (RLD->hasAnyUseOfValue(1) && 17712 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 17713 return false; 17714 17715 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 17716 LLD->getBasePtr().getValueType(), 17717 TheSelect->getOperand(0), 17718 TheSelect->getOperand(1), 17719 LLD->getBasePtr(), RLD->getBasePtr(), 17720 TheSelect->getOperand(4)); 17721 } 17722 17723 SDValue Load; 17724 // It is safe to replace the two loads if they have different alignments, 17725 // but the new load must be the minimum (most restrictive) alignment of the 17726 // inputs. 17727 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 17728 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 17729 if (!RLD->isInvariant()) 17730 MMOFlags &= ~MachineMemOperand::MOInvariant; 17731 if (!RLD->isDereferenceable()) 17732 MMOFlags &= ~MachineMemOperand::MODereferenceable; 17733 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 17734 // FIXME: Discards pointer and AA info. 17735 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 17736 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 17737 MMOFlags); 17738 } else { 17739 // FIXME: Discards pointer and AA info. 17740 Load = DAG.getExtLoad( 17741 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 17742 : LLD->getExtensionType(), 17743 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 17744 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 17745 } 17746 17747 // Users of the select now use the result of the load. 17748 CombineTo(TheSelect, Load); 17749 17750 // Users of the old loads now use the new load's chain. We know the 17751 // old-load value is dead now. 17752 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 17753 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 17754 return true; 17755 } 17756 17757 return false; 17758 } 17759 17760 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 17761 /// bitwise 'and'. 17762 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 17763 SDValue N1, SDValue N2, SDValue N3, 17764 ISD::CondCode CC) { 17765 // If this is a select where the false operand is zero and the compare is a 17766 // check of the sign bit, see if we can perform the "gzip trick": 17767 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 17768 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 17769 EVT XType = N0.getValueType(); 17770 EVT AType = N2.getValueType(); 17771 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 17772 return SDValue(); 17773 17774 // If the comparison is testing for a positive value, we have to invert 17775 // the sign bit mask, so only do that transform if the target has a bitwise 17776 // 'and not' instruction (the invert is free). 17777 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 17778 // (X > -1) ? A : 0 17779 // (X > 0) ? X : 0 <-- This is canonical signed max. 17780 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 17781 return SDValue(); 17782 } else if (CC == ISD::SETLT) { 17783 // (X < 0) ? A : 0 17784 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 17785 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 17786 return SDValue(); 17787 } else { 17788 return SDValue(); 17789 } 17790 17791 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 17792 // constant. 17793 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 17794 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 17795 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 17796 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 17797 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 17798 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 17799 AddToWorklist(Shift.getNode()); 17800 17801 if (XType.bitsGT(AType)) { 17802 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 17803 AddToWorklist(Shift.getNode()); 17804 } 17805 17806 if (CC == ISD::SETGT) 17807 Shift = DAG.getNOT(DL, Shift, AType); 17808 17809 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 17810 } 17811 17812 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 17813 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 17814 AddToWorklist(Shift.getNode()); 17815 17816 if (XType.bitsGT(AType)) { 17817 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 17818 AddToWorklist(Shift.getNode()); 17819 } 17820 17821 if (CC == ISD::SETGT) 17822 Shift = DAG.getNOT(DL, Shift, AType); 17823 17824 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 17825 } 17826 17827 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 17828 /// where 'cond' is the comparison specified by CC. 17829 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 17830 SDValue N2, SDValue N3, ISD::CondCode CC, 17831 bool NotExtCompare) { 17832 // (x ? y : y) -> y. 17833 if (N2 == N3) return N2; 17834 17835 EVT VT = N2.getValueType(); 17836 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 17837 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 17838 17839 // Determine if the condition we're dealing with is constant 17840 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 17841 N0, N1, CC, DL, false); 17842 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 17843 17844 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 17845 // fold select_cc true, x, y -> x 17846 // fold select_cc false, x, y -> y 17847 return !SCCC->isNullValue() ? N2 : N3; 17848 } 17849 17850 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 17851 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 17852 // in it. This is a win when the constant is not otherwise available because 17853 // it replaces two constant pool loads with one. We only do this if the FP 17854 // type is known to be legal, because if it isn't, then we are before legalize 17855 // types an we want the other legalization to happen first (e.g. to avoid 17856 // messing with soft float) and if the ConstantFP is not legal, because if 17857 // it is legal, we may not need to store the FP constant in a constant pool. 17858 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 17859 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 17860 if (TLI.isTypeLegal(N2.getValueType()) && 17861 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 17862 TargetLowering::Legal && 17863 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 17864 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 17865 // If both constants have multiple uses, then we won't need to do an 17866 // extra load, they are likely around in registers for other users. 17867 (TV->hasOneUse() || FV->hasOneUse())) { 17868 Constant *Elts[] = { 17869 const_cast<ConstantFP*>(FV->getConstantFPValue()), 17870 const_cast<ConstantFP*>(TV->getConstantFPValue()) 17871 }; 17872 Type *FPTy = Elts[0]->getType(); 17873 const DataLayout &TD = DAG.getDataLayout(); 17874 17875 // Create a ConstantArray of the two constants. 17876 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 17877 SDValue CPIdx = 17878 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 17879 TD.getPrefTypeAlignment(FPTy)); 17880 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 17881 17882 // Get the offsets to the 0 and 1 element of the array so that we can 17883 // select between them. 17884 SDValue Zero = DAG.getIntPtrConstant(0, DL); 17885 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 17886 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 17887 17888 SDValue Cond = DAG.getSetCC(DL, 17889 getSetCCResultType(N0.getValueType()), 17890 N0, N1, CC); 17891 AddToWorklist(Cond.getNode()); 17892 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 17893 Cond, One, Zero); 17894 AddToWorklist(CstOffset.getNode()); 17895 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 17896 CstOffset); 17897 AddToWorklist(CPIdx.getNode()); 17898 return DAG.getLoad( 17899 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 17900 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 17901 Alignment); 17902 } 17903 } 17904 17905 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 17906 return V; 17907 17908 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 17909 // where y is has a single bit set. 17910 // A plaintext description would be, we can turn the SELECT_CC into an AND 17911 // when the condition can be materialized as an all-ones register. Any 17912 // single bit-test can be materialized as an all-ones register with 17913 // shift-left and shift-right-arith. 17914 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 17915 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 17916 SDValue AndLHS = N0->getOperand(0); 17917 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 17918 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 17919 // Shift the tested bit over the sign bit. 17920 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 17921 SDValue ShlAmt = 17922 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 17923 getShiftAmountTy(AndLHS.getValueType())); 17924 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 17925 17926 // Now arithmetic right shift it all the way over, so the result is either 17927 // all-ones, or zero. 17928 SDValue ShrAmt = 17929 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 17930 getShiftAmountTy(Shl.getValueType())); 17931 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 17932 17933 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 17934 } 17935 } 17936 17937 // fold select C, 16, 0 -> shl C, 4 17938 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 17939 TLI.getBooleanContents(N0.getValueType()) == 17940 TargetLowering::ZeroOrOneBooleanContent) { 17941 17942 // If the caller doesn't want us to simplify this into a zext of a compare, 17943 // don't do it. 17944 if (NotExtCompare && N2C->isOne()) 17945 return SDValue(); 17946 17947 // Get a SetCC of the condition 17948 // NOTE: Don't create a SETCC if it's not legal on this target. 17949 if (!LegalOperations || 17950 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 17951 SDValue Temp, SCC; 17952 // cast from setcc result type to select result type 17953 if (LegalTypes) { 17954 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 17955 N0, N1, CC); 17956 if (N2.getValueType().bitsLT(SCC.getValueType())) 17957 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 17958 N2.getValueType()); 17959 else 17960 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17961 N2.getValueType(), SCC); 17962 } else { 17963 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 17964 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 17965 N2.getValueType(), SCC); 17966 } 17967 17968 AddToWorklist(SCC.getNode()); 17969 AddToWorklist(Temp.getNode()); 17970 17971 if (N2C->isOne()) 17972 return Temp; 17973 17974 // shl setcc result by log2 n2c 17975 return DAG.getNode( 17976 ISD::SHL, DL, N2.getValueType(), Temp, 17977 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 17978 getShiftAmountTy(Temp.getValueType()))); 17979 } 17980 } 17981 17982 // Check to see if this is an integer abs. 17983 // select_cc setg[te] X, 0, X, -X -> 17984 // select_cc setgt X, -1, X, -X -> 17985 // select_cc setl[te] X, 0, -X, X -> 17986 // select_cc setlt X, 1, -X, X -> 17987 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 17988 if (N1C) { 17989 ConstantSDNode *SubC = nullptr; 17990 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 17991 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 17992 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 17993 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 17994 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 17995 (N1C->isOne() && CC == ISD::SETLT)) && 17996 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 17997 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 17998 17999 EVT XType = N0.getValueType(); 18000 if (SubC && SubC->isNullValue() && XType.isInteger()) { 18001 SDLoc DL(N0); 18002 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 18003 N0, 18004 DAG.getConstant(XType.getSizeInBits() - 1, DL, 18005 getShiftAmountTy(N0.getValueType()))); 18006 SDValue Add = DAG.getNode(ISD::ADD, DL, 18007 XType, N0, Shift); 18008 AddToWorklist(Shift.getNode()); 18009 AddToWorklist(Add.getNode()); 18010 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 18011 } 18012 } 18013 18014 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 18015 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 18016 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 18017 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 18018 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 18019 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 18020 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 18021 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 18022 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 18023 SDValue ValueOnZero = N2; 18024 SDValue Count = N3; 18025 // If the condition is NE instead of E, swap the operands. 18026 if (CC == ISD::SETNE) 18027 std::swap(ValueOnZero, Count); 18028 // Check if the value on zero is a constant equal to the bits in the type. 18029 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 18030 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 18031 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 18032 // legal, combine to just cttz. 18033 if ((Count.getOpcode() == ISD::CTTZ || 18034 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 18035 N0 == Count.getOperand(0) && 18036 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 18037 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 18038 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 18039 // legal, combine to just ctlz. 18040 if ((Count.getOpcode() == ISD::CTLZ || 18041 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 18042 N0 == Count.getOperand(0) && 18043 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 18044 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 18045 } 18046 } 18047 } 18048 18049 return SDValue(); 18050 } 18051 18052 /// This is a stub for TargetLowering::SimplifySetCC. 18053 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 18054 ISD::CondCode Cond, const SDLoc &DL, 18055 bool foldBooleans) { 18056 TargetLowering::DAGCombinerInfo 18057 DagCombineInfo(DAG, Level, false, this); 18058 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 18059 } 18060 18061 /// Given an ISD::SDIV node expressing a divide by constant, return 18062 /// a DAG expression to select that will generate the same value by multiplying 18063 /// by a magic number. 18064 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18065 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 18066 // when optimising for minimum size, we don't want to expand a div to a mul 18067 // and a shift. 18068 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18069 return SDValue(); 18070 18071 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 18072 if (!C) 18073 return SDValue(); 18074 18075 // Avoid division by zero. 18076 if (C->isNullValue()) 18077 return SDValue(); 18078 18079 SmallVector<SDNode *, 8> Built; 18080 SDValue S = 18081 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, Built); 18082 18083 for (SDNode *N : Built) 18084 AddToWorklist(N); 18085 return S; 18086 } 18087 18088 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 18089 /// DAG expression that will generate the same value by right shifting. 18090 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 18091 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 18092 if (!C) 18093 return SDValue(); 18094 18095 // Avoid division by zero. 18096 if (C->isNullValue()) 18097 return SDValue(); 18098 18099 SmallVector<SDNode *, 8> Built; 18100 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built); 18101 18102 for (SDNode *N : Built) 18103 AddToWorklist(N); 18104 return S; 18105 } 18106 18107 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 18108 /// expression that will generate the same value by multiplying by a magic 18109 /// number. 18110 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18111 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 18112 // when optimising for minimum size, we don't want to expand a div to a mul 18113 // and a shift. 18114 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18115 return SDValue(); 18116 18117 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 18118 if (!C) 18119 return SDValue(); 18120 18121 // Avoid division by zero. 18122 if (C->isNullValue()) 18123 return SDValue(); 18124 18125 SmallVector<SDNode *, 8> Built; 18126 SDValue S = 18127 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, Built); 18128 18129 for (SDNode *N : Built) 18130 AddToWorklist(N); 18131 return S; 18132 } 18133 18134 /// Determines the LogBase2 value for a non-null input value using the 18135 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 18136 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 18137 EVT VT = V.getValueType(); 18138 unsigned EltBits = VT.getScalarSizeInBits(); 18139 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 18140 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 18141 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 18142 return LogBase2; 18143 } 18144 18145 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18146 /// For the reciprocal, we need to find the zero of the function: 18147 /// F(X) = A X - 1 [which has a zero at X = 1/A] 18148 /// => 18149 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 18150 /// does not require additional intermediate precision] 18151 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 18152 if (Level >= AfterLegalizeDAG) 18153 return SDValue(); 18154 18155 // TODO: Handle half and/or extended types? 18156 EVT VT = Op.getValueType(); 18157 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18158 return SDValue(); 18159 18160 // If estimates are explicitly disabled for this function, we're done. 18161 MachineFunction &MF = DAG.getMachineFunction(); 18162 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 18163 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18164 return SDValue(); 18165 18166 // Estimates may be explicitly enabled for this type with a custom number of 18167 // refinement steps. 18168 int Iterations = TLI.getDivRefinementSteps(VT, MF); 18169 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 18170 AddToWorklist(Est.getNode()); 18171 18172 if (Iterations) { 18173 EVT VT = Op.getValueType(); 18174 SDLoc DL(Op); 18175 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 18176 18177 // Newton iterations: Est = Est + Est (1 - Arg * Est) 18178 for (int i = 0; i < Iterations; ++i) { 18179 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 18180 AddToWorklist(NewEst.getNode()); 18181 18182 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 18183 AddToWorklist(NewEst.getNode()); 18184 18185 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18186 AddToWorklist(NewEst.getNode()); 18187 18188 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 18189 AddToWorklist(Est.getNode()); 18190 } 18191 } 18192 return Est; 18193 } 18194 18195 return SDValue(); 18196 } 18197 18198 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18199 /// For the reciprocal sqrt, we need to find the zero of the function: 18200 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18201 /// => 18202 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 18203 /// As a result, we precompute A/2 prior to the iteration loop. 18204 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 18205 unsigned Iterations, 18206 SDNodeFlags Flags, bool Reciprocal) { 18207 EVT VT = Arg.getValueType(); 18208 SDLoc DL(Arg); 18209 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 18210 18211 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 18212 // this entire sequence requires only one FP constant. 18213 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 18214 AddToWorklist(HalfArg.getNode()); 18215 18216 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 18217 AddToWorklist(HalfArg.getNode()); 18218 18219 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 18220 for (unsigned i = 0; i < Iterations; ++i) { 18221 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 18222 AddToWorklist(NewEst.getNode()); 18223 18224 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 18225 AddToWorklist(NewEst.getNode()); 18226 18227 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 18228 AddToWorklist(NewEst.getNode()); 18229 18230 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18231 AddToWorklist(Est.getNode()); 18232 } 18233 18234 // If non-reciprocal square root is requested, multiply the result by Arg. 18235 if (!Reciprocal) { 18236 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 18237 AddToWorklist(Est.getNode()); 18238 } 18239 18240 return Est; 18241 } 18242 18243 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18244 /// For the reciprocal sqrt, we need to find the zero of the function: 18245 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18246 /// => 18247 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 18248 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 18249 unsigned Iterations, 18250 SDNodeFlags Flags, bool Reciprocal) { 18251 EVT VT = Arg.getValueType(); 18252 SDLoc DL(Arg); 18253 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 18254 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 18255 18256 // This routine must enter the loop below to work correctly 18257 // when (Reciprocal == false). 18258 assert(Iterations > 0); 18259 18260 // Newton iterations for reciprocal square root: 18261 // E = (E * -0.5) * ((A * E) * E + -3.0) 18262 for (unsigned i = 0; i < Iterations; ++i) { 18263 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 18264 AddToWorklist(AE.getNode()); 18265 18266 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 18267 AddToWorklist(AEE.getNode()); 18268 18269 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 18270 AddToWorklist(RHS.getNode()); 18271 18272 // When calculating a square root at the last iteration build: 18273 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 18274 // (notice a common subexpression) 18275 SDValue LHS; 18276 if (Reciprocal || (i + 1) < Iterations) { 18277 // RSQRT: LHS = (E * -0.5) 18278 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 18279 } else { 18280 // SQRT: LHS = (A * E) * -0.5 18281 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 18282 } 18283 AddToWorklist(LHS.getNode()); 18284 18285 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 18286 AddToWorklist(Est.getNode()); 18287 } 18288 18289 return Est; 18290 } 18291 18292 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 18293 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 18294 /// Op can be zero. 18295 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 18296 bool Reciprocal) { 18297 if (Level >= AfterLegalizeDAG) 18298 return SDValue(); 18299 18300 // TODO: Handle half and/or extended types? 18301 EVT VT = Op.getValueType(); 18302 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18303 return SDValue(); 18304 18305 // If estimates are explicitly disabled for this function, we're done. 18306 MachineFunction &MF = DAG.getMachineFunction(); 18307 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 18308 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18309 return SDValue(); 18310 18311 // Estimates may be explicitly enabled for this type with a custom number of 18312 // refinement steps. 18313 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 18314 18315 bool UseOneConstNR = false; 18316 if (SDValue Est = 18317 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 18318 Reciprocal)) { 18319 AddToWorklist(Est.getNode()); 18320 18321 if (Iterations) { 18322 Est = UseOneConstNR 18323 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 18324 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 18325 18326 if (!Reciprocal) { 18327 // The estimate is now completely wrong if the input was exactly 0.0 or 18328 // possibly a denormal. Force the answer to 0.0 for those cases. 18329 EVT VT = Op.getValueType(); 18330 SDLoc DL(Op); 18331 EVT CCVT = getSetCCResultType(VT); 18332 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; 18333 const Function &F = DAG.getMachineFunction().getFunction(); 18334 Attribute Denorms = F.getFnAttribute("denormal-fp-math"); 18335 if (Denorms.getValueAsString().equals("ieee")) { 18336 // fabs(X) < SmallestNormal ? 0.0 : Est 18337 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 18338 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 18339 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 18340 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18341 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 18342 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 18343 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est); 18344 AddToWorklist(Fabs.getNode()); 18345 AddToWorklist(IsDenorm.getNode()); 18346 AddToWorklist(Est.getNode()); 18347 } else { 18348 // X == 0.0 ? 0.0 : Est 18349 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18350 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 18351 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est); 18352 AddToWorklist(IsZero.getNode()); 18353 AddToWorklist(Est.getNode()); 18354 } 18355 } 18356 } 18357 return Est; 18358 } 18359 18360 return SDValue(); 18361 } 18362 18363 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18364 return buildSqrtEstimateImpl(Op, Flags, true); 18365 } 18366 18367 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18368 return buildSqrtEstimateImpl(Op, Flags, false); 18369 } 18370 18371 /// Return true if there is any possibility that the two addresses overlap. 18372 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 18373 // If they are the same then they must be aliases. 18374 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 18375 18376 // If they are both volatile then they cannot be reordered. 18377 if (Op0->isVolatile() && Op1->isVolatile()) return true; 18378 18379 // If one operation reads from invariant memory, and the other may store, they 18380 // cannot alias. These should really be checking the equivalent of mayWrite, 18381 // but it only matters for memory nodes other than load /store. 18382 if (Op0->isInvariant() && Op1->writeMem()) 18383 return false; 18384 18385 if (Op1->isInvariant() && Op0->writeMem()) 18386 return false; 18387 18388 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 18389 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 18390 18391 // Check for BaseIndexOffset matching. 18392 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG); 18393 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG); 18394 int64_t PtrDiff; 18395 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) { 18396 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 18397 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 18398 18399 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 18400 // able to calculate their relative offset if at least one arises 18401 // from an alloca. However, these allocas cannot overlap and we 18402 // can infer there is no alias. 18403 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 18404 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 18405 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 18406 // If the base are the same frame index but the we couldn't find a 18407 // constant offset, (indices are different) be conservative. 18408 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 18409 !MFI.isFixedObjectIndex(B->getIndex()))) 18410 return false; 18411 } 18412 18413 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 18414 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 18415 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 18416 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 18417 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 18418 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 18419 18420 // If of mismatched base types or checkable indices we can check 18421 // they do not alias. 18422 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 18423 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 18424 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 18425 return false; 18426 } 18427 18428 // If we know required SrcValue1 and SrcValue2 have relatively large 18429 // alignment compared to the size and offset of the access, we may be able 18430 // to prove they do not alias. This check is conservative for now to catch 18431 // cases created by splitting vector types. 18432 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 18433 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 18434 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 18435 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 18436 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 18437 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 18438 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 18439 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 18440 18441 // There is no overlap between these relatively aligned accesses of 18442 // similar size. Return no alias. 18443 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 18444 (OffAlign1 + NumBytes1) <= OffAlign0) 18445 return false; 18446 } 18447 18448 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 18449 ? CombinerGlobalAA 18450 : DAG.getSubtarget().useAA(); 18451 #ifndef NDEBUG 18452 if (CombinerAAOnlyFunc.getNumOccurrences() && 18453 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 18454 UseAA = false; 18455 #endif 18456 18457 if (UseAA && AA && 18458 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 18459 // Use alias analysis information. 18460 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 18461 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 18462 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 18463 AliasResult AAResult = 18464 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 18465 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 18466 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 18467 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 18468 if (AAResult == NoAlias) 18469 return false; 18470 } 18471 18472 // Otherwise we have to assume they alias. 18473 return true; 18474 } 18475 18476 /// Walk up chain skipping non-aliasing memory nodes, 18477 /// looking for aliasing nodes and adding them to the Aliases vector. 18478 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 18479 SmallVectorImpl<SDValue> &Aliases) { 18480 SmallVector<SDValue, 8> Chains; // List of chains to visit. 18481 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 18482 18483 // Get alias information for node. 18484 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 18485 18486 // Starting off. 18487 Chains.push_back(OriginalChain); 18488 unsigned Depth = 0; 18489 18490 // Look at each chain and determine if it is an alias. If so, add it to the 18491 // aliases list. If not, then continue up the chain looking for the next 18492 // candidate. 18493 while (!Chains.empty()) { 18494 SDValue Chain = Chains.pop_back_val(); 18495 18496 // For TokenFactor nodes, look at each operand and only continue up the 18497 // chain until we reach the depth limit. 18498 // 18499 // FIXME: The depth check could be made to return the last non-aliasing 18500 // chain we found before we hit a tokenfactor rather than the original 18501 // chain. 18502 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 18503 Aliases.clear(); 18504 Aliases.push_back(OriginalChain); 18505 return; 18506 } 18507 18508 // Don't bother if we've been before. 18509 if (!Visited.insert(Chain.getNode()).second) 18510 continue; 18511 18512 switch (Chain.getOpcode()) { 18513 case ISD::EntryToken: 18514 // Entry token is ideal chain operand, but handled in FindBetterChain. 18515 break; 18516 18517 case ISD::LOAD: 18518 case ISD::STORE: { 18519 // Get alias information for Chain. 18520 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 18521 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 18522 18523 // If chain is alias then stop here. 18524 if (!(IsLoad && IsOpLoad) && 18525 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 18526 Aliases.push_back(Chain); 18527 } else { 18528 // Look further up the chain. 18529 Chains.push_back(Chain.getOperand(0)); 18530 ++Depth; 18531 } 18532 break; 18533 } 18534 18535 case ISD::TokenFactor: 18536 // We have to check each of the operands of the token factor for "small" 18537 // token factors, so we queue them up. Adding the operands to the queue 18538 // (stack) in reverse order maintains the original order and increases the 18539 // likelihood that getNode will find a matching token factor (CSE.) 18540 if (Chain.getNumOperands() > 16) { 18541 Aliases.push_back(Chain); 18542 break; 18543 } 18544 for (unsigned n = Chain.getNumOperands(); n;) 18545 Chains.push_back(Chain.getOperand(--n)); 18546 ++Depth; 18547 break; 18548 18549 case ISD::CopyFromReg: 18550 // Forward past CopyFromReg. 18551 Chains.push_back(Chain.getOperand(0)); 18552 ++Depth; 18553 break; 18554 18555 default: 18556 // For all other instructions we will just have to take what we can get. 18557 Aliases.push_back(Chain); 18558 break; 18559 } 18560 } 18561 } 18562 18563 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 18564 /// (aliasing node.) 18565 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 18566 if (OptLevel == CodeGenOpt::None) 18567 return OldChain; 18568 18569 // Ops for replacing token factor. 18570 SmallVector<SDValue, 8> Aliases; 18571 18572 // Accumulate all the aliases to this node. 18573 GatherAllAliases(N, OldChain, Aliases); 18574 18575 // If no operands then chain to entry token. 18576 if (Aliases.size() == 0) 18577 return DAG.getEntryNode(); 18578 18579 // If a single operand then chain to it. We don't need to revisit it. 18580 if (Aliases.size() == 1) 18581 return Aliases[0]; 18582 18583 // Construct a custom tailored token factor. 18584 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 18585 } 18586 18587 // This function tries to collect a bunch of potentially interesting 18588 // nodes to improve the chains of, all at once. This might seem 18589 // redundant, as this function gets called when visiting every store 18590 // node, so why not let the work be done on each store as it's visited? 18591 // 18592 // I believe this is mainly important because MergeConsecutiveStores 18593 // is unable to deal with merging stores of different sizes, so unless 18594 // we improve the chains of all the potential candidates up-front 18595 // before running MergeConsecutiveStores, it might only see some of 18596 // the nodes that will eventually be candidates, and then not be able 18597 // to go from a partially-merged state to the desired final 18598 // fully-merged state. 18599 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 18600 if (OptLevel == CodeGenOpt::None) 18601 return false; 18602 18603 // This holds the base pointer, index, and the offset in bytes from the base 18604 // pointer. 18605 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 18606 18607 // We must have a base and an offset. 18608 if (!BasePtr.getBase().getNode()) 18609 return false; 18610 18611 // Do not handle stores to undef base pointers. 18612 if (BasePtr.getBase().isUndef()) 18613 return false; 18614 18615 SmallVector<StoreSDNode *, 8> ChainedStores; 18616 ChainedStores.push_back(St); 18617 18618 // Walk up the chain and look for nodes with offsets from the same 18619 // base pointer. Stop when reaching an instruction with a different kind 18620 // or instruction which has a different base pointer. 18621 StoreSDNode *Index = St; 18622 while (Index) { 18623 // If the chain has more than one use, then we can't reorder the mem ops. 18624 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 18625 break; 18626 18627 if (Index->isVolatile() || Index->isIndexed()) 18628 break; 18629 18630 // Find the base pointer and offset for this memory node. 18631 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG); 18632 18633 // Check that the base pointer is the same as the original one. 18634 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 18635 break; 18636 18637 // Walk up the chain to find the next store node, ignoring any 18638 // intermediate loads. Any other kind of node will halt the loop. 18639 SDNode *NextInChain = Index->getChain().getNode(); 18640 while (true) { 18641 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 18642 // We found a store node. Use it for the next iteration. 18643 if (STn->isVolatile() || STn->isIndexed()) { 18644 Index = nullptr; 18645 break; 18646 } 18647 ChainedStores.push_back(STn); 18648 Index = STn; 18649 break; 18650 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 18651 NextInChain = Ldn->getChain().getNode(); 18652 continue; 18653 } else { 18654 Index = nullptr; 18655 break; 18656 } 18657 }// end while 18658 } 18659 18660 // At this point, ChainedStores lists all of the Store nodes 18661 // reachable by iterating up through chain nodes matching the above 18662 // conditions. For each such store identified, try to find an 18663 // earlier chain to attach the store to which won't violate the 18664 // required ordering. 18665 bool MadeChangeToSt = false; 18666 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 18667 18668 for (StoreSDNode *ChainedStore : ChainedStores) { 18669 SDValue Chain = ChainedStore->getChain(); 18670 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 18671 18672 if (Chain != BetterChain) { 18673 if (ChainedStore == St) 18674 MadeChangeToSt = true; 18675 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 18676 } 18677 } 18678 18679 // Do all replacements after finding the replacements to make to avoid making 18680 // the chains more complicated by introducing new TokenFactors. 18681 for (auto Replacement : BetterChains) 18682 replaceStoreChain(Replacement.first, Replacement.second); 18683 18684 return MadeChangeToSt; 18685 } 18686 18687 /// This is the entry point for the file. 18688 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 18689 CodeGenOpt::Level OptLevel) { 18690 /// This is the main entry point to this class. 18691 DAGCombiner(*this, AA, OptLevel).Run(Level); 18692 } 18693