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 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops"); 87 88 static cl::opt<bool> 89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 90 cl::desc("Enable DAG combiner's use of IR alias analysis")); 91 92 static cl::opt<bool> 93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 94 cl::desc("Enable DAG combiner's use of TBAA")); 95 96 #ifndef NDEBUG 97 static cl::opt<std::string> 98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 99 cl::desc("Only use DAG-combiner alias analysis in this" 100 " function")); 101 #endif 102 103 /// Hidden option to stress test load slicing, i.e., when this option 104 /// is enabled, load slicing bypasses most of its profitability guards. 105 static cl::opt<bool> 106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 107 cl::desc("Bypass the profitability model of load slicing"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 112 cl::desc("DAG combiner may split indexing from loads")); 113 114 namespace { 115 116 class DAGCombiner { 117 SelectionDAG &DAG; 118 const TargetLowering &TLI; 119 CombineLevel Level; 120 CodeGenOpt::Level OptLevel; 121 bool LegalOperations = false; 122 bool LegalTypes = false; 123 bool ForCodeSize; 124 125 /// Worklist of all of the nodes that need to be simplified. 126 /// 127 /// This must behave as a stack -- new nodes to process are pushed onto the 128 /// back and when processing we pop off of the back. 129 /// 130 /// The worklist will not contain duplicates but may contain null entries 131 /// due to nodes being deleted from the underlying DAG. 132 SmallVector<SDNode *, 64> Worklist; 133 134 /// Mapping from an SDNode to its position on the worklist. 135 /// 136 /// This is used to find and remove nodes from the worklist (by nulling 137 /// them) when they are deleted from the underlying DAG. It relies on 138 /// stable indices of nodes within the worklist. 139 DenseMap<SDNode *, unsigned> WorklistMap; 140 141 /// Set of nodes which have been combined (at least once). 142 /// 143 /// This is used to allow us to reliably add any operands of a DAG node 144 /// which have not yet been combined to the worklist. 145 SmallPtrSet<SDNode *, 32> CombinedNodes; 146 147 // AA - Used for DAG load/store alias analysis. 148 AliasAnalysis *AA; 149 150 /// When an instruction is simplified, add all users of the instruction to 151 /// the work lists because they might get more simplified now. 152 void AddUsersToWorklist(SDNode *N) { 153 for (SDNode *Node : N->uses()) 154 AddToWorklist(Node); 155 } 156 157 /// Call the node-specific routine that folds each particular type of node. 158 SDValue visit(SDNode *N); 159 160 public: 161 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 162 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 163 OptLevel(OL), AA(AA) { 164 ForCodeSize = DAG.getMachineFunction().getFunction().optForSize(); 165 166 MaximumLegalStoreInBits = 0; 167 for (MVT VT : MVT::all_valuetypes()) 168 if (EVT(VT).isSimple() && VT != MVT::Other && 169 TLI.isTypeLegal(EVT(VT)) && 170 VT.getSizeInBits() >= MaximumLegalStoreInBits) 171 MaximumLegalStoreInBits = VT.getSizeInBits(); 172 } 173 174 /// Add to the worklist making sure its instance is at the back (next to be 175 /// processed.) 176 void AddToWorklist(SDNode *N) { 177 assert(N->getOpcode() != ISD::DELETED_NODE && 178 "Deleted Node added to Worklist"); 179 180 // Skip handle nodes as they can't usefully be combined and confuse the 181 // zero-use deletion strategy. 182 if (N->getOpcode() == ISD::HANDLENODE) 183 return; 184 185 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 186 Worklist.push_back(N); 187 } 188 189 /// Remove all instances of N from the worklist. 190 void removeFromWorklist(SDNode *N) { 191 CombinedNodes.erase(N); 192 193 auto It = WorklistMap.find(N); 194 if (It == WorklistMap.end()) 195 return; // Not in the worklist. 196 197 // Null out the entry rather than erasing it to avoid a linear operation. 198 Worklist[It->second] = nullptr; 199 WorklistMap.erase(It); 200 } 201 202 void deleteAndRecombine(SDNode *N); 203 bool recursivelyDeleteUnusedNodes(SDNode *N); 204 205 /// Replaces all uses of the results of one DAG node with new values. 206 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 207 bool AddTo = true); 208 209 /// Replaces all uses of the results of one DAG node with new values. 210 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 211 return CombineTo(N, &Res, 1, AddTo); 212 } 213 214 /// Replaces all uses of the results of one DAG node with new values. 215 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 216 bool AddTo = true) { 217 SDValue To[] = { Res0, Res1 }; 218 return CombineTo(N, To, 2, AddTo); 219 } 220 221 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 222 223 private: 224 unsigned MaximumLegalStoreInBits; 225 226 /// Check the specified integer node value to see if it can be simplified or 227 /// if things it uses can be simplified by bit propagation. 228 /// If so, return true. 229 bool SimplifyDemandedBits(SDValue Op) { 230 unsigned BitWidth = Op.getScalarValueSizeInBits(); 231 APInt Demanded = APInt::getAllOnesValue(BitWidth); 232 return SimplifyDemandedBits(Op, Demanded); 233 } 234 235 /// Check the specified vector node value to see if it can be simplified or 236 /// if things it uses can be simplified as it only uses some of the 237 /// elements. If so, return true. 238 bool SimplifyDemandedVectorElts(SDValue Op) { 239 unsigned NumElts = Op.getValueType().getVectorNumElements(); 240 APInt Demanded = APInt::getAllOnesValue(NumElts); 241 return SimplifyDemandedVectorElts(Op, Demanded); 242 } 243 244 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 245 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded, 246 bool AssumeSingleUse = false); 247 248 bool CombineToPreIndexedLoadStore(SDNode *N); 249 bool CombineToPostIndexedLoadStore(SDNode *N); 250 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 251 bool SliceUpLoad(SDNode *N); 252 253 // Scalars have size 0 to distinguish from singleton vectors. 254 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD); 255 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val); 256 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val); 257 258 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 259 /// load. 260 /// 261 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 262 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 263 /// \param EltNo index of the vector element to load. 264 /// \param OriginalLoad load that EVE came from to be replaced. 265 /// \returns EVE on success SDValue() on failure. 266 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 267 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 268 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 269 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 270 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 271 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 272 SDValue PromoteIntBinOp(SDValue Op); 273 SDValue PromoteIntShiftOp(SDValue Op); 274 SDValue PromoteExtend(SDValue Op); 275 bool PromoteLoad(SDValue Op); 276 277 /// Call the node-specific routine that knows how to fold each 278 /// particular type of node. If that doesn't do anything, try the 279 /// target-specific DAG combines. 280 SDValue combine(SDNode *N); 281 282 // Visitation implementation - Implement dag node combining for different 283 // node types. The semantics are as follows: 284 // Return Value: 285 // SDValue.getNode() == 0 - No change was made 286 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 287 // otherwise - N should be replaced by the returned Operand. 288 // 289 SDValue visitTokenFactor(SDNode *N); 290 SDValue visitMERGE_VALUES(SDNode *N); 291 SDValue visitADD(SDNode *N); 292 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 293 SDValue visitSUB(SDNode *N); 294 SDValue visitADDC(SDNode *N); 295 SDValue visitUADDO(SDNode *N); 296 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 297 SDValue visitSUBC(SDNode *N); 298 SDValue visitUSUBO(SDNode *N); 299 SDValue visitADDE(SDNode *N); 300 SDValue visitADDCARRY(SDNode *N); 301 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 302 SDValue visitSUBE(SDNode *N); 303 SDValue visitSUBCARRY(SDNode *N); 304 SDValue visitMUL(SDNode *N); 305 SDValue useDivRem(SDNode *N); 306 SDValue visitSDIV(SDNode *N); 307 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N); 308 SDValue visitUDIV(SDNode *N); 309 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N); 310 SDValue visitREM(SDNode *N); 311 SDValue visitMULHU(SDNode *N); 312 SDValue visitMULHS(SDNode *N); 313 SDValue visitSMUL_LOHI(SDNode *N); 314 SDValue visitUMUL_LOHI(SDNode *N); 315 SDValue visitSMULO(SDNode *N); 316 SDValue visitUMULO(SDNode *N); 317 SDValue visitIMINMAX(SDNode *N); 318 SDValue visitAND(SDNode *N); 319 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N); 320 SDValue visitOR(SDNode *N); 321 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N); 322 SDValue visitXOR(SDNode *N); 323 SDValue SimplifyVBinOp(SDNode *N); 324 SDValue visitSHL(SDNode *N); 325 SDValue visitSRA(SDNode *N); 326 SDValue visitSRL(SDNode *N); 327 SDValue visitRotate(SDNode *N); 328 SDValue visitABS(SDNode *N); 329 SDValue visitBSWAP(SDNode *N); 330 SDValue visitBITREVERSE(SDNode *N); 331 SDValue visitCTLZ(SDNode *N); 332 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 333 SDValue visitCTTZ(SDNode *N); 334 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 335 SDValue visitCTPOP(SDNode *N); 336 SDValue visitSELECT(SDNode *N); 337 SDValue visitVSELECT(SDNode *N); 338 SDValue visitSELECT_CC(SDNode *N); 339 SDValue visitSETCC(SDNode *N); 340 SDValue visitSETCCCARRY(SDNode *N); 341 SDValue visitSIGN_EXTEND(SDNode *N); 342 SDValue visitZERO_EXTEND(SDNode *N); 343 SDValue visitANY_EXTEND(SDNode *N); 344 SDValue visitAssertExt(SDNode *N); 345 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 346 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 347 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 348 SDValue visitTRUNCATE(SDNode *N); 349 SDValue visitBITCAST(SDNode *N); 350 SDValue visitBUILD_PAIR(SDNode *N); 351 SDValue visitFADD(SDNode *N); 352 SDValue visitFSUB(SDNode *N); 353 SDValue visitFMUL(SDNode *N); 354 SDValue visitFMA(SDNode *N); 355 SDValue visitFDIV(SDNode *N); 356 SDValue visitFREM(SDNode *N); 357 SDValue visitFSQRT(SDNode *N); 358 SDValue visitFCOPYSIGN(SDNode *N); 359 SDValue visitFPOW(SDNode *N); 360 SDValue visitSINT_TO_FP(SDNode *N); 361 SDValue visitUINT_TO_FP(SDNode *N); 362 SDValue visitFP_TO_SINT(SDNode *N); 363 SDValue visitFP_TO_UINT(SDNode *N); 364 SDValue visitFP_ROUND(SDNode *N); 365 SDValue visitFP_ROUND_INREG(SDNode *N); 366 SDValue visitFP_EXTEND(SDNode *N); 367 SDValue visitFNEG(SDNode *N); 368 SDValue visitFABS(SDNode *N); 369 SDValue visitFCEIL(SDNode *N); 370 SDValue visitFTRUNC(SDNode *N); 371 SDValue visitFFLOOR(SDNode *N); 372 SDValue visitFMINNUM(SDNode *N); 373 SDValue visitFMAXNUM(SDNode *N); 374 SDValue visitFMINIMUM(SDNode *N); 375 SDValue visitFMAXIMUM(SDNode *N); 376 SDValue visitBRCOND(SDNode *N); 377 SDValue visitBR_CC(SDNode *N); 378 SDValue visitLOAD(SDNode *N); 379 380 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 381 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 382 383 SDValue visitSTORE(SDNode *N); 384 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 385 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 386 SDValue visitBUILD_VECTOR(SDNode *N); 387 SDValue visitCONCAT_VECTORS(SDNode *N); 388 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 389 SDValue visitVECTOR_SHUFFLE(SDNode *N); 390 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 391 SDValue visitINSERT_SUBVECTOR(SDNode *N); 392 SDValue visitMLOAD(SDNode *N); 393 SDValue visitMSTORE(SDNode *N); 394 SDValue visitMGATHER(SDNode *N); 395 SDValue visitMSCATTER(SDNode *N); 396 SDValue visitFP_TO_FP16(SDNode *N); 397 SDValue visitFP16_TO_FP(SDNode *N); 398 399 SDValue visitFADDForFMACombine(SDNode *N); 400 SDValue visitFSUBForFMACombine(SDNode *N); 401 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 402 403 SDValue XformToShuffleWithZero(SDNode *N); 404 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 405 SDValue N1, SDNodeFlags Flags); 406 407 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 408 409 SDValue foldSelectOfConstants(SDNode *N); 410 SDValue foldVSelectOfConstants(SDNode *N); 411 SDValue foldBinOpIntoSelect(SDNode *BO); 412 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 413 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 414 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 415 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 416 SDValue N2, SDValue N3, ISD::CondCode CC, 417 bool NotExtCompare = false); 418 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 419 SDValue N2, SDValue N3, ISD::CondCode CC); 420 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 421 const SDLoc &DL); 422 SDValue unfoldMaskedMerge(SDNode *N); 423 SDValue unfoldExtremeBitClearingToShifts(SDNode *N); 424 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 425 const SDLoc &DL, bool foldBooleans); 426 SDValue rebuildSetCC(SDValue N); 427 428 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 429 SDValue &CC) const; 430 bool isOneUseSetCC(SDValue N) const; 431 432 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 433 unsigned HiOp); 434 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 435 SDValue CombineExtLoad(SDNode *N); 436 SDValue CombineZExtLogicopShiftLoad(SDNode *N); 437 SDValue combineRepeatedFPDivisors(SDNode *N); 438 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 439 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 440 SDValue BuildSDIV(SDNode *N); 441 SDValue BuildSDIVPow2(SDNode *N); 442 SDValue BuildUDIV(SDNode *N); 443 SDValue BuildLogBase2(SDValue V, const SDLoc &DL); 444 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 445 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 446 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 447 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 448 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, 449 SDNodeFlags Flags, bool Reciprocal); 450 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, 451 SDNodeFlags Flags, bool Reciprocal); 452 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 453 bool DemandHighBits = true); 454 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 455 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 456 SDValue InnerPos, SDValue InnerNeg, 457 unsigned PosOpcode, unsigned NegOpcode, 458 const SDLoc &DL); 459 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 460 SDValue MatchLoadCombine(SDNode *N); 461 SDValue ReduceLoadWidth(SDNode *N); 462 SDValue ReduceLoadOpStoreWidth(SDNode *N); 463 SDValue splitMergedValStore(StoreSDNode *ST); 464 SDValue TransformFPLoadStorePair(SDNode *N); 465 SDValue convertBuildVecZextToZext(SDNode *N); 466 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 467 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 468 SDValue reduceBuildVecToShuffle(SDNode *N); 469 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 470 ArrayRef<int> VectorMask, SDValue VecIn1, 471 SDValue VecIn2, unsigned LeftIdx); 472 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); 473 474 /// Walk up chain skipping non-aliasing memory nodes, 475 /// looking for aliasing nodes and adding them to the Aliases vector. 476 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 477 SmallVectorImpl<SDValue> &Aliases); 478 479 /// Return true if there is any possibility that the two addresses overlap. 480 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 481 482 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 483 /// chain (aliasing node.) 484 SDValue FindBetterChain(SDNode *N, SDValue Chain); 485 486 /// Try to replace a store and any possibly adjacent stores on 487 /// consecutive chains with better chains. Return true only if St is 488 /// replaced. 489 /// 490 /// Notice that other chains may still be replaced even if the function 491 /// returns false. 492 bool findBetterNeighborChains(StoreSDNode *St); 493 494 /// Holds a pointer to an LSBaseSDNode as well as information on where it 495 /// is located in a sequence of memory operations connected by a chain. 496 struct MemOpLink { 497 // Ptr to the mem node. 498 LSBaseSDNode *MemNode; 499 500 // Offset from the base ptr. 501 int64_t OffsetFromBase; 502 503 MemOpLink(LSBaseSDNode *N, int64_t Offset) 504 : MemNode(N), OffsetFromBase(Offset) {} 505 }; 506 507 /// This is a helper function for visitMUL to check the profitability 508 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 509 /// MulNode is the original multiply, AddNode is (add x, c1), 510 /// and ConstNode is c2. 511 bool isMulAddWithConstProfitable(SDNode *MulNode, 512 SDValue &AddNode, 513 SDValue &ConstNode); 514 515 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 516 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 517 /// the type of the loaded value to be extended. 518 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 519 EVT LoadResultTy, EVT &ExtVT); 520 521 /// Helper function to calculate whether the given Load/Store can have its 522 /// width reduced to ExtVT. 523 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, 524 EVT &MemVT, unsigned ShAmt = 0); 525 526 /// Used by BackwardsPropagateMask to find suitable loads. 527 bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads, 528 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 529 ConstantSDNode *Mask, SDNode *&NodeToMask); 530 /// Attempt to propagate a given AND node back to load leaves so that they 531 /// can be combined into narrow loads. 532 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG); 533 534 /// Helper function for MergeConsecutiveStores which merges the 535 /// component store chains. 536 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 537 unsigned NumStores); 538 539 /// This is a helper function for MergeConsecutiveStores. When the 540 /// source elements of the consecutive stores are all constants or 541 /// all extracted vector elements, try to merge them into one 542 /// larger store introducing bitcasts if necessary. \return True 543 /// if a merged store was created. 544 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 545 EVT MemVT, unsigned NumStores, 546 bool IsConstantSrc, bool UseVector, 547 bool UseTrunc); 548 549 /// This is a helper function for MergeConsecutiveStores. Stores 550 /// that potentially may be merged with St are placed in 551 /// StoreNodes. RootNode is a chain predecessor to all store 552 /// candidates. 553 void getStoreMergeCandidates(StoreSDNode *St, 554 SmallVectorImpl<MemOpLink> &StoreNodes, 555 SDNode *&Root); 556 557 /// Helper function for MergeConsecutiveStores. Checks if 558 /// candidate stores have indirect dependency through their 559 /// operands. RootNode is the predecessor to all stores calculated 560 /// by getStoreMergeCandidates and is used to prune the dependency check. 561 /// \return True if safe to merge. 562 bool checkMergeStoreCandidatesForDependencies( 563 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 564 SDNode *RootNode); 565 566 /// Merge consecutive store operations into a wide store. 567 /// This optimization uses wide integers or vectors when possible. 568 /// \return number of stores that were merged into a merged store (the 569 /// affected nodes are stored as a prefix in \p StoreNodes). 570 bool MergeConsecutiveStores(StoreSDNode *St); 571 572 /// Try to transform a truncation where C is a constant: 573 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 574 /// 575 /// \p N needs to be a truncation and its first operand an AND. Other 576 /// requirements are checked by the function (e.g. that trunc is 577 /// single-use) and if missed an empty SDValue is returned. 578 SDValue distributeTruncateThroughAnd(SDNode *N); 579 580 /// Helper function to determine whether the target supports operation 581 /// given by \p Opcode for type \p VT, that is, whether the operation 582 /// is legal or custom before legalizing operations, and whether is 583 /// legal (but not custom) after legalization. 584 bool hasOperation(unsigned Opcode, EVT VT) { 585 if (LegalOperations) 586 return TLI.isOperationLegal(Opcode, VT); 587 return TLI.isOperationLegalOrCustom(Opcode, VT); 588 } 589 590 public: 591 /// Runs the dag combiner on all nodes in the work list 592 void Run(CombineLevel AtLevel); 593 594 SelectionDAG &getDAG() const { return DAG; } 595 596 /// Returns a type large enough to hold any valid shift amount - before type 597 /// legalization these can be huge. 598 EVT getShiftAmountTy(EVT LHSTy) { 599 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 600 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 601 } 602 603 /// This method returns true if we are running before type legalization or 604 /// if the specified VT is legal. 605 bool isTypeLegal(const EVT &VT) { 606 if (!LegalTypes) return true; 607 return TLI.isTypeLegal(VT); 608 } 609 610 /// Convenience wrapper around TargetLowering::getSetCCResultType 611 EVT getSetCCResultType(EVT VT) const { 612 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 613 } 614 615 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 616 SDValue OrigLoad, SDValue ExtLoad, 617 ISD::NodeType ExtType); 618 }; 619 620 /// This class is a DAGUpdateListener that removes any deleted 621 /// nodes from the worklist. 622 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 623 DAGCombiner &DC; 624 625 public: 626 explicit WorklistRemover(DAGCombiner &dc) 627 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 628 629 void NodeDeleted(SDNode *N, SDNode *E) override { 630 DC.removeFromWorklist(N); 631 } 632 }; 633 634 } // end anonymous namespace 635 636 //===----------------------------------------------------------------------===// 637 // TargetLowering::DAGCombinerInfo implementation 638 //===----------------------------------------------------------------------===// 639 640 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 641 ((DAGCombiner*)DC)->AddToWorklist(N); 642 } 643 644 SDValue TargetLowering::DAGCombinerInfo:: 645 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 646 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 647 } 648 649 SDValue TargetLowering::DAGCombinerInfo:: 650 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 651 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 652 } 653 654 SDValue TargetLowering::DAGCombinerInfo:: 655 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 656 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 657 } 658 659 void TargetLowering::DAGCombinerInfo:: 660 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 661 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 662 } 663 664 //===----------------------------------------------------------------------===// 665 // Helper Functions 666 //===----------------------------------------------------------------------===// 667 668 void DAGCombiner::deleteAndRecombine(SDNode *N) { 669 removeFromWorklist(N); 670 671 // If the operands of this node are only used by the node, they will now be 672 // dead. Make sure to re-visit them and recursively delete dead nodes. 673 for (const SDValue &Op : N->ops()) 674 // For an operand generating multiple values, one of the values may 675 // become dead allowing further simplification (e.g. split index 676 // arithmetic from an indexed load). 677 if (Op->hasOneUse() || Op->getNumValues() > 1) 678 AddToWorklist(Op.getNode()); 679 680 DAG.DeleteNode(N); 681 } 682 683 /// Return 1 if we can compute the negated form of the specified expression for 684 /// the same cost as the expression itself, or 2 if we can compute the negated 685 /// form more cheaply than the expression itself. 686 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 687 const TargetLowering &TLI, 688 const TargetOptions *Options, 689 unsigned Depth = 0) { 690 // fneg is removable even if it has multiple uses. 691 if (Op.getOpcode() == ISD::FNEG) return 2; 692 693 // Don't allow anything with multiple uses unless we know it is free. 694 EVT VT = Op.getValueType(); 695 const SDNodeFlags Flags = Op->getFlags(); 696 if (!Op.hasOneUse()) 697 if (!(Op.getOpcode() == ISD::FP_EXTEND && 698 TLI.isFPExtFree(VT, Op.getOperand(0).getValueType()))) 699 return 0; 700 701 // Don't recurse exponentially. 702 if (Depth > 6) return 0; 703 704 switch (Op.getOpcode()) { 705 default: return false; 706 case ISD::ConstantFP: { 707 if (!LegalOperations) 708 return 1; 709 710 // Don't invert constant FP values after legalization unless the target says 711 // the negated constant is legal. 712 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 713 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 714 } 715 case ISD::FADD: 716 if (!Options->UnsafeFPMath && !Flags.hasNoSignedZeros()) 717 return 0; 718 719 // After operation legalization, it might not be legal to create new FSUBs. 720 if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 721 return 0; 722 723 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 724 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 725 Options, Depth + 1)) 726 return V; 727 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 728 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 729 Depth + 1); 730 case ISD::FSUB: 731 // We can't turn -(A-B) into B-A when we honor signed zeros. 732 if (!Options->NoSignedZerosFPMath && 733 !Flags.hasNoSignedZeros()) 734 return 0; 735 736 // fold (fneg (fsub A, B)) -> (fsub B, A) 737 return 1; 738 739 case ISD::FMUL: 740 case ISD::FDIV: 741 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 742 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 743 Options, Depth + 1)) 744 return V; 745 746 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 747 Depth + 1); 748 749 case ISD::FP_EXTEND: 750 case ISD::FP_ROUND: 751 case ISD::FSIN: 752 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 753 Depth + 1); 754 } 755 } 756 757 /// If isNegatibleForFree returns true, return the newly negated expression. 758 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 759 bool LegalOperations, unsigned Depth = 0) { 760 const TargetOptions &Options = DAG.getTarget().Options; 761 // fneg is removable even if it has multiple uses. 762 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 763 764 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 765 766 const SDNodeFlags Flags = Op.getNode()->getFlags(); 767 768 switch (Op.getOpcode()) { 769 default: llvm_unreachable("Unknown code"); 770 case ISD::ConstantFP: { 771 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 772 V.changeSign(); 773 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 774 } 775 case ISD::FADD: 776 assert(Options.UnsafeFPMath || Flags.hasNoSignedZeros()); 777 778 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 779 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 780 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 781 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 782 GetNegatedExpression(Op.getOperand(0), DAG, 783 LegalOperations, Depth+1), 784 Op.getOperand(1), Flags); 785 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 786 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 787 GetNegatedExpression(Op.getOperand(1), DAG, 788 LegalOperations, Depth+1), 789 Op.getOperand(0), Flags); 790 case ISD::FSUB: 791 // fold (fneg (fsub 0, B)) -> B 792 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 793 if (N0CFP->isZero()) 794 return Op.getOperand(1); 795 796 // fold (fneg (fsub A, B)) -> (fsub B, A) 797 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 798 Op.getOperand(1), Op.getOperand(0), Flags); 799 800 case ISD::FMUL: 801 case ISD::FDIV: 802 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 803 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 804 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 805 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 806 GetNegatedExpression(Op.getOperand(0), DAG, 807 LegalOperations, Depth+1), 808 Op.getOperand(1), Flags); 809 810 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 811 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 812 Op.getOperand(0), 813 GetNegatedExpression(Op.getOperand(1), DAG, 814 LegalOperations, Depth+1), Flags); 815 816 case ISD::FP_EXTEND: 817 case ISD::FSIN: 818 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 819 GetNegatedExpression(Op.getOperand(0), DAG, 820 LegalOperations, Depth+1)); 821 case ISD::FP_ROUND: 822 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 823 GetNegatedExpression(Op.getOperand(0), DAG, 824 LegalOperations, Depth+1), 825 Op.getOperand(1)); 826 } 827 } 828 829 // APInts must be the same size for most operations, this helper 830 // function zero extends the shorter of the pair so that they match. 831 // We provide an Offset so that we can create bitwidths that won't overflow. 832 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 833 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 834 LHS = LHS.zextOrSelf(Bits); 835 RHS = RHS.zextOrSelf(Bits); 836 } 837 838 // Return true if this node is a setcc, or is a select_cc 839 // that selects between the target values used for true and false, making it 840 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 841 // the appropriate nodes based on the type of node we are checking. This 842 // simplifies life a bit for the callers. 843 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 844 SDValue &CC) const { 845 if (N.getOpcode() == ISD::SETCC) { 846 LHS = N.getOperand(0); 847 RHS = N.getOperand(1); 848 CC = N.getOperand(2); 849 return true; 850 } 851 852 if (N.getOpcode() != ISD::SELECT_CC || 853 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 854 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 855 return false; 856 857 if (TLI.getBooleanContents(N.getValueType()) == 858 TargetLowering::UndefinedBooleanContent) 859 return false; 860 861 LHS = N.getOperand(0); 862 RHS = N.getOperand(1); 863 CC = N.getOperand(4); 864 return true; 865 } 866 867 /// Return true if this is a SetCC-equivalent operation with only one use. 868 /// If this is true, it allows the users to invert the operation for free when 869 /// it is profitable to do so. 870 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 871 SDValue N0, N1, N2; 872 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 873 return true; 874 return false; 875 } 876 877 // Returns the SDNode if it is a constant float BuildVector 878 // or constant float. 879 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 880 if (isa<ConstantFPSDNode>(N)) 881 return N.getNode(); 882 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 883 return N.getNode(); 884 return nullptr; 885 } 886 887 // Determines if it is a constant integer or a build vector of constant 888 // integers (and undefs). 889 // Do not permit build vector implicit truncation. 890 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 891 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 892 return !(Const->isOpaque() && NoOpaques); 893 if (N.getOpcode() != ISD::BUILD_VECTOR) 894 return false; 895 unsigned BitWidth = N.getScalarValueSizeInBits(); 896 for (const SDValue &Op : N->op_values()) { 897 if (Op.isUndef()) 898 continue; 899 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 900 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 901 (Const->isOpaque() && NoOpaques)) 902 return false; 903 } 904 return true; 905 } 906 907 // Determines if it is a constant null integer or a splatted vector of a 908 // constant null integer (with no undefs). 909 // Build vector implicit truncation is not an issue for null values. 910 static bool isNullConstantOrNullSplatConstant(SDValue N) { 911 // TODO: may want to use peekThroughBitcast() here. 912 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 913 return Splat->isNullValue(); 914 return false; 915 } 916 917 // Determines if it is a constant integer of one or a splatted vector of a 918 // constant integer of one (with no undefs). 919 // Do not permit build vector implicit truncation. 920 static bool isOneConstantOrOneSplatConstant(SDValue N) { 921 // TODO: may want to use peekThroughBitcast() here. 922 unsigned BitWidth = N.getScalarValueSizeInBits(); 923 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 924 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 925 return false; 926 } 927 928 // Determines if it is a constant integer of all ones or a splatted vector of a 929 // constant integer of all ones (with no undefs). 930 // Do not permit build vector implicit truncation. 931 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 932 N = peekThroughBitcasts(N); 933 unsigned BitWidth = N.getScalarValueSizeInBits(); 934 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 935 return Splat->isAllOnesValue() && 936 Splat->getAPIntValue().getBitWidth() == BitWidth; 937 return false; 938 } 939 940 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 941 // undef's. 942 static bool isAnyConstantBuildVector(const SDNode *N) { 943 return ISD::isBuildVectorOfConstantSDNodes(N) || 944 ISD::isBuildVectorOfConstantFPSDNodes(N); 945 } 946 947 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 948 SDValue N1, SDNodeFlags Flags) { 949 // Don't reassociate reductions. 950 if (Flags.hasVectorReduction()) 951 return SDValue(); 952 953 EVT VT = N0.getValueType(); 954 if (N0.getOpcode() == Opc && !N0->getFlags().hasVectorReduction()) { 955 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 956 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 957 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 958 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 959 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 960 return SDValue(); 961 } 962 if (N0.hasOneUse()) { 963 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 964 // use 965 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 966 if (!OpNode.getNode()) 967 return SDValue(); 968 AddToWorklist(OpNode.getNode()); 969 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 970 } 971 } 972 } 973 974 if (N1.getOpcode() == Opc && !N1->getFlags().hasVectorReduction()) { 975 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 976 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 977 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 978 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 979 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 980 return SDValue(); 981 } 982 if (N1.hasOneUse()) { 983 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 984 // use 985 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 986 if (!OpNode.getNode()) 987 return SDValue(); 988 AddToWorklist(OpNode.getNode()); 989 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 990 } 991 } 992 } 993 994 return SDValue(); 995 } 996 997 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 998 bool AddTo) { 999 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1000 ++NodesCombined; 1001 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 1002 To[0].getNode()->dump(&DAG); 1003 dbgs() << " and " << NumTo - 1 << " other values\n"); 1004 for (unsigned i = 0, e = NumTo; i != e; ++i) 1005 assert((!To[i].getNode() || 1006 N->getValueType(i) == To[i].getValueType()) && 1007 "Cannot combine value to value of different type!"); 1008 1009 WorklistRemover DeadNodes(*this); 1010 DAG.ReplaceAllUsesWith(N, To); 1011 if (AddTo) { 1012 // Push the new nodes and any users onto the worklist 1013 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1014 if (To[i].getNode()) { 1015 AddToWorklist(To[i].getNode()); 1016 AddUsersToWorklist(To[i].getNode()); 1017 } 1018 } 1019 } 1020 1021 // Finally, if the node is now dead, remove it from the graph. The node 1022 // may not be dead if the replacement process recursively simplified to 1023 // something else needing this node. 1024 if (N->use_empty()) 1025 deleteAndRecombine(N); 1026 return SDValue(N, 0); 1027 } 1028 1029 void DAGCombiner:: 1030 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1031 // Replace all uses. If any nodes become isomorphic to other nodes and 1032 // are deleted, make sure to remove them from our worklist. 1033 WorklistRemover DeadNodes(*this); 1034 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1035 1036 // Push the new node and any (possibly new) users onto the worklist. 1037 AddToWorklist(TLO.New.getNode()); 1038 AddUsersToWorklist(TLO.New.getNode()); 1039 1040 // Finally, if the node is now dead, remove it from the graph. The node 1041 // may not be dead if the replacement process recursively simplified to 1042 // something else needing this node. 1043 if (TLO.Old.getNode()->use_empty()) 1044 deleteAndRecombine(TLO.Old.getNode()); 1045 } 1046 1047 /// Check the specified integer node value to see if it can be simplified or if 1048 /// things it uses can be simplified by bit propagation. If so, return true. 1049 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1050 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1051 KnownBits Known; 1052 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1053 return false; 1054 1055 // Revisit the node. 1056 AddToWorklist(Op.getNode()); 1057 1058 // Replace the old value with the new one. 1059 ++NodesCombined; 1060 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1061 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1062 dbgs() << '\n'); 1063 1064 CommitTargetLoweringOpt(TLO); 1065 return true; 1066 } 1067 1068 /// Check the specified vector node value to see if it can be simplified or 1069 /// if things it uses can be simplified as it only uses some of the elements. 1070 /// If so, return true. 1071 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded, 1072 bool AssumeSingleUse) { 1073 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1074 APInt KnownUndef, KnownZero; 1075 if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO, 1076 0, AssumeSingleUse)) 1077 return false; 1078 1079 // Revisit the node. 1080 AddToWorklist(Op.getNode()); 1081 1082 // Replace the old value with the new one. 1083 ++NodesCombined; 1084 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1085 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1086 dbgs() << '\n'); 1087 1088 CommitTargetLoweringOpt(TLO); 1089 return true; 1090 } 1091 1092 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1093 SDLoc DL(Load); 1094 EVT VT = Load->getValueType(0); 1095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1096 1097 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1098 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1099 WorklistRemover DeadNodes(*this); 1100 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1101 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1102 deleteAndRecombine(Load); 1103 AddToWorklist(Trunc.getNode()); 1104 } 1105 1106 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1107 Replace = false; 1108 SDLoc DL(Op); 1109 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1110 LoadSDNode *LD = cast<LoadSDNode>(Op); 1111 EVT MemVT = LD->getMemoryVT(); 1112 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1113 : LD->getExtensionType(); 1114 Replace = true; 1115 return DAG.getExtLoad(ExtType, DL, PVT, 1116 LD->getChain(), LD->getBasePtr(), 1117 MemVT, LD->getMemOperand()); 1118 } 1119 1120 unsigned Opc = Op.getOpcode(); 1121 switch (Opc) { 1122 default: break; 1123 case ISD::AssertSext: 1124 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1125 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1126 break; 1127 case ISD::AssertZext: 1128 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1129 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1130 break; 1131 case ISD::Constant: { 1132 unsigned ExtOpc = 1133 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1134 return DAG.getNode(ExtOpc, DL, PVT, Op); 1135 } 1136 } 1137 1138 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1139 return SDValue(); 1140 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1141 } 1142 1143 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1144 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1145 return SDValue(); 1146 EVT OldVT = Op.getValueType(); 1147 SDLoc DL(Op); 1148 bool Replace = false; 1149 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1150 if (!NewOp.getNode()) 1151 return SDValue(); 1152 AddToWorklist(NewOp.getNode()); 1153 1154 if (Replace) 1155 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1156 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1157 DAG.getValueType(OldVT)); 1158 } 1159 1160 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1161 EVT OldVT = Op.getValueType(); 1162 SDLoc DL(Op); 1163 bool Replace = false; 1164 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1165 if (!NewOp.getNode()) 1166 return SDValue(); 1167 AddToWorklist(NewOp.getNode()); 1168 1169 if (Replace) 1170 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1171 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1172 } 1173 1174 /// Promote the specified integer binary operation if the target indicates it is 1175 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1176 /// i32 since i16 instructions are longer. 1177 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1178 if (!LegalOperations) 1179 return SDValue(); 1180 1181 EVT VT = Op.getValueType(); 1182 if (VT.isVector() || !VT.isInteger()) 1183 return SDValue(); 1184 1185 // If operation type is 'undesirable', e.g. i16 on x86, consider 1186 // promoting it. 1187 unsigned Opc = Op.getOpcode(); 1188 if (TLI.isTypeDesirableForOp(Opc, VT)) 1189 return SDValue(); 1190 1191 EVT PVT = VT; 1192 // Consult target whether it is a good idea to promote this operation and 1193 // what's the right type to promote it to. 1194 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1195 assert(PVT != VT && "Don't know what type to promote to!"); 1196 1197 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1198 1199 bool Replace0 = false; 1200 SDValue N0 = Op.getOperand(0); 1201 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1202 1203 bool Replace1 = false; 1204 SDValue N1 = Op.getOperand(1); 1205 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1206 SDLoc DL(Op); 1207 1208 SDValue RV = 1209 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1210 1211 // We are always replacing N0/N1's use in N and only need 1212 // additional replacements if there are additional uses. 1213 Replace0 &= !N0->hasOneUse(); 1214 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1215 1216 // Combine Op here so it is preserved past replacements. 1217 CombineTo(Op.getNode(), RV); 1218 1219 // If operands have a use ordering, make sure we deal with 1220 // predecessor first. 1221 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1222 std::swap(N0, N1); 1223 std::swap(NN0, NN1); 1224 } 1225 1226 if (Replace0) { 1227 AddToWorklist(NN0.getNode()); 1228 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1229 } 1230 if (Replace1) { 1231 AddToWorklist(NN1.getNode()); 1232 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1233 } 1234 return Op; 1235 } 1236 return SDValue(); 1237 } 1238 1239 /// Promote the specified integer shift operation if the target indicates it is 1240 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1241 /// i32 since i16 instructions are longer. 1242 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1243 if (!LegalOperations) 1244 return SDValue(); 1245 1246 EVT VT = Op.getValueType(); 1247 if (VT.isVector() || !VT.isInteger()) 1248 return SDValue(); 1249 1250 // If operation type is 'undesirable', e.g. i16 on x86, consider 1251 // promoting it. 1252 unsigned Opc = Op.getOpcode(); 1253 if (TLI.isTypeDesirableForOp(Opc, VT)) 1254 return SDValue(); 1255 1256 EVT PVT = VT; 1257 // Consult target whether it is a good idea to promote this operation and 1258 // what's the right type to promote it to. 1259 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1260 assert(PVT != VT && "Don't know what type to promote to!"); 1261 1262 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1263 1264 bool Replace = false; 1265 SDValue N0 = Op.getOperand(0); 1266 SDValue N1 = Op.getOperand(1); 1267 if (Opc == ISD::SRA) 1268 N0 = SExtPromoteOperand(N0, PVT); 1269 else if (Opc == ISD::SRL) 1270 N0 = ZExtPromoteOperand(N0, PVT); 1271 else 1272 N0 = PromoteOperand(N0, PVT, Replace); 1273 1274 if (!N0.getNode()) 1275 return SDValue(); 1276 1277 SDLoc DL(Op); 1278 SDValue RV = 1279 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1280 1281 AddToWorklist(N0.getNode()); 1282 if (Replace) 1283 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1284 1285 // Deal with Op being deleted. 1286 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1287 return RV; 1288 } 1289 return SDValue(); 1290 } 1291 1292 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1293 if (!LegalOperations) 1294 return SDValue(); 1295 1296 EVT VT = Op.getValueType(); 1297 if (VT.isVector() || !VT.isInteger()) 1298 return SDValue(); 1299 1300 // If operation type is 'undesirable', e.g. i16 on x86, consider 1301 // promoting it. 1302 unsigned Opc = Op.getOpcode(); 1303 if (TLI.isTypeDesirableForOp(Opc, VT)) 1304 return SDValue(); 1305 1306 EVT PVT = VT; 1307 // Consult target whether it is a good idea to promote this operation and 1308 // what's the right type to promote it to. 1309 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1310 assert(PVT != VT && "Don't know what type to promote to!"); 1311 // fold (aext (aext x)) -> (aext x) 1312 // fold (aext (zext x)) -> (zext x) 1313 // fold (aext (sext x)) -> (sext x) 1314 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1315 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1316 } 1317 return SDValue(); 1318 } 1319 1320 bool DAGCombiner::PromoteLoad(SDValue Op) { 1321 if (!LegalOperations) 1322 return false; 1323 1324 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1325 return false; 1326 1327 EVT VT = Op.getValueType(); 1328 if (VT.isVector() || !VT.isInteger()) 1329 return false; 1330 1331 // If operation type is 'undesirable', e.g. i16 on x86, consider 1332 // promoting it. 1333 unsigned Opc = Op.getOpcode(); 1334 if (TLI.isTypeDesirableForOp(Opc, VT)) 1335 return false; 1336 1337 EVT PVT = VT; 1338 // Consult target whether it is a good idea to promote this operation and 1339 // what's the right type to promote it to. 1340 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1341 assert(PVT != VT && "Don't know what type to promote to!"); 1342 1343 SDLoc DL(Op); 1344 SDNode *N = Op.getNode(); 1345 LoadSDNode *LD = cast<LoadSDNode>(N); 1346 EVT MemVT = LD->getMemoryVT(); 1347 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1348 : LD->getExtensionType(); 1349 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1350 LD->getChain(), LD->getBasePtr(), 1351 MemVT, LD->getMemOperand()); 1352 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1353 1354 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1355 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1356 WorklistRemover DeadNodes(*this); 1357 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1358 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1359 deleteAndRecombine(N); 1360 AddToWorklist(Result.getNode()); 1361 return true; 1362 } 1363 return false; 1364 } 1365 1366 /// Recursively delete a node which has no uses and any operands for 1367 /// which it is the only use. 1368 /// 1369 /// Note that this both deletes the nodes and removes them from the worklist. 1370 /// It also adds any nodes who have had a user deleted to the worklist as they 1371 /// may now have only one use and subject to other combines. 1372 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1373 if (!N->use_empty()) 1374 return false; 1375 1376 SmallSetVector<SDNode *, 16> Nodes; 1377 Nodes.insert(N); 1378 do { 1379 N = Nodes.pop_back_val(); 1380 if (!N) 1381 continue; 1382 1383 if (N->use_empty()) { 1384 for (const SDValue &ChildN : N->op_values()) 1385 Nodes.insert(ChildN.getNode()); 1386 1387 removeFromWorklist(N); 1388 DAG.DeleteNode(N); 1389 } else { 1390 AddToWorklist(N); 1391 } 1392 } while (!Nodes.empty()); 1393 return true; 1394 } 1395 1396 //===----------------------------------------------------------------------===// 1397 // Main DAG Combiner implementation 1398 //===----------------------------------------------------------------------===// 1399 1400 void DAGCombiner::Run(CombineLevel AtLevel) { 1401 // set the instance variables, so that the various visit routines may use it. 1402 Level = AtLevel; 1403 LegalOperations = Level >= AfterLegalizeVectorOps; 1404 LegalTypes = Level >= AfterLegalizeTypes; 1405 1406 // Add all the dag nodes to the worklist. 1407 for (SDNode &Node : DAG.allnodes()) 1408 AddToWorklist(&Node); 1409 1410 // Create a dummy node (which is not added to allnodes), that adds a reference 1411 // to the root node, preventing it from being deleted, and tracking any 1412 // changes of the root. 1413 HandleSDNode Dummy(DAG.getRoot()); 1414 1415 // While the worklist isn't empty, find a node and try to combine it. 1416 while (!WorklistMap.empty()) { 1417 SDNode *N; 1418 // The Worklist holds the SDNodes in order, but it may contain null entries. 1419 do { 1420 N = Worklist.pop_back_val(); 1421 } while (!N); 1422 1423 bool GoodWorklistEntry = WorklistMap.erase(N); 1424 (void)GoodWorklistEntry; 1425 assert(GoodWorklistEntry && 1426 "Found a worklist entry without a corresponding map entry!"); 1427 1428 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1429 // N is deleted from the DAG, since they too may now be dead or may have a 1430 // reduced number of uses, allowing other xforms. 1431 if (recursivelyDeleteUnusedNodes(N)) 1432 continue; 1433 1434 WorklistRemover DeadNodes(*this); 1435 1436 // If this combine is running after legalizing the DAG, re-legalize any 1437 // nodes pulled off the worklist. 1438 if (Level == AfterLegalizeDAG) { 1439 SmallSetVector<SDNode *, 16> UpdatedNodes; 1440 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1441 1442 for (SDNode *LN : UpdatedNodes) { 1443 AddToWorklist(LN); 1444 AddUsersToWorklist(LN); 1445 } 1446 if (!NIsValid) 1447 continue; 1448 } 1449 1450 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1451 1452 // Add any operands of the new node which have not yet been combined to the 1453 // worklist as well. Because the worklist uniques things already, this 1454 // won't repeatedly process the same operand. 1455 CombinedNodes.insert(N); 1456 for (const SDValue &ChildN : N->op_values()) 1457 if (!CombinedNodes.count(ChildN.getNode())) 1458 AddToWorklist(ChildN.getNode()); 1459 1460 SDValue RV = combine(N); 1461 1462 if (!RV.getNode()) 1463 continue; 1464 1465 ++NodesCombined; 1466 1467 // If we get back the same node we passed in, rather than a new node or 1468 // zero, we know that the node must have defined multiple values and 1469 // CombineTo was used. Since CombineTo takes care of the worklist 1470 // mechanics for us, we have no work to do in this case. 1471 if (RV.getNode() == N) 1472 continue; 1473 1474 assert(N->getOpcode() != ISD::DELETED_NODE && 1475 RV.getOpcode() != ISD::DELETED_NODE && 1476 "Node was deleted but visit returned new node!"); 1477 1478 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1479 1480 if (N->getNumValues() == RV.getNode()->getNumValues()) 1481 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1482 else { 1483 assert(N->getValueType(0) == RV.getValueType() && 1484 N->getNumValues() == 1 && "Type mismatch"); 1485 DAG.ReplaceAllUsesWith(N, &RV); 1486 } 1487 1488 // Push the new node and any users onto the worklist 1489 AddToWorklist(RV.getNode()); 1490 AddUsersToWorklist(RV.getNode()); 1491 1492 // Finally, if the node is now dead, remove it from the graph. The node 1493 // may not be dead if the replacement process recursively simplified to 1494 // something else needing this node. This will also take care of adding any 1495 // operands which have lost a user to the worklist. 1496 recursivelyDeleteUnusedNodes(N); 1497 } 1498 1499 // If the root changed (e.g. it was a dead load, update the root). 1500 DAG.setRoot(Dummy.getValue()); 1501 DAG.RemoveDeadNodes(); 1502 } 1503 1504 SDValue DAGCombiner::visit(SDNode *N) { 1505 switch (N->getOpcode()) { 1506 default: break; 1507 case ISD::TokenFactor: return visitTokenFactor(N); 1508 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1509 case ISD::ADD: return visitADD(N); 1510 case ISD::SUB: return visitSUB(N); 1511 case ISD::ADDC: return visitADDC(N); 1512 case ISD::UADDO: return visitUADDO(N); 1513 case ISD::SUBC: return visitSUBC(N); 1514 case ISD::USUBO: return visitUSUBO(N); 1515 case ISD::ADDE: return visitADDE(N); 1516 case ISD::ADDCARRY: return visitADDCARRY(N); 1517 case ISD::SUBE: return visitSUBE(N); 1518 case ISD::SUBCARRY: return visitSUBCARRY(N); 1519 case ISD::MUL: return visitMUL(N); 1520 case ISD::SDIV: return visitSDIV(N); 1521 case ISD::UDIV: return visitUDIV(N); 1522 case ISD::SREM: 1523 case ISD::UREM: return visitREM(N); 1524 case ISD::MULHU: return visitMULHU(N); 1525 case ISD::MULHS: return visitMULHS(N); 1526 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1527 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1528 case ISD::SMULO: return visitSMULO(N); 1529 case ISD::UMULO: return visitUMULO(N); 1530 case ISD::SMIN: 1531 case ISD::SMAX: 1532 case ISD::UMIN: 1533 case ISD::UMAX: return visitIMINMAX(N); 1534 case ISD::AND: return visitAND(N); 1535 case ISD::OR: return visitOR(N); 1536 case ISD::XOR: return visitXOR(N); 1537 case ISD::SHL: return visitSHL(N); 1538 case ISD::SRA: return visitSRA(N); 1539 case ISD::SRL: return visitSRL(N); 1540 case ISD::ROTR: 1541 case ISD::ROTL: return visitRotate(N); 1542 case ISD::ABS: return visitABS(N); 1543 case ISD::BSWAP: return visitBSWAP(N); 1544 case ISD::BITREVERSE: return visitBITREVERSE(N); 1545 case ISD::CTLZ: return visitCTLZ(N); 1546 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1547 case ISD::CTTZ: return visitCTTZ(N); 1548 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1549 case ISD::CTPOP: return visitCTPOP(N); 1550 case ISD::SELECT: return visitSELECT(N); 1551 case ISD::VSELECT: return visitVSELECT(N); 1552 case ISD::SELECT_CC: return visitSELECT_CC(N); 1553 case ISD::SETCC: return visitSETCC(N); 1554 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1555 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1556 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1557 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1558 case ISD::AssertSext: 1559 case ISD::AssertZext: return visitAssertExt(N); 1560 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1561 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1562 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1563 case ISD::TRUNCATE: return visitTRUNCATE(N); 1564 case ISD::BITCAST: return visitBITCAST(N); 1565 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1566 case ISD::FADD: return visitFADD(N); 1567 case ISD::FSUB: return visitFSUB(N); 1568 case ISD::FMUL: return visitFMUL(N); 1569 case ISD::FMA: return visitFMA(N); 1570 case ISD::FDIV: return visitFDIV(N); 1571 case ISD::FREM: return visitFREM(N); 1572 case ISD::FSQRT: return visitFSQRT(N); 1573 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1574 case ISD::FPOW: return visitFPOW(N); 1575 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1576 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1577 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1578 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1579 case ISD::FP_ROUND: return visitFP_ROUND(N); 1580 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1581 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1582 case ISD::FNEG: return visitFNEG(N); 1583 case ISD::FABS: return visitFABS(N); 1584 case ISD::FFLOOR: return visitFFLOOR(N); 1585 case ISD::FMINNUM: return visitFMINNUM(N); 1586 case ISD::FMAXNUM: return visitFMAXNUM(N); 1587 case ISD::FMINIMUM: return visitFMINIMUM(N); 1588 case ISD::FMAXIMUM: return visitFMAXIMUM(N); 1589 case ISD::FCEIL: return visitFCEIL(N); 1590 case ISD::FTRUNC: return visitFTRUNC(N); 1591 case ISD::BRCOND: return visitBRCOND(N); 1592 case ISD::BR_CC: return visitBR_CC(N); 1593 case ISD::LOAD: return visitLOAD(N); 1594 case ISD::STORE: return visitSTORE(N); 1595 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1596 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1597 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1598 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1599 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1600 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1601 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1602 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1603 case ISD::MGATHER: return visitMGATHER(N); 1604 case ISD::MLOAD: return visitMLOAD(N); 1605 case ISD::MSCATTER: return visitMSCATTER(N); 1606 case ISD::MSTORE: return visitMSTORE(N); 1607 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1608 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1609 } 1610 return SDValue(); 1611 } 1612 1613 SDValue DAGCombiner::combine(SDNode *N) { 1614 SDValue RV = visit(N); 1615 1616 // If nothing happened, try a target-specific DAG combine. 1617 if (!RV.getNode()) { 1618 assert(N->getOpcode() != ISD::DELETED_NODE && 1619 "Node was deleted but visit returned NULL!"); 1620 1621 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1622 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1623 1624 // Expose the DAG combiner to the target combiner impls. 1625 TargetLowering::DAGCombinerInfo 1626 DagCombineInfo(DAG, Level, false, this); 1627 1628 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1629 } 1630 } 1631 1632 // If nothing happened still, try promoting the operation. 1633 if (!RV.getNode()) { 1634 switch (N->getOpcode()) { 1635 default: break; 1636 case ISD::ADD: 1637 case ISD::SUB: 1638 case ISD::MUL: 1639 case ISD::AND: 1640 case ISD::OR: 1641 case ISD::XOR: 1642 RV = PromoteIntBinOp(SDValue(N, 0)); 1643 break; 1644 case ISD::SHL: 1645 case ISD::SRA: 1646 case ISD::SRL: 1647 RV = PromoteIntShiftOp(SDValue(N, 0)); 1648 break; 1649 case ISD::SIGN_EXTEND: 1650 case ISD::ZERO_EXTEND: 1651 case ISD::ANY_EXTEND: 1652 RV = PromoteExtend(SDValue(N, 0)); 1653 break; 1654 case ISD::LOAD: 1655 if (PromoteLoad(SDValue(N, 0))) 1656 RV = SDValue(N, 0); 1657 break; 1658 } 1659 } 1660 1661 // If N is a commutative binary node, try eliminate it if the commuted 1662 // version is already present in the DAG. 1663 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1664 N->getNumValues() == 1) { 1665 SDValue N0 = N->getOperand(0); 1666 SDValue N1 = N->getOperand(1); 1667 1668 // Constant operands are canonicalized to RHS. 1669 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1670 SDValue Ops[] = {N1, N0}; 1671 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1672 N->getFlags()); 1673 if (CSENode) 1674 return SDValue(CSENode, 0); 1675 } 1676 } 1677 1678 return RV; 1679 } 1680 1681 /// Given a node, return its input chain if it has one, otherwise return a null 1682 /// sd operand. 1683 static SDValue getInputChainForNode(SDNode *N) { 1684 if (unsigned NumOps = N->getNumOperands()) { 1685 if (N->getOperand(0).getValueType() == MVT::Other) 1686 return N->getOperand(0); 1687 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1688 return N->getOperand(NumOps-1); 1689 for (unsigned i = 1; i < NumOps-1; ++i) 1690 if (N->getOperand(i).getValueType() == MVT::Other) 1691 return N->getOperand(i); 1692 } 1693 return SDValue(); 1694 } 1695 1696 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1697 // If N has two operands, where one has an input chain equal to the other, 1698 // the 'other' chain is redundant. 1699 if (N->getNumOperands() == 2) { 1700 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1701 return N->getOperand(0); 1702 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1703 return N->getOperand(1); 1704 } 1705 1706 // Don't simplify token factors if optnone. 1707 if (OptLevel == CodeGenOpt::None) 1708 return SDValue(); 1709 1710 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1711 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1712 SmallPtrSet<SDNode*, 16> SeenOps; 1713 bool Changed = false; // If we should replace this token factor. 1714 1715 // Start out with this token factor. 1716 TFs.push_back(N); 1717 1718 // Iterate through token factors. The TFs grows when new token factors are 1719 // encountered. 1720 for (unsigned i = 0; i < TFs.size(); ++i) { 1721 SDNode *TF = TFs[i]; 1722 1723 // Check each of the operands. 1724 for (const SDValue &Op : TF->op_values()) { 1725 switch (Op.getOpcode()) { 1726 case ISD::EntryToken: 1727 // Entry tokens don't need to be added to the list. They are 1728 // redundant. 1729 Changed = true; 1730 break; 1731 1732 case ISD::TokenFactor: 1733 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1734 // Queue up for processing. 1735 TFs.push_back(Op.getNode()); 1736 // Clean up in case the token factor is removed. 1737 AddToWorklist(Op.getNode()); 1738 Changed = true; 1739 break; 1740 } 1741 LLVM_FALLTHROUGH; 1742 1743 default: 1744 // Only add if it isn't already in the list. 1745 if (SeenOps.insert(Op.getNode()).second) 1746 Ops.push_back(Op); 1747 else 1748 Changed = true; 1749 break; 1750 } 1751 } 1752 } 1753 1754 // Remove Nodes that are chained to another node in the list. Do so 1755 // by walking up chains breath-first stopping when we've seen 1756 // another operand. In general we must climb to the EntryNode, but we can exit 1757 // early if we find all remaining work is associated with just one operand as 1758 // no further pruning is possible. 1759 1760 // List of nodes to search through and original Ops from which they originate. 1761 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1762 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1763 SmallPtrSet<SDNode *, 16> SeenChains; 1764 bool DidPruneOps = false; 1765 1766 unsigned NumLeftToConsider = 0; 1767 for (const SDValue &Op : Ops) { 1768 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1769 OpWorkCount.push_back(1); 1770 } 1771 1772 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1773 // If this is an Op, we can remove the op from the list. Remark any 1774 // search associated with it as from the current OpNumber. 1775 if (SeenOps.count(Op) != 0) { 1776 Changed = true; 1777 DidPruneOps = true; 1778 unsigned OrigOpNumber = 0; 1779 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1780 OrigOpNumber++; 1781 assert((OrigOpNumber != Ops.size()) && 1782 "expected to find TokenFactor Operand"); 1783 // Re-mark worklist from OrigOpNumber to OpNumber 1784 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1785 if (Worklist[i].second == OrigOpNumber) { 1786 Worklist[i].second = OpNumber; 1787 } 1788 } 1789 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1790 OpWorkCount[OrigOpNumber] = 0; 1791 NumLeftToConsider--; 1792 } 1793 // Add if it's a new chain 1794 if (SeenChains.insert(Op).second) { 1795 OpWorkCount[OpNumber]++; 1796 Worklist.push_back(std::make_pair(Op, OpNumber)); 1797 } 1798 }; 1799 1800 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1801 // We need at least be consider at least 2 Ops to prune. 1802 if (NumLeftToConsider <= 1) 1803 break; 1804 auto CurNode = Worklist[i].first; 1805 auto CurOpNumber = Worklist[i].second; 1806 assert((OpWorkCount[CurOpNumber] > 0) && 1807 "Node should not appear in worklist"); 1808 switch (CurNode->getOpcode()) { 1809 case ISD::EntryToken: 1810 // Hitting EntryToken is the only way for the search to terminate without 1811 // hitting 1812 // another operand's search. Prevent us from marking this operand 1813 // considered. 1814 NumLeftToConsider++; 1815 break; 1816 case ISD::TokenFactor: 1817 for (const SDValue &Op : CurNode->op_values()) 1818 AddToWorklist(i, Op.getNode(), CurOpNumber); 1819 break; 1820 case ISD::CopyFromReg: 1821 case ISD::CopyToReg: 1822 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1823 break; 1824 default: 1825 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1826 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1827 break; 1828 } 1829 OpWorkCount[CurOpNumber]--; 1830 if (OpWorkCount[CurOpNumber] == 0) 1831 NumLeftToConsider--; 1832 } 1833 1834 // If we've changed things around then replace token factor. 1835 if (Changed) { 1836 SDValue Result; 1837 if (Ops.empty()) { 1838 // The entry token is the only possible outcome. 1839 Result = DAG.getEntryNode(); 1840 } else { 1841 if (DidPruneOps) { 1842 SmallVector<SDValue, 8> PrunedOps; 1843 // 1844 for (const SDValue &Op : Ops) { 1845 if (SeenChains.count(Op.getNode()) == 0) 1846 PrunedOps.push_back(Op); 1847 } 1848 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1849 } else { 1850 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1851 } 1852 } 1853 return Result; 1854 } 1855 return SDValue(); 1856 } 1857 1858 /// MERGE_VALUES can always be eliminated. 1859 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1860 WorklistRemover DeadNodes(*this); 1861 // Replacing results may cause a different MERGE_VALUES to suddenly 1862 // be CSE'd with N, and carry its uses with it. Iterate until no 1863 // uses remain, to ensure that the node can be safely deleted. 1864 // First add the users of this node to the work list so that they 1865 // can be tried again once they have new operands. 1866 AddUsersToWorklist(N); 1867 do { 1868 // Do as a single replacement to avoid rewalking use lists. 1869 SmallVector<SDValue, 8> Ops; 1870 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1871 Ops.push_back(N->getOperand(i)); 1872 DAG.ReplaceAllUsesWith(N, Ops.data()); 1873 } while (!N->use_empty()); 1874 deleteAndRecombine(N); 1875 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1876 } 1877 1878 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1879 /// ConstantSDNode pointer else nullptr. 1880 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1881 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1882 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1883 } 1884 1885 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1886 assert(ISD::isBinaryOp(BO) && "Unexpected binary operator"); 1887 1888 // Don't do this unless the old select is going away. We want to eliminate the 1889 // binary operator, not replace a binop with a select. 1890 // TODO: Handle ISD::SELECT_CC. 1891 unsigned SelOpNo = 0; 1892 SDValue Sel = BO->getOperand(0); 1893 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 1894 SelOpNo = 1; 1895 Sel = BO->getOperand(1); 1896 } 1897 1898 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1899 return SDValue(); 1900 1901 SDValue CT = Sel.getOperand(1); 1902 if (!isConstantOrConstantVector(CT, true) && 1903 !isConstantFPBuildVectorOrConstantFP(CT)) 1904 return SDValue(); 1905 1906 SDValue CF = Sel.getOperand(2); 1907 if (!isConstantOrConstantVector(CF, true) && 1908 !isConstantFPBuildVectorOrConstantFP(CF)) 1909 return SDValue(); 1910 1911 // Bail out if any constants are opaque because we can't constant fold those. 1912 // The exception is "and" and "or" with either 0 or -1 in which case we can 1913 // propagate non constant operands into select. I.e.: 1914 // and (select Cond, 0, -1), X --> select Cond, 0, X 1915 // or X, (select Cond, -1, 0) --> select Cond, -1, X 1916 auto BinOpcode = BO->getOpcode(); 1917 bool CanFoldNonConst = (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 1918 (isNullConstantOrNullSplatConstant(CT) || 1919 isAllOnesConstantOrAllOnesSplatConstant(CT)) && 1920 (isNullConstantOrNullSplatConstant(CF) || 1921 isAllOnesConstantOrAllOnesSplatConstant(CF)); 1922 1923 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 1924 if (!CanFoldNonConst && 1925 !isConstantOrConstantVector(CBO, true) && 1926 !isConstantFPBuildVectorOrConstantFP(CBO)) 1927 return SDValue(); 1928 1929 EVT VT = Sel.getValueType(); 1930 1931 // In case of shift value and shift amount may have different VT. For instance 1932 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have 1933 // swapped operands and value types do not match. NB: x86 is fine if operands 1934 // are not swapped with shift amount VT being not bigger than shifted value. 1935 // TODO: that is possible to check for a shift operation, correct VTs and 1936 // still perform optimization on x86 if needed. 1937 if (SelOpNo && VT != CBO.getValueType()) 1938 return SDValue(); 1939 1940 // We have a select-of-constants followed by a binary operator with a 1941 // constant. Eliminate the binop by pulling the constant math into the select. 1942 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 1943 SDLoc DL(Sel); 1944 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 1945 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 1946 if (!CanFoldNonConst && !NewCT.isUndef() && 1947 !isConstantOrConstantVector(NewCT, true) && 1948 !isConstantFPBuildVectorOrConstantFP(NewCT)) 1949 return SDValue(); 1950 1951 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 1952 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 1953 if (!CanFoldNonConst && !NewCF.isUndef() && 1954 !isConstantOrConstantVector(NewCF, true) && 1955 !isConstantFPBuildVectorOrConstantFP(NewCF)) 1956 return SDValue(); 1957 1958 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1959 } 1960 1961 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 1962 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 1963 "Expecting add or sub"); 1964 1965 // Match a constant operand and a zext operand for the math instruction: 1966 // add Z, C 1967 // sub C, Z 1968 bool IsAdd = N->getOpcode() == ISD::ADD; 1969 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 1970 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 1971 auto *CN = dyn_cast<ConstantSDNode>(C); 1972 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 1973 return SDValue(); 1974 1975 // Match the zext operand as a setcc of a boolean. 1976 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 1977 Z.getOperand(0).getValueType() != MVT::i1) 1978 return SDValue(); 1979 1980 // Match the compare as: setcc (X & 1), 0, eq. 1981 SDValue SetCC = Z.getOperand(0); 1982 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 1983 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 1984 SetCC.getOperand(0).getOpcode() != ISD::AND || 1985 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 1986 return SDValue(); 1987 1988 // We are adding/subtracting a constant and an inverted low bit. Turn that 1989 // into a subtract/add of the low bit with incremented/decremented constant: 1990 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 1991 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 1992 EVT VT = C.getValueType(); 1993 SDLoc DL(N); 1994 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 1995 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 1996 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 1997 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 1998 } 1999 2000 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 2001 /// a shift and add with a different constant. 2002 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 2003 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2004 "Expecting add or sub"); 2005 2006 // We need a constant operand for the add/sub, and the other operand is a 2007 // logical shift right: add (srl), C or sub C, (srl). 2008 bool IsAdd = N->getOpcode() == ISD::ADD; 2009 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2010 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2011 ConstantSDNode *C = isConstOrConstSplat(ConstantOp); 2012 if (!C || ShiftOp.getOpcode() != ISD::SRL) 2013 return SDValue(); 2014 2015 // The shift must be of a 'not' value. 2016 SDValue Not = ShiftOp.getOperand(0); 2017 if (!Not.hasOneUse() || !isBitwiseNot(Not)) 2018 return SDValue(); 2019 2020 // The shift must be moving the sign bit to the least-significant-bit. 2021 EVT VT = ShiftOp.getValueType(); 2022 SDValue ShAmt = ShiftOp.getOperand(1); 2023 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2024 if (!ShAmtC || ShAmtC->getZExtValue() != VT.getScalarSizeInBits() - 1) 2025 return SDValue(); 2026 2027 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2028 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2029 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2030 SDLoc DL(N); 2031 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2032 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2033 APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1; 2034 return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT)); 2035 } 2036 2037 SDValue DAGCombiner::visitADD(SDNode *N) { 2038 SDValue N0 = N->getOperand(0); 2039 SDValue N1 = N->getOperand(1); 2040 EVT VT = N0.getValueType(); 2041 SDLoc DL(N); 2042 2043 // fold vector ops 2044 if (VT.isVector()) { 2045 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2046 return FoldedVOp; 2047 2048 // fold (add x, 0) -> x, vector edition 2049 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2050 return N0; 2051 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2052 return N1; 2053 } 2054 2055 // fold (add x, undef) -> undef 2056 if (N0.isUndef()) 2057 return N0; 2058 2059 if (N1.isUndef()) 2060 return N1; 2061 2062 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2063 // canonicalize constant to RHS 2064 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2065 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2066 // fold (add c1, c2) -> c1+c2 2067 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 2068 N1.getNode()); 2069 } 2070 2071 // fold (add x, 0) -> x 2072 if (isNullConstant(N1)) 2073 return N0; 2074 2075 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2076 // fold ((c1-A)+c2) -> (c1+c2)-A 2077 if (N0.getOpcode() == ISD::SUB && 2078 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2079 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 2080 return DAG.getNode(ISD::SUB, DL, VT, 2081 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 2082 N0.getOperand(1)); 2083 } 2084 2085 // add (sext i1 X), 1 -> zext (not i1 X) 2086 // We don't transform this pattern: 2087 // add (zext i1 X), -1 -> sext (not i1 X) 2088 // because most (?) targets generate better code for the zext form. 2089 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2090 isOneConstantOrOneSplatConstant(N1)) { 2091 SDValue X = N0.getOperand(0); 2092 if ((!LegalOperations || 2093 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2094 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2095 X.getScalarValueSizeInBits() == 1) { 2096 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2097 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2098 } 2099 } 2100 2101 // Undo the add -> or combine to merge constant offsets from a frame index. 2102 if (N0.getOpcode() == ISD::OR && 2103 isa<FrameIndexSDNode>(N0.getOperand(0)) && 2104 isa<ConstantSDNode>(N0.getOperand(1)) && 2105 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2106 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 2107 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2108 } 2109 } 2110 2111 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2112 return NewSel; 2113 2114 // reassociate add 2115 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) 2116 return RADD; 2117 2118 // fold ((0-A) + B) -> B-A 2119 if (N0.getOpcode() == ISD::SUB && 2120 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2121 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2122 2123 // fold (A + (0-B)) -> A-B 2124 if (N1.getOpcode() == ISD::SUB && 2125 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2126 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2127 2128 // fold (A+(B-A)) -> B 2129 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2130 return N1.getOperand(0); 2131 2132 // fold ((B-A)+A) -> B 2133 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2134 return N0.getOperand(0); 2135 2136 // fold (A+(B-(A+C))) to (B-C) 2137 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2138 N0 == N1.getOperand(1).getOperand(0)) 2139 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2140 N1.getOperand(1).getOperand(1)); 2141 2142 // fold (A+(B-(C+A))) to (B-C) 2143 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2144 N0 == N1.getOperand(1).getOperand(1)) 2145 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2146 N1.getOperand(1).getOperand(0)); 2147 2148 // fold (A+((B-A)+or-C)) to (B+or-C) 2149 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2150 N1.getOperand(0).getOpcode() == ISD::SUB && 2151 N0 == N1.getOperand(0).getOperand(1)) 2152 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2153 N1.getOperand(1)); 2154 2155 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2156 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2157 SDValue N00 = N0.getOperand(0); 2158 SDValue N01 = N0.getOperand(1); 2159 SDValue N10 = N1.getOperand(0); 2160 SDValue N11 = N1.getOperand(1); 2161 2162 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2163 return DAG.getNode(ISD::SUB, DL, VT, 2164 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2165 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2166 } 2167 2168 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2169 return V; 2170 2171 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2172 return V; 2173 2174 if (SimplifyDemandedBits(SDValue(N, 0))) 2175 return SDValue(N, 0); 2176 2177 // fold (a+b) -> (a|b) iff a and b share no bits. 2178 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2179 DAG.haveNoCommonBitsSet(N0, N1)) 2180 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2181 2182 // fold (add (xor a, -1), 1) -> (sub 0, a) 2183 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) 2184 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2185 N0.getOperand(0)); 2186 2187 if (SDValue Combined = visitADDLike(N0, N1, N)) 2188 return Combined; 2189 2190 if (SDValue Combined = visitADDLike(N1, N0, N)) 2191 return Combined; 2192 2193 return SDValue(); 2194 } 2195 2196 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2197 bool Masked = false; 2198 2199 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2200 while (true) { 2201 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2202 V = V.getOperand(0); 2203 continue; 2204 } 2205 2206 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2207 Masked = true; 2208 V = V.getOperand(0); 2209 continue; 2210 } 2211 2212 break; 2213 } 2214 2215 // If this is not a carry, return. 2216 if (V.getResNo() != 1) 2217 return SDValue(); 2218 2219 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2220 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2221 return SDValue(); 2222 2223 // If the result is masked, then no matter what kind of bool it is we can 2224 // return. If it isn't, then we need to make sure the bool type is either 0 or 2225 // 1 and not other values. 2226 if (Masked || 2227 TLI.getBooleanContents(V.getValueType()) == 2228 TargetLoweringBase::ZeroOrOneBooleanContent) 2229 return V; 2230 2231 return SDValue(); 2232 } 2233 2234 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2235 EVT VT = N0.getValueType(); 2236 SDLoc DL(LocReference); 2237 2238 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2239 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2240 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2241 return DAG.getNode(ISD::SUB, DL, VT, N0, 2242 DAG.getNode(ISD::SHL, DL, VT, 2243 N1.getOperand(0).getOperand(1), 2244 N1.getOperand(1))); 2245 2246 if (N1.getOpcode() == ISD::AND) { 2247 SDValue AndOp0 = N1.getOperand(0); 2248 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2249 unsigned DestBits = VT.getScalarSizeInBits(); 2250 2251 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2252 // and similar xforms where the inner op is either ~0 or 0. 2253 if (NumSignBits == DestBits && 2254 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2255 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2256 } 2257 2258 // add (sext i1), X -> sub X, (zext i1) 2259 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2260 N0.getOperand(0).getValueType() == MVT::i1 && 2261 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2262 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2263 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2264 } 2265 2266 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2267 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2268 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2269 if (TN->getVT() == MVT::i1) { 2270 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2271 DAG.getConstant(1, DL, VT)); 2272 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2273 } 2274 } 2275 2276 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2277 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2278 N1.getResNo() == 0) 2279 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2280 N0, N1.getOperand(0), N1.getOperand(2)); 2281 2282 // (add X, Carry) -> (addcarry X, 0, Carry) 2283 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2284 if (SDValue Carry = getAsCarry(TLI, N1)) 2285 return DAG.getNode(ISD::ADDCARRY, DL, 2286 DAG.getVTList(VT, Carry.getValueType()), N0, 2287 DAG.getConstant(0, DL, VT), Carry); 2288 2289 return SDValue(); 2290 } 2291 2292 SDValue DAGCombiner::visitADDC(SDNode *N) { 2293 SDValue N0 = N->getOperand(0); 2294 SDValue N1 = N->getOperand(1); 2295 EVT VT = N0.getValueType(); 2296 SDLoc DL(N); 2297 2298 // If the flag result is dead, turn this into an ADD. 2299 if (!N->hasAnyUseOfValue(1)) 2300 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2301 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2302 2303 // canonicalize constant to RHS. 2304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2306 if (N0C && !N1C) 2307 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2308 2309 // fold (addc x, 0) -> x + no carry out 2310 if (isNullConstant(N1)) 2311 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2312 DL, MVT::Glue)); 2313 2314 // If it cannot overflow, transform into an add. 2315 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2316 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2317 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2318 2319 return SDValue(); 2320 } 2321 2322 static SDValue flipBoolean(SDValue V, const SDLoc &DL, EVT VT, 2323 SelectionDAG &DAG, const TargetLowering &TLI) { 2324 SDValue Cst; 2325 switch (TLI.getBooleanContents(VT)) { 2326 case TargetLowering::ZeroOrOneBooleanContent: 2327 case TargetLowering::UndefinedBooleanContent: 2328 Cst = DAG.getConstant(1, DL, VT); 2329 break; 2330 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2331 Cst = DAG.getConstant(-1, DL, VT); 2332 break; 2333 } 2334 2335 return DAG.getNode(ISD::XOR, DL, VT, V, Cst); 2336 } 2337 2338 static bool isBooleanFlip(SDValue V, EVT VT, const TargetLowering &TLI) { 2339 if (V.getOpcode() != ISD::XOR) return false; 2340 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V.getOperand(1)); 2341 if (!Const) return false; 2342 2343 switch(TLI.getBooleanContents(VT)) { 2344 case TargetLowering::ZeroOrOneBooleanContent: 2345 return Const->isOne(); 2346 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2347 return Const->isAllOnesValue(); 2348 case TargetLowering::UndefinedBooleanContent: 2349 return (Const->getAPIntValue() & 0x01) == 1; 2350 } 2351 llvm_unreachable("Unsupported boolean content"); 2352 } 2353 2354 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2355 SDValue N0 = N->getOperand(0); 2356 SDValue N1 = N->getOperand(1); 2357 EVT VT = N0.getValueType(); 2358 if (VT.isVector()) 2359 return SDValue(); 2360 2361 EVT CarryVT = N->getValueType(1); 2362 SDLoc DL(N); 2363 2364 // If the flag result is dead, turn this into an ADD. 2365 if (!N->hasAnyUseOfValue(1)) 2366 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2367 DAG.getUNDEF(CarryVT)); 2368 2369 // canonicalize constant to RHS. 2370 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2371 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2372 if (N0C && !N1C) 2373 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2374 2375 // fold (uaddo x, 0) -> x + no carry out 2376 if (isNullConstant(N1)) 2377 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2378 2379 // If it cannot overflow, transform into an add. 2380 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2381 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2382 DAG.getConstant(0, DL, CarryVT)); 2383 2384 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2385 if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) { 2386 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2387 DAG.getConstant(0, DL, VT), 2388 N0.getOperand(0)); 2389 return CombineTo(N, Sub, 2390 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2391 } 2392 2393 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2394 return Combined; 2395 2396 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2397 return Combined; 2398 2399 return SDValue(); 2400 } 2401 2402 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2403 auto VT = N0.getValueType(); 2404 2405 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2406 // If Y + 1 cannot overflow. 2407 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2408 SDValue Y = N1.getOperand(0); 2409 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2410 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2411 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2412 N1.getOperand(2)); 2413 } 2414 2415 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2416 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2417 if (SDValue Carry = getAsCarry(TLI, N1)) 2418 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2419 DAG.getConstant(0, SDLoc(N), VT), Carry); 2420 2421 return SDValue(); 2422 } 2423 2424 SDValue DAGCombiner::visitADDE(SDNode *N) { 2425 SDValue N0 = N->getOperand(0); 2426 SDValue N1 = N->getOperand(1); 2427 SDValue CarryIn = N->getOperand(2); 2428 2429 // canonicalize constant to RHS 2430 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2431 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2432 if (N0C && !N1C) 2433 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2434 N1, N0, CarryIn); 2435 2436 // fold (adde x, y, false) -> (addc x, y) 2437 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2438 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2439 2440 return SDValue(); 2441 } 2442 2443 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2444 SDValue N0 = N->getOperand(0); 2445 SDValue N1 = N->getOperand(1); 2446 SDValue CarryIn = N->getOperand(2); 2447 SDLoc DL(N); 2448 2449 // canonicalize constant to RHS 2450 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2451 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2452 if (N0C && !N1C) 2453 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2454 2455 // fold (addcarry x, y, false) -> (uaddo x, y) 2456 if (isNullConstant(CarryIn)) { 2457 if (!LegalOperations || 2458 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2459 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2460 } 2461 2462 EVT CarryVT = CarryIn.getValueType(); 2463 2464 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2465 if (isNullConstant(N0) && isNullConstant(N1)) { 2466 EVT VT = N0.getValueType(); 2467 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2468 AddToWorklist(CarryExt.getNode()); 2469 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2470 DAG.getConstant(1, DL, VT)), 2471 DAG.getConstant(0, DL, CarryVT)); 2472 } 2473 2474 // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry. 2475 if (isBitwiseNot(N0) && isNullConstant(N1) && 2476 isBooleanFlip(CarryIn, CarryVT, TLI)) { 2477 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), 2478 DAG.getConstant(0, DL, N0.getValueType()), 2479 N0.getOperand(0), CarryIn.getOperand(0)); 2480 return CombineTo(N, Sub, 2481 flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI)); 2482 } 2483 2484 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2485 return Combined; 2486 2487 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2488 return Combined; 2489 2490 return SDValue(); 2491 } 2492 2493 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2494 SDNode *N) { 2495 // Iff the flag result is dead: 2496 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2497 if ((N0.getOpcode() == ISD::ADD || 2498 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2499 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2500 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2501 N0.getOperand(0), N0.getOperand(1), CarryIn); 2502 2503 /** 2504 * When one of the addcarry argument is itself a carry, we may be facing 2505 * a diamond carry propagation. In which case we try to transform the DAG 2506 * to ensure linear carry propagation if that is possible. 2507 * 2508 * We are trying to get: 2509 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2510 */ 2511 if (auto Y = getAsCarry(TLI, N1)) { 2512 /** 2513 * (uaddo A, B) 2514 * / \ 2515 * Carry Sum 2516 * | \ 2517 * | (addcarry *, 0, Z) 2518 * | / 2519 * \ Carry 2520 * | / 2521 * (addcarry X, *, *) 2522 */ 2523 if (Y.getOpcode() == ISD::UADDO && 2524 CarryIn.getResNo() == 1 && 2525 CarryIn.getOpcode() == ISD::ADDCARRY && 2526 isNullConstant(CarryIn.getOperand(1)) && 2527 CarryIn.getOperand(0) == Y.getValue(0)) { 2528 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2529 Y.getOperand(0), Y.getOperand(1), 2530 CarryIn.getOperand(2)); 2531 AddToWorklist(NewY.getNode()); 2532 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2533 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2534 NewY.getValue(1)); 2535 } 2536 } 2537 2538 return SDValue(); 2539 } 2540 2541 // Since it may not be valid to emit a fold to zero for vector initializers 2542 // check if we can before folding. 2543 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2544 SelectionDAG &DAG, bool LegalOperations, 2545 bool LegalTypes) { 2546 if (!VT.isVector()) 2547 return DAG.getConstant(0, DL, VT); 2548 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2549 return DAG.getConstant(0, DL, VT); 2550 return SDValue(); 2551 } 2552 2553 SDValue DAGCombiner::visitSUB(SDNode *N) { 2554 SDValue N0 = N->getOperand(0); 2555 SDValue N1 = N->getOperand(1); 2556 EVT VT = N0.getValueType(); 2557 SDLoc DL(N); 2558 2559 // fold vector ops 2560 if (VT.isVector()) { 2561 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2562 return FoldedVOp; 2563 2564 // fold (sub x, 0) -> x, vector edition 2565 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2566 return N0; 2567 } 2568 2569 // fold (sub x, x) -> 0 2570 // FIXME: Refactor this and xor and other similar operations together. 2571 if (N0 == N1) 2572 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2573 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2574 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2575 // fold (sub c1, c2) -> c1-c2 2576 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2577 N1.getNode()); 2578 } 2579 2580 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2581 return NewSel; 2582 2583 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2584 2585 // fold (sub x, c) -> (add x, -c) 2586 if (N1C) { 2587 return DAG.getNode(ISD::ADD, DL, VT, N0, 2588 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2589 } 2590 2591 if (isNullConstantOrNullSplatConstant(N0)) { 2592 unsigned BitWidth = VT.getScalarSizeInBits(); 2593 // Right-shifting everything out but the sign bit followed by negation is 2594 // the same as flipping arithmetic/logical shift type without the negation: 2595 // -(X >>u 31) -> (X >>s 31) 2596 // -(X >>s 31) -> (X >>u 31) 2597 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2598 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2599 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2600 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2601 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2602 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2603 } 2604 } 2605 2606 // 0 - X --> 0 if the sub is NUW. 2607 if (N->getFlags().hasNoUnsignedWrap()) 2608 return N0; 2609 2610 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2611 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2612 // N1 must be 0 because negating the minimum signed value is undefined. 2613 if (N->getFlags().hasNoSignedWrap()) 2614 return N0; 2615 2616 // 0 - X --> X if X is 0 or the minimum signed value. 2617 return N1; 2618 } 2619 } 2620 2621 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2622 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2623 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2624 2625 // fold (A - (0-B)) -> A+B 2626 if (N1.getOpcode() == ISD::SUB && 2627 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2628 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 2629 2630 // fold A-(A-B) -> B 2631 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2632 return N1.getOperand(1); 2633 2634 // fold (A+B)-A -> B 2635 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2636 return N0.getOperand(1); 2637 2638 // fold (A+B)-B -> A 2639 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2640 return N0.getOperand(0); 2641 2642 // fold C2-(A+C1) -> (C2-C1)-A 2643 if (N1.getOpcode() == ISD::ADD) { 2644 SDValue N11 = N1.getOperand(1); 2645 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2646 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2647 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2648 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2649 } 2650 } 2651 2652 // fold ((A+(B+or-C))-B) -> A+or-C 2653 if (N0.getOpcode() == ISD::ADD && 2654 (N0.getOperand(1).getOpcode() == ISD::SUB || 2655 N0.getOperand(1).getOpcode() == ISD::ADD) && 2656 N0.getOperand(1).getOperand(0) == N1) 2657 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2658 N0.getOperand(1).getOperand(1)); 2659 2660 // fold ((A+(C+B))-B) -> A+C 2661 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2662 N0.getOperand(1).getOperand(1) == N1) 2663 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2664 N0.getOperand(1).getOperand(0)); 2665 2666 // fold ((A-(B-C))-C) -> A-B 2667 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2668 N0.getOperand(1).getOperand(1) == N1) 2669 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2670 N0.getOperand(1).getOperand(0)); 2671 2672 // fold (A-(B-C)) -> A+(C-B) 2673 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 2674 return DAG.getNode(ISD::ADD, DL, VT, N0, 2675 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 2676 N1.getOperand(0))); 2677 2678 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 2679 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 2680 if (N1.getOperand(0).getOpcode() == ISD::SUB && 2681 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) { 2682 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2683 N1.getOperand(0).getOperand(1), 2684 N1.getOperand(1)); 2685 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2686 } 2687 if (N1.getOperand(1).getOpcode() == ISD::SUB && 2688 isNullConstantOrNullSplatConstant(N1.getOperand(1).getOperand(0))) { 2689 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2690 N1.getOperand(0), 2691 N1.getOperand(1).getOperand(1)); 2692 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2693 } 2694 } 2695 2696 // If either operand of a sub is undef, the result is undef 2697 if (N0.isUndef()) 2698 return N0; 2699 if (N1.isUndef()) 2700 return N1; 2701 2702 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2703 return V; 2704 2705 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2706 return V; 2707 2708 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 2709 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 2710 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 2711 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 2712 SDValue S0 = N1.getOperand(0); 2713 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) { 2714 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 2715 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 2716 if (C->getAPIntValue() == (OpSizeInBits - 1)) 2717 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 2718 } 2719 } 2720 } 2721 2722 // If the relocation model supports it, consider symbol offsets. 2723 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2724 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2725 // fold (sub Sym, c) -> Sym-c 2726 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2727 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2728 GA->getOffset() - 2729 (uint64_t)N1C->getSExtValue()); 2730 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2731 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2732 if (GA->getGlobal() == GB->getGlobal()) 2733 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2734 DL, VT); 2735 } 2736 2737 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2738 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2739 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2740 if (TN->getVT() == MVT::i1) { 2741 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2742 DAG.getConstant(1, DL, VT)); 2743 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2744 } 2745 } 2746 2747 // Prefer an add for more folding potential and possibly better codegen: 2748 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 2749 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 2750 SDValue ShAmt = N1.getOperand(1); 2751 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2752 if (ShAmtC && ShAmtC->getZExtValue() == N1.getScalarValueSizeInBits() - 1) { 2753 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 2754 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 2755 } 2756 } 2757 2758 return SDValue(); 2759 } 2760 2761 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2762 SDValue N0 = N->getOperand(0); 2763 SDValue N1 = N->getOperand(1); 2764 EVT VT = N0.getValueType(); 2765 SDLoc DL(N); 2766 2767 // If the flag result is dead, turn this into an SUB. 2768 if (!N->hasAnyUseOfValue(1)) 2769 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2770 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2771 2772 // fold (subc x, x) -> 0 + no borrow 2773 if (N0 == N1) 2774 return CombineTo(N, DAG.getConstant(0, DL, VT), 2775 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2776 2777 // fold (subc x, 0) -> x + no borrow 2778 if (isNullConstant(N1)) 2779 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2780 2781 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2782 if (isAllOnesConstant(N0)) 2783 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2784 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2785 2786 return SDValue(); 2787 } 2788 2789 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2790 SDValue N0 = N->getOperand(0); 2791 SDValue N1 = N->getOperand(1); 2792 EVT VT = N0.getValueType(); 2793 if (VT.isVector()) 2794 return SDValue(); 2795 2796 EVT CarryVT = N->getValueType(1); 2797 SDLoc DL(N); 2798 2799 // If the flag result is dead, turn this into an SUB. 2800 if (!N->hasAnyUseOfValue(1)) 2801 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2802 DAG.getUNDEF(CarryVT)); 2803 2804 // fold (usubo x, x) -> 0 + no borrow 2805 if (N0 == N1) 2806 return CombineTo(N, DAG.getConstant(0, DL, VT), 2807 DAG.getConstant(0, DL, CarryVT)); 2808 2809 // fold (usubo x, 0) -> x + no borrow 2810 if (isNullConstant(N1)) 2811 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2812 2813 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2814 if (isAllOnesConstant(N0)) 2815 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2816 DAG.getConstant(0, DL, CarryVT)); 2817 2818 return SDValue(); 2819 } 2820 2821 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2822 SDValue N0 = N->getOperand(0); 2823 SDValue N1 = N->getOperand(1); 2824 SDValue CarryIn = N->getOperand(2); 2825 2826 // fold (sube x, y, false) -> (subc x, y) 2827 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2828 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2829 2830 return SDValue(); 2831 } 2832 2833 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2834 SDValue N0 = N->getOperand(0); 2835 SDValue N1 = N->getOperand(1); 2836 SDValue CarryIn = N->getOperand(2); 2837 2838 // fold (subcarry x, y, false) -> (usubo x, y) 2839 if (isNullConstant(CarryIn)) { 2840 if (!LegalOperations || 2841 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 2842 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2843 } 2844 2845 return SDValue(); 2846 } 2847 2848 SDValue DAGCombiner::visitMUL(SDNode *N) { 2849 SDValue N0 = N->getOperand(0); 2850 SDValue N1 = N->getOperand(1); 2851 EVT VT = N0.getValueType(); 2852 2853 // fold (mul x, undef) -> 0 2854 if (N0.isUndef() || N1.isUndef()) 2855 return DAG.getConstant(0, SDLoc(N), VT); 2856 2857 bool N0IsConst = false; 2858 bool N1IsConst = false; 2859 bool N1IsOpaqueConst = false; 2860 bool N0IsOpaqueConst = false; 2861 APInt ConstValue0, ConstValue1; 2862 // fold vector ops 2863 if (VT.isVector()) { 2864 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2865 return FoldedVOp; 2866 2867 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2868 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2869 assert((!N0IsConst || 2870 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2871 "Splat APInt should be element width"); 2872 assert((!N1IsConst || 2873 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2874 "Splat APInt should be element width"); 2875 } else { 2876 N0IsConst = isa<ConstantSDNode>(N0); 2877 if (N0IsConst) { 2878 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2879 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2880 } 2881 N1IsConst = isa<ConstantSDNode>(N1); 2882 if (N1IsConst) { 2883 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2884 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2885 } 2886 } 2887 2888 // fold (mul c1, c2) -> c1*c2 2889 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2890 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2891 N0.getNode(), N1.getNode()); 2892 2893 // canonicalize constant to RHS (vector doesn't have to splat) 2894 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2895 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2896 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2897 // fold (mul x, 0) -> 0 2898 if (N1IsConst && ConstValue1.isNullValue()) 2899 return N1; 2900 // fold (mul x, 1) -> x 2901 if (N1IsConst && ConstValue1.isOneValue()) 2902 return N0; 2903 2904 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2905 return NewSel; 2906 2907 // fold (mul x, -1) -> 0-x 2908 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2909 SDLoc DL(N); 2910 return DAG.getNode(ISD::SUB, DL, VT, 2911 DAG.getConstant(0, DL, VT), N0); 2912 } 2913 // fold (mul x, (1 << c)) -> x << c 2914 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2915 DAG.isKnownToBeAPowerOfTwo(N1) && 2916 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 2917 SDLoc DL(N); 2918 SDValue LogBase2 = BuildLogBase2(N1, DL); 2919 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2920 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2921 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2922 } 2923 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2924 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2925 unsigned Log2Val = (-ConstValue1).logBase2(); 2926 SDLoc DL(N); 2927 // FIXME: If the input is something that is easily negated (e.g. a 2928 // single-use add), we should put the negate there. 2929 return DAG.getNode(ISD::SUB, DL, VT, 2930 DAG.getConstant(0, DL, VT), 2931 DAG.getNode(ISD::SHL, DL, VT, N0, 2932 DAG.getConstant(Log2Val, DL, 2933 getShiftAmountTy(N0.getValueType())))); 2934 } 2935 2936 // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub. 2937 // mul x, (2^N + 1) --> add (shl x, N), x 2938 // mul x, (2^N - 1) --> sub (shl x, N), x 2939 // Examples: x * 33 --> (x << 5) + x 2940 // x * 15 --> (x << 4) - x 2941 // x * -33 --> -((x << 5) + x) 2942 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4) 2943 if (N1IsConst && TLI.decomposeMulByConstant(VT, N1)) { 2944 // TODO: We could handle more general decomposition of any constant by 2945 // having the target set a limit on number of ops and making a 2946 // callback to determine that sequence (similar to sqrt expansion). 2947 unsigned MathOp = ISD::DELETED_NODE; 2948 APInt MulC = ConstValue1.abs(); 2949 if ((MulC - 1).isPowerOf2()) 2950 MathOp = ISD::ADD; 2951 else if ((MulC + 1).isPowerOf2()) 2952 MathOp = ISD::SUB; 2953 2954 if (MathOp != ISD::DELETED_NODE) { 2955 unsigned ShAmt = MathOp == ISD::ADD ? (MulC - 1).logBase2() 2956 : (MulC + 1).logBase2(); 2957 assert(ShAmt > 0 && ShAmt < VT.getScalarSizeInBits() && 2958 "Not expecting multiply-by-constant that could have simplified"); 2959 SDLoc DL(N); 2960 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, N0, 2961 DAG.getConstant(ShAmt, DL, VT)); 2962 SDValue R = DAG.getNode(MathOp, DL, VT, Shl, N0); 2963 if (ConstValue1.isNegative()) 2964 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R); 2965 return R; 2966 } 2967 } 2968 2969 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2970 if (N0.getOpcode() == ISD::SHL && 2971 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2972 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2973 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2974 if (isConstantOrConstantVector(C3)) 2975 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2976 } 2977 2978 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2979 // use. 2980 { 2981 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2982 2983 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2984 if (N0.getOpcode() == ISD::SHL && 2985 isConstantOrConstantVector(N0.getOperand(1)) && 2986 N0.getNode()->hasOneUse()) { 2987 Sh = N0; Y = N1; 2988 } else if (N1.getOpcode() == ISD::SHL && 2989 isConstantOrConstantVector(N1.getOperand(1)) && 2990 N1.getNode()->hasOneUse()) { 2991 Sh = N1; Y = N0; 2992 } 2993 2994 if (Sh.getNode()) { 2995 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2996 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2997 } 2998 } 2999 3000 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 3001 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 3002 N0.getOpcode() == ISD::ADD && 3003 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 3004 isMulAddWithConstProfitable(N, N0, N1)) 3005 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 3006 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 3007 N0.getOperand(0), N1), 3008 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 3009 N0.getOperand(1), N1)); 3010 3011 // reassociate mul 3012 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) 3013 return RMUL; 3014 3015 return SDValue(); 3016 } 3017 3018 /// Return true if divmod libcall is available. 3019 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 3020 const TargetLowering &TLI) { 3021 RTLIB::Libcall LC; 3022 EVT NodeType = Node->getValueType(0); 3023 if (!NodeType.isSimple()) 3024 return false; 3025 switch (NodeType.getSimpleVT().SimpleTy) { 3026 default: return false; // No libcall for vector types. 3027 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 3028 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 3029 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 3030 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 3031 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 3032 } 3033 3034 return TLI.getLibcallName(LC) != nullptr; 3035 } 3036 3037 /// Issue divrem if both quotient and remainder are needed. 3038 SDValue DAGCombiner::useDivRem(SDNode *Node) { 3039 if (Node->use_empty()) 3040 return SDValue(); // This is a dead node, leave it alone. 3041 3042 unsigned Opcode = Node->getOpcode(); 3043 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 3044 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3045 3046 // DivMod lib calls can still work on non-legal types if using lib-calls. 3047 EVT VT = Node->getValueType(0); 3048 if (VT.isVector() || !VT.isInteger()) 3049 return SDValue(); 3050 3051 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 3052 return SDValue(); 3053 3054 // If DIVREM is going to get expanded into a libcall, 3055 // but there is no libcall available, then don't combine. 3056 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 3057 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 3058 return SDValue(); 3059 3060 // If div is legal, it's better to do the normal expansion 3061 unsigned OtherOpcode = 0; 3062 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 3063 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 3064 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 3065 return SDValue(); 3066 } else { 3067 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3068 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 3069 return SDValue(); 3070 } 3071 3072 SDValue Op0 = Node->getOperand(0); 3073 SDValue Op1 = Node->getOperand(1); 3074 SDValue combined; 3075 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 3076 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 3077 SDNode *User = *UI; 3078 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 3079 User->use_empty()) 3080 continue; 3081 // Convert the other matching node(s), too; 3082 // otherwise, the DIVREM may get target-legalized into something 3083 // target-specific that we won't be able to recognize. 3084 unsigned UserOpc = User->getOpcode(); 3085 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 3086 User->getOperand(0) == Op0 && 3087 User->getOperand(1) == Op1) { 3088 if (!combined) { 3089 if (UserOpc == OtherOpcode) { 3090 SDVTList VTs = DAG.getVTList(VT, VT); 3091 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 3092 } else if (UserOpc == DivRemOpc) { 3093 combined = SDValue(User, 0); 3094 } else { 3095 assert(UserOpc == Opcode); 3096 continue; 3097 } 3098 } 3099 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 3100 CombineTo(User, combined); 3101 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 3102 CombineTo(User, combined.getValue(1)); 3103 } 3104 } 3105 return combined; 3106 } 3107 3108 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 3109 SDValue N0 = N->getOperand(0); 3110 SDValue N1 = N->getOperand(1); 3111 EVT VT = N->getValueType(0); 3112 SDLoc DL(N); 3113 3114 unsigned Opc = N->getOpcode(); 3115 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); 3116 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3117 3118 // X / undef -> undef 3119 // X % undef -> undef 3120 // X / 0 -> undef 3121 // X % 0 -> undef 3122 // NOTE: This includes vectors where any divisor element is zero/undef. 3123 if (DAG.isUndef(Opc, {N0, N1})) 3124 return DAG.getUNDEF(VT); 3125 3126 // undef / X -> 0 3127 // undef % X -> 0 3128 if (N0.isUndef()) 3129 return DAG.getConstant(0, DL, VT); 3130 3131 // TODO: 0 / X -> 0 3132 // TODO: 0 % X -> 0 3133 3134 // X / X -> 1 3135 // X % X -> 0 3136 if (N0 == N1) 3137 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); 3138 3139 // X / 1 -> X 3140 // X % 1 -> 0 3141 // If this is a boolean op (single-bit element type), we can't have 3142 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 3143 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume 3144 // it's a 1. 3145 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1)) 3146 return IsDiv ? N0 : DAG.getConstant(0, DL, VT); 3147 3148 return SDValue(); 3149 } 3150 3151 SDValue DAGCombiner::visitSDIV(SDNode *N) { 3152 SDValue N0 = N->getOperand(0); 3153 SDValue N1 = N->getOperand(1); 3154 EVT VT = N->getValueType(0); 3155 EVT CCVT = getSetCCResultType(VT); 3156 3157 // fold vector ops 3158 if (VT.isVector()) 3159 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3160 return FoldedVOp; 3161 3162 SDLoc DL(N); 3163 3164 // fold (sdiv c1, c2) -> c1/c2 3165 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3166 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3167 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 3168 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 3169 // fold (sdiv X, -1) -> 0-X 3170 if (N1C && N1C->isAllOnesValue()) 3171 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 3172 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 3173 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 3174 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3175 DAG.getConstant(1, DL, VT), 3176 DAG.getConstant(0, DL, VT)); 3177 3178 if (SDValue V = simplifyDivRem(N, DAG)) 3179 return V; 3180 3181 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3182 return NewSel; 3183 3184 // If we know the sign bits of both operands are zero, strength reduce to a 3185 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 3186 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3187 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 3188 3189 if (SDValue V = visitSDIVLike(N0, N1, N)) 3190 return V; 3191 3192 // sdiv, srem -> sdivrem 3193 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3194 // true. Otherwise, we break the simplification logic in visitREM(). 3195 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3196 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3197 if (SDValue DivRem = useDivRem(N)) 3198 return DivRem; 3199 3200 return SDValue(); 3201 } 3202 3203 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3204 SDLoc DL(N); 3205 EVT VT = N->getValueType(0); 3206 EVT CCVT = getSetCCResultType(VT); 3207 unsigned BitWidth = VT.getScalarSizeInBits(); 3208 3209 // Helper for determining whether a value is a power-2 constant scalar or a 3210 // vector of such elements. 3211 auto IsPowerOfTwo = [](ConstantSDNode *C) { 3212 if (C->isNullValue() || C->isOpaque()) 3213 return false; 3214 if (C->getAPIntValue().isPowerOf2()) 3215 return true; 3216 if ((-C->getAPIntValue()).isPowerOf2()) 3217 return true; 3218 return false; 3219 }; 3220 3221 // fold (sdiv X, pow2) -> simple ops after legalize 3222 // FIXME: We check for the exact bit here because the generic lowering gives 3223 // better results in that case. The target-specific lowering should learn how 3224 // to handle exact sdivs efficiently. 3225 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { 3226 // Target-specific implementation of sdiv x, pow2. 3227 if (SDValue Res = BuildSDIVPow2(N)) 3228 return Res; 3229 3230 // Create constants that are functions of the shift amount value. 3231 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 3232 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 3233 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 3234 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 3235 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 3236 if (!isConstantOrConstantVector(Inexact)) 3237 return SDValue(); 3238 3239 // Splat the sign bit into the register 3240 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 3241 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 3242 AddToWorklist(Sign.getNode()); 3243 3244 // Add (N0 < 0) ? abs2 - 1 : 0; 3245 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 3246 AddToWorklist(Srl.getNode()); 3247 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 3248 AddToWorklist(Add.getNode()); 3249 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 3250 AddToWorklist(Sra.getNode()); 3251 3252 // Special case: (sdiv X, 1) -> X 3253 // Special Case: (sdiv X, -1) -> 0-X 3254 SDValue One = DAG.getConstant(1, DL, VT); 3255 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 3256 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 3257 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 3258 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 3259 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 3260 3261 // If dividing by a positive value, we're done. Otherwise, the result must 3262 // be negated. 3263 SDValue Zero = DAG.getConstant(0, DL, VT); 3264 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 3265 3266 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 3267 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 3268 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 3269 return Res; 3270 } 3271 3272 // If integer divide is expensive and we satisfy the requirements, emit an 3273 // alternate sequence. Targets may check function attributes for size/speed 3274 // trade-offs. 3275 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3276 if (isConstantOrConstantVector(N1) && 3277 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3278 if (SDValue Op = BuildSDIV(N)) 3279 return Op; 3280 3281 return SDValue(); 3282 } 3283 3284 SDValue DAGCombiner::visitUDIV(SDNode *N) { 3285 SDValue N0 = N->getOperand(0); 3286 SDValue N1 = N->getOperand(1); 3287 EVT VT = N->getValueType(0); 3288 EVT CCVT = getSetCCResultType(VT); 3289 3290 // fold vector ops 3291 if (VT.isVector()) 3292 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3293 return FoldedVOp; 3294 3295 SDLoc DL(N); 3296 3297 // fold (udiv c1, c2) -> c1/c2 3298 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3299 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3300 if (N0C && N1C) 3301 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 3302 N0C, N1C)) 3303 return Folded; 3304 // fold (udiv X, -1) -> select(X == -1, 1, 0) 3305 if (N1C && N1C->getAPIntValue().isAllOnesValue()) 3306 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3307 DAG.getConstant(1, DL, VT), 3308 DAG.getConstant(0, DL, VT)); 3309 3310 if (SDValue V = simplifyDivRem(N, DAG)) 3311 return V; 3312 3313 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3314 return NewSel; 3315 3316 if (SDValue V = visitUDIVLike(N0, N1, N)) 3317 return V; 3318 3319 // sdiv, srem -> sdivrem 3320 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3321 // true. Otherwise, we break the simplification logic in visitREM(). 3322 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3323 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3324 if (SDValue DivRem = useDivRem(N)) 3325 return DivRem; 3326 3327 return SDValue(); 3328 } 3329 3330 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3331 SDLoc DL(N); 3332 EVT VT = N->getValueType(0); 3333 3334 // fold (udiv x, (1 << c)) -> x >>u c 3335 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3336 DAG.isKnownToBeAPowerOfTwo(N1)) { 3337 SDValue LogBase2 = BuildLogBase2(N1, DL); 3338 AddToWorklist(LogBase2.getNode()); 3339 3340 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3341 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3342 AddToWorklist(Trunc.getNode()); 3343 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3344 } 3345 3346 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 3347 if (N1.getOpcode() == ISD::SHL) { 3348 SDValue N10 = N1.getOperand(0); 3349 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 3350 DAG.isKnownToBeAPowerOfTwo(N10)) { 3351 SDValue LogBase2 = BuildLogBase2(N10, DL); 3352 AddToWorklist(LogBase2.getNode()); 3353 3354 EVT ADDVT = N1.getOperand(1).getValueType(); 3355 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 3356 AddToWorklist(Trunc.getNode()); 3357 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 3358 AddToWorklist(Add.getNode()); 3359 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 3360 } 3361 } 3362 3363 // fold (udiv x, c) -> alternate 3364 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3365 if (isConstantOrConstantVector(N1) && 3366 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3367 if (SDValue Op = BuildUDIV(N)) 3368 return Op; 3369 3370 return SDValue(); 3371 } 3372 3373 // handles ISD::SREM and ISD::UREM 3374 SDValue DAGCombiner::visitREM(SDNode *N) { 3375 unsigned Opcode = N->getOpcode(); 3376 SDValue N0 = N->getOperand(0); 3377 SDValue N1 = N->getOperand(1); 3378 EVT VT = N->getValueType(0); 3379 EVT CCVT = getSetCCResultType(VT); 3380 3381 bool isSigned = (Opcode == ISD::SREM); 3382 SDLoc DL(N); 3383 3384 // fold (rem c1, c2) -> c1%c2 3385 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3386 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3387 if (N0C && N1C) 3388 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3389 return Folded; 3390 // fold (urem X, -1) -> select(X == -1, 0, x) 3391 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) 3392 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3393 DAG.getConstant(0, DL, VT), N0); 3394 3395 if (SDValue V = simplifyDivRem(N, DAG)) 3396 return V; 3397 3398 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3399 return NewSel; 3400 3401 if (isSigned) { 3402 // If we know the sign bits of both operands are zero, strength reduce to a 3403 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3404 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3405 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3406 } else { 3407 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3408 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3409 // fold (urem x, pow2) -> (and x, pow2-1) 3410 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3411 AddToWorklist(Add.getNode()); 3412 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3413 } 3414 if (N1.getOpcode() == ISD::SHL && 3415 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3416 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3417 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3418 AddToWorklist(Add.getNode()); 3419 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3420 } 3421 } 3422 3423 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3424 3425 // If X/C can be simplified by the division-by-constant logic, lower 3426 // X%C to the equivalent of X-X/C*C. 3427 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 3428 // speculative DIV must not cause a DIVREM conversion. We guard against this 3429 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 3430 // combine will not return a DIVREM. Regardless, checking cheapness here 3431 // makes sense since the simplification results in fatter code. 3432 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 3433 SDValue OptimizedDiv = 3434 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 3435 if (OptimizedDiv.getNode()) { 3436 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3437 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3438 AddToWorklist(OptimizedDiv.getNode()); 3439 AddToWorklist(Mul.getNode()); 3440 return Sub; 3441 } 3442 } 3443 3444 // sdiv, srem -> sdivrem 3445 if (SDValue DivRem = useDivRem(N)) 3446 return DivRem.getValue(1); 3447 3448 return SDValue(); 3449 } 3450 3451 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3452 SDValue N0 = N->getOperand(0); 3453 SDValue N1 = N->getOperand(1); 3454 EVT VT = N->getValueType(0); 3455 SDLoc DL(N); 3456 3457 if (VT.isVector()) { 3458 // fold (mulhs x, 0) -> 0 3459 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3460 return N1; 3461 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3462 return N0; 3463 } 3464 3465 // fold (mulhs x, 0) -> 0 3466 if (isNullConstant(N1)) 3467 return N1; 3468 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3469 if (isOneConstant(N1)) 3470 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3471 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3472 getShiftAmountTy(N0.getValueType()))); 3473 3474 // fold (mulhs x, undef) -> 0 3475 if (N0.isUndef() || N1.isUndef()) 3476 return DAG.getConstant(0, DL, VT); 3477 3478 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3479 // plus a shift. 3480 if (VT.isSimple() && !VT.isVector()) { 3481 MVT Simple = VT.getSimpleVT(); 3482 unsigned SimpleSize = Simple.getSizeInBits(); 3483 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3484 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3485 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3486 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3487 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3488 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3489 DAG.getConstant(SimpleSize, DL, 3490 getShiftAmountTy(N1.getValueType()))); 3491 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3492 } 3493 } 3494 3495 return SDValue(); 3496 } 3497 3498 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3499 SDValue N0 = N->getOperand(0); 3500 SDValue N1 = N->getOperand(1); 3501 EVT VT = N->getValueType(0); 3502 SDLoc DL(N); 3503 3504 if (VT.isVector()) { 3505 // fold (mulhu x, 0) -> 0 3506 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3507 return N1; 3508 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3509 return N0; 3510 } 3511 3512 // fold (mulhu x, 0) -> 0 3513 if (isNullConstant(N1)) 3514 return N1; 3515 // fold (mulhu x, 1) -> 0 3516 if (isOneConstant(N1)) 3517 return DAG.getConstant(0, DL, N0.getValueType()); 3518 // fold (mulhu x, undef) -> 0 3519 if (N0.isUndef() || N1.isUndef()) 3520 return DAG.getConstant(0, DL, VT); 3521 3522 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) 3523 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3524 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { 3525 SDLoc DL(N); 3526 unsigned NumEltBits = VT.getScalarSizeInBits(); 3527 SDValue LogBase2 = BuildLogBase2(N1, DL); 3528 SDValue SRLAmt = DAG.getNode( 3529 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); 3530 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3531 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); 3532 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3533 } 3534 3535 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3536 // plus a shift. 3537 if (VT.isSimple() && !VT.isVector()) { 3538 MVT Simple = VT.getSimpleVT(); 3539 unsigned SimpleSize = Simple.getSizeInBits(); 3540 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3541 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3542 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3543 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3544 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3545 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3546 DAG.getConstant(SimpleSize, DL, 3547 getShiftAmountTy(N1.getValueType()))); 3548 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3549 } 3550 } 3551 3552 return SDValue(); 3553 } 3554 3555 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3556 /// give the opcodes for the two computations that are being performed. Return 3557 /// true if a simplification was made. 3558 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3559 unsigned HiOp) { 3560 // If the high half is not needed, just compute the low half. 3561 bool HiExists = N->hasAnyUseOfValue(1); 3562 if (!HiExists && 3563 (!LegalOperations || 3564 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3565 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3566 return CombineTo(N, Res, Res); 3567 } 3568 3569 // If the low half is not needed, just compute the high half. 3570 bool LoExists = N->hasAnyUseOfValue(0); 3571 if (!LoExists && 3572 (!LegalOperations || 3573 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3574 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3575 return CombineTo(N, Res, Res); 3576 } 3577 3578 // If both halves are used, return as it is. 3579 if (LoExists && HiExists) 3580 return SDValue(); 3581 3582 // If the two computed results can be simplified separately, separate them. 3583 if (LoExists) { 3584 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3585 AddToWorklist(Lo.getNode()); 3586 SDValue LoOpt = combine(Lo.getNode()); 3587 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3588 (!LegalOperations || 3589 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3590 return CombineTo(N, LoOpt, LoOpt); 3591 } 3592 3593 if (HiExists) { 3594 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3595 AddToWorklist(Hi.getNode()); 3596 SDValue HiOpt = combine(Hi.getNode()); 3597 if (HiOpt.getNode() && HiOpt != Hi && 3598 (!LegalOperations || 3599 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3600 return CombineTo(N, HiOpt, HiOpt); 3601 } 3602 3603 return SDValue(); 3604 } 3605 3606 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3607 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3608 return Res; 3609 3610 EVT VT = N->getValueType(0); 3611 SDLoc DL(N); 3612 3613 // If the type is twice as wide is legal, transform the mulhu to a wider 3614 // multiply plus a shift. 3615 if (VT.isSimple() && !VT.isVector()) { 3616 MVT Simple = VT.getSimpleVT(); 3617 unsigned SimpleSize = Simple.getSizeInBits(); 3618 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3619 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3620 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3621 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3622 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3623 // Compute the high part as N1. 3624 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3625 DAG.getConstant(SimpleSize, DL, 3626 getShiftAmountTy(Lo.getValueType()))); 3627 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3628 // Compute the low part as N0. 3629 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3630 return CombineTo(N, Lo, Hi); 3631 } 3632 } 3633 3634 return SDValue(); 3635 } 3636 3637 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3638 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3639 return Res; 3640 3641 EVT VT = N->getValueType(0); 3642 SDLoc DL(N); 3643 3644 // If the type is twice as wide is legal, transform the mulhu to a wider 3645 // multiply plus a shift. 3646 if (VT.isSimple() && !VT.isVector()) { 3647 MVT Simple = VT.getSimpleVT(); 3648 unsigned SimpleSize = Simple.getSizeInBits(); 3649 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3650 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3651 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3652 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3653 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3654 // Compute the high part as N1. 3655 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3656 DAG.getConstant(SimpleSize, DL, 3657 getShiftAmountTy(Lo.getValueType()))); 3658 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3659 // Compute the low part as N0. 3660 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3661 return CombineTo(N, Lo, Hi); 3662 } 3663 } 3664 3665 return SDValue(); 3666 } 3667 3668 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3669 // (smulo x, 2) -> (saddo x, x) 3670 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3671 if (C2->getAPIntValue() == 2) 3672 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3673 N->getOperand(0), N->getOperand(0)); 3674 3675 return SDValue(); 3676 } 3677 3678 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3679 // (umulo x, 2) -> (uaddo x, x) 3680 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3681 if (C2->getAPIntValue() == 2) 3682 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3683 N->getOperand(0), N->getOperand(0)); 3684 3685 return SDValue(); 3686 } 3687 3688 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3689 SDValue N0 = N->getOperand(0); 3690 SDValue N1 = N->getOperand(1); 3691 EVT VT = N0.getValueType(); 3692 3693 // fold vector ops 3694 if (VT.isVector()) 3695 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3696 return FoldedVOp; 3697 3698 // fold operation with constant operands. 3699 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3700 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3701 if (N0C && N1C) 3702 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3703 3704 // canonicalize constant to RHS 3705 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3706 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3707 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3708 3709 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 3710 // Only do this if the current op isn't legal and the flipped is. 3711 unsigned Opcode = N->getOpcode(); 3712 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3713 if (!TLI.isOperationLegal(Opcode, VT) && 3714 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 3715 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 3716 unsigned AltOpcode; 3717 switch (Opcode) { 3718 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 3719 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 3720 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 3721 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 3722 default: llvm_unreachable("Unknown MINMAX opcode"); 3723 } 3724 if (TLI.isOperationLegal(AltOpcode, VT)) 3725 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 3726 } 3727 3728 return SDValue(); 3729 } 3730 3731 /// If this is a binary operator with two operands of the same opcode, try to 3732 /// simplify it. 3733 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3734 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3735 EVT VT = N0.getValueType(); 3736 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3737 3738 // Bail early if none of these transforms apply. 3739 if (N0.getNumOperands() == 0) return SDValue(); 3740 3741 // For each of OP in AND/OR/XOR: 3742 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3743 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3744 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3745 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3746 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3747 // 3748 // do not sink logical op inside of a vector extend, since it may combine 3749 // into a vsetcc. 3750 EVT Op0VT = N0.getOperand(0).getValueType(); 3751 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3752 N0.getOpcode() == ISD::SIGN_EXTEND || 3753 N0.getOpcode() == ISD::BSWAP || 3754 // Avoid infinite looping with PromoteIntBinOp. 3755 (N0.getOpcode() == ISD::ANY_EXTEND && 3756 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3757 (N0.getOpcode() == ISD::TRUNCATE && 3758 (!TLI.isZExtFree(VT, Op0VT) || 3759 !TLI.isTruncateFree(Op0VT, VT)) && 3760 TLI.isTypeLegal(Op0VT))) && 3761 !VT.isVector() && 3762 Op0VT == N1.getOperand(0).getValueType() && 3763 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3764 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3765 N0.getOperand(0).getValueType(), 3766 N0.getOperand(0), N1.getOperand(0)); 3767 AddToWorklist(ORNode.getNode()); 3768 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3769 } 3770 3771 // For each of OP in SHL/SRL/SRA/AND... 3772 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3773 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3774 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3775 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3776 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3777 N0.getOperand(1) == N1.getOperand(1)) { 3778 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3779 N0.getOperand(0).getValueType(), 3780 N0.getOperand(0), N1.getOperand(0)); 3781 AddToWorklist(ORNode.getNode()); 3782 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3783 ORNode, N0.getOperand(1)); 3784 } 3785 3786 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3787 // Only perform this optimization up until type legalization, before 3788 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3789 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3790 // we don't want to undo this promotion. 3791 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3792 // on scalars. 3793 if ((N0.getOpcode() == ISD::BITCAST || 3794 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3795 Level <= AfterLegalizeTypes) { 3796 SDValue In0 = N0.getOperand(0); 3797 SDValue In1 = N1.getOperand(0); 3798 EVT In0Ty = In0.getValueType(); 3799 EVT In1Ty = In1.getValueType(); 3800 SDLoc DL(N); 3801 // If both incoming values are integers, and the original types are the 3802 // same. 3803 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3804 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3805 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3806 AddToWorklist(Op.getNode()); 3807 return BC; 3808 } 3809 } 3810 3811 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3812 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3813 // If both shuffles use the same mask, and both shuffle within a single 3814 // vector, then it is worthwhile to move the swizzle after the operation. 3815 // The type-legalizer generates this pattern when loading illegal 3816 // vector types from memory. In many cases this allows additional shuffle 3817 // optimizations. 3818 // There are other cases where moving the shuffle after the xor/and/or 3819 // is profitable even if shuffles don't perform a swizzle. 3820 // If both shuffles use the same mask, and both shuffles have the same first 3821 // or second operand, then it might still be profitable to move the shuffle 3822 // after the xor/and/or operation. 3823 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3824 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3825 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3826 3827 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3828 "Inputs to shuffles are not the same type"); 3829 3830 // Check that both shuffles use the same mask. The masks are known to be of 3831 // the same length because the result vector type is the same. 3832 // Check also that shuffles have only one use to avoid introducing extra 3833 // instructions. 3834 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3835 SVN0->getMask().equals(SVN1->getMask())) { 3836 SDValue ShOp = N0->getOperand(1); 3837 3838 // Don't try to fold this node if it requires introducing a 3839 // build vector of all zeros that might be illegal at this stage. 3840 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3841 if (!LegalTypes) 3842 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3843 else 3844 ShOp = SDValue(); 3845 } 3846 3847 // (AND (shuf (A, C), shuf (B, C))) -> shuf (AND (A, B), C) 3848 // (OR (shuf (A, C), shuf (B, C))) -> shuf (OR (A, B), C) 3849 // (XOR (shuf (A, C), shuf (B, C))) -> shuf (XOR (A, B), V_0) 3850 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3851 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3852 N0->getOperand(0), N1->getOperand(0)); 3853 AddToWorklist(NewNode.getNode()); 3854 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3855 SVN0->getMask()); 3856 } 3857 3858 // Don't try to fold this node if it requires introducing a 3859 // build vector of all zeros that might be illegal at this stage. 3860 ShOp = N0->getOperand(0); 3861 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3862 if (!LegalTypes) 3863 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3864 else 3865 ShOp = SDValue(); 3866 } 3867 3868 // (AND (shuf (C, A), shuf (C, B))) -> shuf (C, AND (A, B)) 3869 // (OR (shuf (C, A), shuf (C, B))) -> shuf (C, OR (A, B)) 3870 // (XOR (shuf (C, A), shuf (C, B))) -> shuf (V_0, XOR (A, B)) 3871 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3872 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3873 N0->getOperand(1), N1->getOperand(1)); 3874 AddToWorklist(NewNode.getNode()); 3875 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3876 SVN0->getMask()); 3877 } 3878 } 3879 } 3880 3881 return SDValue(); 3882 } 3883 3884 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3885 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3886 const SDLoc &DL) { 3887 SDValue LL, LR, RL, RR, N0CC, N1CC; 3888 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3889 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3890 return SDValue(); 3891 3892 assert(N0.getValueType() == N1.getValueType() && 3893 "Unexpected operand types for bitwise logic op"); 3894 assert(LL.getValueType() == LR.getValueType() && 3895 RL.getValueType() == RR.getValueType() && 3896 "Unexpected operand types for setcc"); 3897 3898 // If we're here post-legalization or the logic op type is not i1, the logic 3899 // op type must match a setcc result type. Also, all folds require new 3900 // operations on the left and right operands, so those types must match. 3901 EVT VT = N0.getValueType(); 3902 EVT OpVT = LL.getValueType(); 3903 if (LegalOperations || VT.getScalarType() != MVT::i1) 3904 if (VT != getSetCCResultType(OpVT)) 3905 return SDValue(); 3906 if (OpVT != RL.getValueType()) 3907 return SDValue(); 3908 3909 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3910 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3911 bool IsInteger = OpVT.isInteger(); 3912 if (LR == RR && CC0 == CC1 && IsInteger) { 3913 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3914 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3915 3916 // All bits clear? 3917 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3918 // All sign bits clear? 3919 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3920 // Any bits set? 3921 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3922 // Any sign bits set? 3923 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3924 3925 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3926 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3927 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3928 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3929 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3930 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3931 AddToWorklist(Or.getNode()); 3932 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3933 } 3934 3935 // All bits set? 3936 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3937 // All sign bits set? 3938 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3939 // Any bits clear? 3940 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3941 // Any sign bits clear? 3942 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3943 3944 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3945 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3946 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3947 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3948 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3949 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3950 AddToWorklist(And.getNode()); 3951 return DAG.getSetCC(DL, VT, And, LR, CC1); 3952 } 3953 } 3954 3955 // TODO: What is the 'or' equivalent of this fold? 3956 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3957 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 3958 IsInteger && CC0 == ISD::SETNE && 3959 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3960 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3961 SDValue One = DAG.getConstant(1, DL, OpVT); 3962 SDValue Two = DAG.getConstant(2, DL, OpVT); 3963 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3964 AddToWorklist(Add.getNode()); 3965 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3966 } 3967 3968 // Try more general transforms if the predicates match and the only user of 3969 // the compares is the 'and' or 'or'. 3970 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3971 N0.hasOneUse() && N1.hasOneUse()) { 3972 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3973 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3974 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3975 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3976 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3977 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3978 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3979 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3980 } 3981 } 3982 3983 // Canonicalize equivalent operands to LL == RL. 3984 if (LL == RR && LR == RL) { 3985 CC1 = ISD::getSetCCSwappedOperands(CC1); 3986 std::swap(RL, RR); 3987 } 3988 3989 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3990 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3991 if (LL == RL && LR == RR) { 3992 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3993 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3994 if (NewCC != ISD::SETCC_INVALID && 3995 (!LegalOperations || 3996 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3997 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3998 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3999 } 4000 4001 return SDValue(); 4002 } 4003 4004 /// This contains all DAGCombine rules which reduce two values combined by 4005 /// an And operation to a single value. This makes them reusable in the context 4006 /// of visitSELECT(). Rules involving constants are not included as 4007 /// visitSELECT() already handles those cases. 4008 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 4009 EVT VT = N1.getValueType(); 4010 SDLoc DL(N); 4011 4012 // fold (and x, undef) -> 0 4013 if (N0.isUndef() || N1.isUndef()) 4014 return DAG.getConstant(0, DL, VT); 4015 4016 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 4017 return V; 4018 4019 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 4020 VT.getSizeInBits() <= 64) { 4021 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4022 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 4023 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 4024 // immediate for an add, but it is legal if its top c2 bits are set, 4025 // transform the ADD so the immediate doesn't need to be materialized 4026 // in a register. 4027 APInt ADDC = ADDI->getAPIntValue(); 4028 APInt SRLC = SRLI->getAPIntValue(); 4029 if (ADDC.getMinSignedBits() <= 64 && 4030 SRLC.ult(VT.getSizeInBits()) && 4031 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 4032 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 4033 SRLC.getZExtValue()); 4034 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 4035 ADDC |= Mask; 4036 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 4037 SDLoc DL0(N0); 4038 SDValue NewAdd = 4039 DAG.getNode(ISD::ADD, DL0, VT, 4040 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 4041 CombineTo(N0.getNode(), NewAdd); 4042 // Return N so it doesn't get rechecked! 4043 return SDValue(N, 0); 4044 } 4045 } 4046 } 4047 } 4048 } 4049 } 4050 4051 // Reduce bit extract of low half of an integer to the narrower type. 4052 // (and (srl i64:x, K), KMask) -> 4053 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 4054 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4055 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 4056 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4057 unsigned Size = VT.getSizeInBits(); 4058 const APInt &AndMask = CAnd->getAPIntValue(); 4059 unsigned ShiftBits = CShift->getZExtValue(); 4060 4061 // Bail out, this node will probably disappear anyway. 4062 if (ShiftBits == 0) 4063 return SDValue(); 4064 4065 unsigned MaskBits = AndMask.countTrailingOnes(); 4066 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 4067 4068 if (AndMask.isMask() && 4069 // Required bits must not span the two halves of the integer and 4070 // must fit in the half size type. 4071 (ShiftBits + MaskBits <= Size / 2) && 4072 TLI.isNarrowingProfitable(VT, HalfVT) && 4073 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 4074 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 4075 TLI.isTruncateFree(VT, HalfVT) && 4076 TLI.isZExtFree(HalfVT, VT)) { 4077 // The isNarrowingProfitable is to avoid regressions on PPC and 4078 // AArch64 which match a few 64-bit bit insert / bit extract patterns 4079 // on downstream users of this. Those patterns could probably be 4080 // extended to handle extensions mixed in. 4081 4082 SDValue SL(N0); 4083 assert(MaskBits <= Size); 4084 4085 // Extracting the highest bit of the low half. 4086 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 4087 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 4088 N0.getOperand(0)); 4089 4090 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 4091 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 4092 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 4093 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 4094 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 4095 } 4096 } 4097 } 4098 } 4099 4100 return SDValue(); 4101 } 4102 4103 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 4104 EVT LoadResultTy, EVT &ExtVT) { 4105 if (!AndC->getAPIntValue().isMask()) 4106 return false; 4107 4108 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 4109 4110 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4111 EVT LoadedVT = LoadN->getMemoryVT(); 4112 4113 if (ExtVT == LoadedVT && 4114 (!LegalOperations || 4115 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 4116 // ZEXTLOAD will match without needing to change the size of the value being 4117 // loaded. 4118 return true; 4119 } 4120 4121 // Do not change the width of a volatile load. 4122 if (LoadN->isVolatile()) 4123 return false; 4124 4125 // Do not generate loads of non-round integer types since these can 4126 // be expensive (and would be wrong if the type is not byte sized). 4127 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 4128 return false; 4129 4130 if (LegalOperations && 4131 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 4132 return false; 4133 4134 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 4135 return false; 4136 4137 return true; 4138 } 4139 4140 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 4141 ISD::LoadExtType ExtType, EVT &MemVT, 4142 unsigned ShAmt) { 4143 if (!LDST) 4144 return false; 4145 // Only allow byte offsets. 4146 if (ShAmt % 8) 4147 return false; 4148 4149 // Do not generate loads of non-round integer types since these can 4150 // be expensive (and would be wrong if the type is not byte sized). 4151 if (!MemVT.isRound()) 4152 return false; 4153 4154 // Don't change the width of a volatile load. 4155 if (LDST->isVolatile()) 4156 return false; 4157 4158 // Verify that we are actually reducing a load width here. 4159 if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits()) 4160 return false; 4161 4162 // Ensure that this isn't going to produce an unsupported unaligned access. 4163 if (ShAmt && 4164 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4165 LDST->getAddressSpace(), ShAmt / 8)) 4166 return false; 4167 4168 // It's not possible to generate a constant of extended or untyped type. 4169 EVT PtrType = LDST->getBasePtr().getValueType(); 4170 if (PtrType == MVT::Untyped || PtrType.isExtended()) 4171 return false; 4172 4173 if (isa<LoadSDNode>(LDST)) { 4174 LoadSDNode *Load = cast<LoadSDNode>(LDST); 4175 // Don't transform one with multiple uses, this would require adding a new 4176 // load. 4177 if (!SDValue(Load, 0).hasOneUse()) 4178 return false; 4179 4180 if (LegalOperations && 4181 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 4182 return false; 4183 4184 // For the transform to be legal, the load must produce only two values 4185 // (the value loaded and the chain). Don't transform a pre-increment 4186 // load, for example, which produces an extra value. Otherwise the 4187 // transformation is not equivalent, and the downstream logic to replace 4188 // uses gets things wrong. 4189 if (Load->getNumValues() > 2) 4190 return false; 4191 4192 // If the load that we're shrinking is an extload and we're not just 4193 // discarding the extension we can't simply shrink the load. Bail. 4194 // TODO: It would be possible to merge the extensions in some cases. 4195 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 4196 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4197 return false; 4198 4199 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 4200 return false; 4201 } else { 4202 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 4203 StoreSDNode *Store = cast<StoreSDNode>(LDST); 4204 // Can't write outside the original store 4205 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4206 return false; 4207 4208 if (LegalOperations && 4209 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 4210 return false; 4211 } 4212 return true; 4213 } 4214 4215 bool DAGCombiner::SearchForAndLoads(SDNode *N, 4216 SmallPtrSetImpl<LoadSDNode*> &Loads, 4217 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 4218 ConstantSDNode *Mask, 4219 SDNode *&NodeToMask) { 4220 // Recursively search for the operands, looking for loads which can be 4221 // narrowed. 4222 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 4223 SDValue Op = N->getOperand(i); 4224 4225 if (Op.getValueType().isVector()) 4226 return false; 4227 4228 // Some constants may need fixing up later if they are too large. 4229 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4230 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 4231 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 4232 NodesWithConsts.insert(N); 4233 continue; 4234 } 4235 4236 if (!Op.hasOneUse()) 4237 return false; 4238 4239 switch(Op.getOpcode()) { 4240 case ISD::LOAD: { 4241 auto *Load = cast<LoadSDNode>(Op); 4242 EVT ExtVT; 4243 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 4244 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 4245 4246 // ZEXTLOAD is already small enough. 4247 if (Load->getExtensionType() == ISD::ZEXTLOAD && 4248 ExtVT.bitsGE(Load->getMemoryVT())) 4249 continue; 4250 4251 // Use LE to convert equal sized loads to zext. 4252 if (ExtVT.bitsLE(Load->getMemoryVT())) 4253 Loads.insert(Load); 4254 4255 continue; 4256 } 4257 return false; 4258 } 4259 case ISD::ZERO_EXTEND: 4260 case ISD::AssertZext: { 4261 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 4262 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4263 EVT VT = Op.getOpcode() == ISD::AssertZext ? 4264 cast<VTSDNode>(Op.getOperand(1))->getVT() : 4265 Op.getOperand(0).getValueType(); 4266 4267 // We can accept extending nodes if the mask is wider or an equal 4268 // width to the original type. 4269 if (ExtVT.bitsGE(VT)) 4270 continue; 4271 break; 4272 } 4273 case ISD::OR: 4274 case ISD::XOR: 4275 case ISD::AND: 4276 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 4277 NodeToMask)) 4278 return false; 4279 continue; 4280 } 4281 4282 // Allow one node which will masked along with any loads found. 4283 if (NodeToMask) 4284 return false; 4285 4286 // Also ensure that the node to be masked only produces one data result. 4287 NodeToMask = Op.getNode(); 4288 if (NodeToMask->getNumValues() > 1) { 4289 bool HasValue = false; 4290 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 4291 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 4292 if (VT != MVT::Glue && VT != MVT::Other) { 4293 if (HasValue) { 4294 NodeToMask = nullptr; 4295 return false; 4296 } 4297 HasValue = true; 4298 } 4299 } 4300 assert(HasValue && "Node to be masked has no data result?"); 4301 } 4302 } 4303 return true; 4304 } 4305 4306 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 4307 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4308 if (!Mask) 4309 return false; 4310 4311 if (!Mask->getAPIntValue().isMask()) 4312 return false; 4313 4314 // No need to do anything if the and directly uses a load. 4315 if (isa<LoadSDNode>(N->getOperand(0))) 4316 return false; 4317 4318 SmallPtrSet<LoadSDNode*, 8> Loads; 4319 SmallPtrSet<SDNode*, 2> NodesWithConsts; 4320 SDNode *FixupNode = nullptr; 4321 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 4322 if (Loads.size() == 0) 4323 return false; 4324 4325 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 4326 SDValue MaskOp = N->getOperand(1); 4327 4328 // If it exists, fixup the single node we allow in the tree that needs 4329 // masking. 4330 if (FixupNode) { 4331 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 4332 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 4333 FixupNode->getValueType(0), 4334 SDValue(FixupNode, 0), MaskOp); 4335 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 4336 if (And.getOpcode() == ISD ::AND) 4337 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 4338 } 4339 4340 // Narrow any constants that need it. 4341 for (auto *LogicN : NodesWithConsts) { 4342 SDValue Op0 = LogicN->getOperand(0); 4343 SDValue Op1 = LogicN->getOperand(1); 4344 4345 if (isa<ConstantSDNode>(Op0)) 4346 std::swap(Op0, Op1); 4347 4348 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 4349 Op1, MaskOp); 4350 4351 DAG.UpdateNodeOperands(LogicN, Op0, And); 4352 } 4353 4354 // Create narrow loads. 4355 for (auto *Load : Loads) { 4356 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 4357 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 4358 SDValue(Load, 0), MaskOp); 4359 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 4360 if (And.getOpcode() == ISD ::AND) 4361 And = SDValue( 4362 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 4363 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 4364 assert(NewLoad && 4365 "Shouldn't be masking the load if it can't be narrowed"); 4366 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 4367 } 4368 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 4369 return true; 4370 } 4371 return false; 4372 } 4373 4374 // Unfold 4375 // x & (-1 'logical shift' y) 4376 // To 4377 // (x 'opposite logical shift' y) 'logical shift' y 4378 // if it is better for performance. 4379 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 4380 assert(N->getOpcode() == ISD::AND); 4381 4382 SDValue N0 = N->getOperand(0); 4383 SDValue N1 = N->getOperand(1); 4384 4385 // Do we actually prefer shifts over mask? 4386 if (!TLI.preferShiftsToClearExtremeBits(N0)) 4387 return SDValue(); 4388 4389 // Try to match (-1 '[outer] logical shift' y) 4390 unsigned OuterShift; 4391 unsigned InnerShift; // The opposite direction to the OuterShift. 4392 SDValue Y; // Shift amount. 4393 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 4394 if (!M.hasOneUse()) 4395 return false; 4396 OuterShift = M->getOpcode(); 4397 if (OuterShift == ISD::SHL) 4398 InnerShift = ISD::SRL; 4399 else if (OuterShift == ISD::SRL) 4400 InnerShift = ISD::SHL; 4401 else 4402 return false; 4403 if (!isAllOnesConstant(M->getOperand(0))) 4404 return false; 4405 Y = M->getOperand(1); 4406 return true; 4407 }; 4408 4409 SDValue X; 4410 if (matchMask(N1)) 4411 X = N0; 4412 else if (matchMask(N0)) 4413 X = N1; 4414 else 4415 return SDValue(); 4416 4417 SDLoc DL(N); 4418 EVT VT = N->getValueType(0); 4419 4420 // tmp = x 'opposite logical shift' y 4421 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 4422 // ret = tmp 'logical shift' y 4423 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 4424 4425 return T1; 4426 } 4427 4428 SDValue DAGCombiner::visitAND(SDNode *N) { 4429 SDValue N0 = N->getOperand(0); 4430 SDValue N1 = N->getOperand(1); 4431 EVT VT = N1.getValueType(); 4432 4433 // x & x --> x 4434 if (N0 == N1) 4435 return N0; 4436 4437 // fold vector ops 4438 if (VT.isVector()) { 4439 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4440 return FoldedVOp; 4441 4442 // fold (and x, 0) -> 0, vector edition 4443 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4444 // do not return N0, because undef node may exist in N0 4445 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 4446 SDLoc(N), N0.getValueType()); 4447 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4448 // do not return N1, because undef node may exist in N1 4449 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 4450 SDLoc(N), N1.getValueType()); 4451 4452 // fold (and x, -1) -> x, vector edition 4453 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4454 return N1; 4455 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4456 return N0; 4457 } 4458 4459 // fold (and c1, c2) -> c1&c2 4460 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4461 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4462 if (N0C && N1C && !N1C->isOpaque()) 4463 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 4464 // canonicalize constant to RHS 4465 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4466 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4467 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 4468 // fold (and x, -1) -> x 4469 if (isAllOnesConstant(N1)) 4470 return N0; 4471 // if (and x, c) is known to be zero, return 0 4472 unsigned BitWidth = VT.getScalarSizeInBits(); 4473 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4474 APInt::getAllOnesValue(BitWidth))) 4475 return DAG.getConstant(0, SDLoc(N), VT); 4476 4477 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4478 return NewSel; 4479 4480 // reassociate and 4481 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) 4482 return RAND; 4483 4484 // Try to convert a constant mask AND into a shuffle clear mask. 4485 if (VT.isVector()) 4486 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4487 return Shuffle; 4488 4489 // fold (and (or x, C), D) -> D if (C & D) == D 4490 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4491 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4492 }; 4493 if (N0.getOpcode() == ISD::OR && 4494 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4495 return N1; 4496 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4497 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4498 SDValue N0Op0 = N0.getOperand(0); 4499 APInt Mask = ~N1C->getAPIntValue(); 4500 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4501 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4502 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4503 N0.getValueType(), N0Op0); 4504 4505 // Replace uses of the AND with uses of the Zero extend node. 4506 CombineTo(N, Zext); 4507 4508 // We actually want to replace all uses of the any_extend with the 4509 // zero_extend, to avoid duplicating things. This will later cause this 4510 // AND to be folded. 4511 CombineTo(N0.getNode(), Zext); 4512 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4513 } 4514 } 4515 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4516 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4517 // already be zero by virtue of the width of the base type of the load. 4518 // 4519 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4520 // more cases. 4521 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4522 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4523 N0.getOperand(0).getOpcode() == ISD::LOAD && 4524 N0.getOperand(0).getResNo() == 0) || 4525 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4526 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4527 N0 : N0.getOperand(0) ); 4528 4529 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4530 // This can be a pure constant or a vector splat, in which case we treat the 4531 // vector as a scalar and use the splat value. 4532 APInt Constant = APInt::getNullValue(1); 4533 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4534 Constant = C->getAPIntValue(); 4535 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4536 APInt SplatValue, SplatUndef; 4537 unsigned SplatBitSize; 4538 bool HasAnyUndefs; 4539 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4540 SplatBitSize, HasAnyUndefs); 4541 if (IsSplat) { 4542 // Undef bits can contribute to a possible optimisation if set, so 4543 // set them. 4544 SplatValue |= SplatUndef; 4545 4546 // The splat value may be something like "0x00FFFFFF", which means 0 for 4547 // the first vector value and FF for the rest, repeating. We need a mask 4548 // that will apply equally to all members of the vector, so AND all the 4549 // lanes of the constant together. 4550 EVT VT = Vector->getValueType(0); 4551 unsigned BitWidth = VT.getScalarSizeInBits(); 4552 4553 // If the splat value has been compressed to a bitlength lower 4554 // than the size of the vector lane, we need to re-expand it to 4555 // the lane size. 4556 if (BitWidth > SplatBitSize) 4557 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4558 SplatBitSize < BitWidth; 4559 SplatBitSize = SplatBitSize * 2) 4560 SplatValue |= SplatValue.shl(SplatBitSize); 4561 4562 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4563 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4564 if (SplatBitSize % BitWidth == 0) { 4565 Constant = APInt::getAllOnesValue(BitWidth); 4566 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4567 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4568 } 4569 } 4570 } 4571 4572 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4573 // actually legal and isn't going to get expanded, else this is a false 4574 // optimisation. 4575 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4576 Load->getValueType(0), 4577 Load->getMemoryVT()); 4578 4579 // Resize the constant to the same size as the original memory access before 4580 // extension. If it is still the AllOnesValue then this AND is completely 4581 // unneeded. 4582 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4583 4584 bool B; 4585 switch (Load->getExtensionType()) { 4586 default: B = false; break; 4587 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4588 case ISD::ZEXTLOAD: 4589 case ISD::NON_EXTLOAD: B = true; break; 4590 } 4591 4592 if (B && Constant.isAllOnesValue()) { 4593 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4594 // preserve semantics once we get rid of the AND. 4595 SDValue NewLoad(Load, 0); 4596 4597 // Fold the AND away. NewLoad may get replaced immediately. 4598 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4599 4600 if (Load->getExtensionType() == ISD::EXTLOAD) { 4601 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4602 Load->getValueType(0), SDLoc(Load), 4603 Load->getChain(), Load->getBasePtr(), 4604 Load->getOffset(), Load->getMemoryVT(), 4605 Load->getMemOperand()); 4606 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4607 if (Load->getNumValues() == 3) { 4608 // PRE/POST_INC loads have 3 values. 4609 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4610 NewLoad.getValue(2) }; 4611 CombineTo(Load, To, 3, true); 4612 } else { 4613 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4614 } 4615 } 4616 4617 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4618 } 4619 } 4620 4621 // fold (and (load x), 255) -> (zextload x, i8) 4622 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4623 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4624 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4625 (N0.getOpcode() == ISD::ANY_EXTEND && 4626 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4627 if (SDValue Res = ReduceLoadWidth(N)) { 4628 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4629 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4630 4631 AddToWorklist(N); 4632 CombineTo(LN0, Res, Res.getValue(1)); 4633 return SDValue(N, 0); 4634 } 4635 } 4636 4637 if (Level >= AfterLegalizeTypes) { 4638 // Attempt to propagate the AND back up to the leaves which, if they're 4639 // loads, can be combined to narrow loads and the AND node can be removed. 4640 // Perform after legalization so that extend nodes will already be 4641 // combined into the loads. 4642 if (BackwardsPropagateMask(N, DAG)) { 4643 return SDValue(N, 0); 4644 } 4645 } 4646 4647 if (SDValue Combined = visitANDLike(N0, N1, N)) 4648 return Combined; 4649 4650 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4651 if (N0.getOpcode() == N1.getOpcode()) 4652 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4653 return Tmp; 4654 4655 // Masking the negated extension of a boolean is just the zero-extended 4656 // boolean: 4657 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4658 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4659 // 4660 // Note: the SimplifyDemandedBits fold below can make an information-losing 4661 // transform, and then we have no way to find this better fold. 4662 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4663 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 4664 SDValue SubRHS = N0.getOperand(1); 4665 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4666 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4667 return SubRHS; 4668 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4669 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4670 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4671 } 4672 } 4673 4674 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4675 // fold (and (sra)) -> (and (srl)) when possible. 4676 if (SimplifyDemandedBits(SDValue(N, 0))) 4677 return SDValue(N, 0); 4678 4679 // fold (zext_inreg (extload x)) -> (zextload x) 4680 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 4681 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4682 EVT MemVT = LN0->getMemoryVT(); 4683 // If we zero all the possible extended bits, then we can turn this into 4684 // a zextload if we are running before legalize or the operation is legal. 4685 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4686 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4687 BitWidth - MemVT.getScalarSizeInBits())) && 4688 ((!LegalOperations && !LN0->isVolatile()) || 4689 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4690 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4691 LN0->getChain(), LN0->getBasePtr(), 4692 MemVT, LN0->getMemOperand()); 4693 AddToWorklist(N); 4694 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4695 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4696 } 4697 } 4698 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 4699 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4700 N0.hasOneUse()) { 4701 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4702 EVT MemVT = LN0->getMemoryVT(); 4703 // If we zero all the possible extended bits, then we can turn this into 4704 // a zextload if we are running before legalize or the operation is legal. 4705 unsigned BitWidth = N1.getScalarValueSizeInBits(); 4706 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 4707 BitWidth - MemVT.getScalarSizeInBits())) && 4708 ((!LegalOperations && !LN0->isVolatile()) || 4709 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 4710 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4711 LN0->getChain(), LN0->getBasePtr(), 4712 MemVT, LN0->getMemOperand()); 4713 AddToWorklist(N); 4714 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4715 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4716 } 4717 } 4718 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4719 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4720 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4721 N0.getOperand(1), false)) 4722 return BSwap; 4723 } 4724 4725 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 4726 return Shifts; 4727 4728 return SDValue(); 4729 } 4730 4731 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4732 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4733 bool DemandHighBits) { 4734 if (!LegalOperations) 4735 return SDValue(); 4736 4737 EVT VT = N->getValueType(0); 4738 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4739 return SDValue(); 4740 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4741 return SDValue(); 4742 4743 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4744 bool LookPassAnd0 = false; 4745 bool LookPassAnd1 = false; 4746 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4747 std::swap(N0, N1); 4748 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4749 std::swap(N0, N1); 4750 if (N0.getOpcode() == ISD::AND) { 4751 if (!N0.getNode()->hasOneUse()) 4752 return SDValue(); 4753 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4754 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 4755 // This is needed for X86. 4756 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 4757 N01C->getZExtValue() != 0xFFFF)) 4758 return SDValue(); 4759 N0 = N0.getOperand(0); 4760 LookPassAnd0 = true; 4761 } 4762 4763 if (N1.getOpcode() == ISD::AND) { 4764 if (!N1.getNode()->hasOneUse()) 4765 return SDValue(); 4766 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4767 if (!N11C || N11C->getZExtValue() != 0xFF) 4768 return SDValue(); 4769 N1 = N1.getOperand(0); 4770 LookPassAnd1 = true; 4771 } 4772 4773 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4774 std::swap(N0, N1); 4775 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4776 return SDValue(); 4777 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4778 return SDValue(); 4779 4780 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4781 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4782 if (!N01C || !N11C) 4783 return SDValue(); 4784 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4785 return SDValue(); 4786 4787 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4788 SDValue N00 = N0->getOperand(0); 4789 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4790 if (!N00.getNode()->hasOneUse()) 4791 return SDValue(); 4792 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4793 if (!N001C || N001C->getZExtValue() != 0xFF) 4794 return SDValue(); 4795 N00 = N00.getOperand(0); 4796 LookPassAnd0 = true; 4797 } 4798 4799 SDValue N10 = N1->getOperand(0); 4800 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4801 if (!N10.getNode()->hasOneUse()) 4802 return SDValue(); 4803 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4804 // Also allow 0xFFFF since the bits will be shifted out. This is needed 4805 // for X86. 4806 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 4807 N101C->getZExtValue() != 0xFFFF)) 4808 return SDValue(); 4809 N10 = N10.getOperand(0); 4810 LookPassAnd1 = true; 4811 } 4812 4813 if (N00 != N10) 4814 return SDValue(); 4815 4816 // Make sure everything beyond the low halfword gets set to zero since the SRL 4817 // 16 will clear the top bits. 4818 unsigned OpSizeInBits = VT.getSizeInBits(); 4819 if (DemandHighBits && OpSizeInBits > 16) { 4820 // If the left-shift isn't masked out then the only way this is a bswap is 4821 // if all bits beyond the low 8 are 0. In that case the entire pattern 4822 // reduces to a left shift anyway: leave it for other parts of the combiner. 4823 if (!LookPassAnd0) 4824 return SDValue(); 4825 4826 // However, if the right shift isn't masked out then it might be because 4827 // it's not needed. See if we can spot that too. 4828 if (!LookPassAnd1 && 4829 !DAG.MaskedValueIsZero( 4830 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4831 return SDValue(); 4832 } 4833 4834 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4835 if (OpSizeInBits > 16) { 4836 SDLoc DL(N); 4837 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4838 DAG.getConstant(OpSizeInBits - 16, DL, 4839 getShiftAmountTy(VT))); 4840 } 4841 return Res; 4842 } 4843 4844 /// Return true if the specified node is an element that makes up a 32-bit 4845 /// packed halfword byteswap. 4846 /// ((x & 0x000000ff) << 8) | 4847 /// ((x & 0x0000ff00) >> 8) | 4848 /// ((x & 0x00ff0000) << 8) | 4849 /// ((x & 0xff000000) >> 8) 4850 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4851 if (!N.getNode()->hasOneUse()) 4852 return false; 4853 4854 unsigned Opc = N.getOpcode(); 4855 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4856 return false; 4857 4858 SDValue N0 = N.getOperand(0); 4859 unsigned Opc0 = N0.getOpcode(); 4860 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4861 return false; 4862 4863 ConstantSDNode *N1C = nullptr; 4864 // SHL or SRL: look upstream for AND mask operand 4865 if (Opc == ISD::AND) 4866 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4867 else if (Opc0 == ISD::AND) 4868 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4869 if (!N1C) 4870 return false; 4871 4872 unsigned MaskByteOffset; 4873 switch (N1C->getZExtValue()) { 4874 default: 4875 return false; 4876 case 0xFF: MaskByteOffset = 0; break; 4877 case 0xFF00: MaskByteOffset = 1; break; 4878 case 0xFFFF: 4879 // In case demanded bits didn't clear the bits that will be shifted out. 4880 // This is needed for X86. 4881 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 4882 MaskByteOffset = 1; 4883 break; 4884 } 4885 return false; 4886 case 0xFF0000: MaskByteOffset = 2; break; 4887 case 0xFF000000: MaskByteOffset = 3; break; 4888 } 4889 4890 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4891 if (Opc == ISD::AND) { 4892 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4893 // (x >> 8) & 0xff 4894 // (x >> 8) & 0xff0000 4895 if (Opc0 != ISD::SRL) 4896 return false; 4897 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4898 if (!C || C->getZExtValue() != 8) 4899 return false; 4900 } else { 4901 // (x << 8) & 0xff00 4902 // (x << 8) & 0xff000000 4903 if (Opc0 != ISD::SHL) 4904 return false; 4905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4906 if (!C || C->getZExtValue() != 8) 4907 return false; 4908 } 4909 } else if (Opc == ISD::SHL) { 4910 // (x & 0xff) << 8 4911 // (x & 0xff0000) << 8 4912 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4913 return false; 4914 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4915 if (!C || C->getZExtValue() != 8) 4916 return false; 4917 } else { // Opc == ISD::SRL 4918 // (x & 0xff00) >> 8 4919 // (x & 0xff000000) >> 8 4920 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4921 return false; 4922 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4923 if (!C || C->getZExtValue() != 8) 4924 return false; 4925 } 4926 4927 if (Parts[MaskByteOffset]) 4928 return false; 4929 4930 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4931 return true; 4932 } 4933 4934 /// Match a 32-bit packed halfword bswap. That is 4935 /// ((x & 0x000000ff) << 8) | 4936 /// ((x & 0x0000ff00) >> 8) | 4937 /// ((x & 0x00ff0000) << 8) | 4938 /// ((x & 0xff000000) >> 8) 4939 /// => (rotl (bswap x), 16) 4940 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4941 if (!LegalOperations) 4942 return SDValue(); 4943 4944 EVT VT = N->getValueType(0); 4945 if (VT != MVT::i32) 4946 return SDValue(); 4947 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4948 return SDValue(); 4949 4950 // Look for either 4951 // (or (or (and), (and)), (or (and), (and))) 4952 // (or (or (or (and), (and)), (and)), (and)) 4953 if (N0.getOpcode() != ISD::OR) 4954 return SDValue(); 4955 SDValue N00 = N0.getOperand(0); 4956 SDValue N01 = N0.getOperand(1); 4957 SDNode *Parts[4] = {}; 4958 4959 if (N1.getOpcode() == ISD::OR && 4960 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4961 // (or (or (and), (and)), (or (and), (and))) 4962 if (!isBSwapHWordElement(N00, Parts)) 4963 return SDValue(); 4964 4965 if (!isBSwapHWordElement(N01, Parts)) 4966 return SDValue(); 4967 SDValue N10 = N1.getOperand(0); 4968 if (!isBSwapHWordElement(N10, Parts)) 4969 return SDValue(); 4970 SDValue N11 = N1.getOperand(1); 4971 if (!isBSwapHWordElement(N11, Parts)) 4972 return SDValue(); 4973 } else { 4974 // (or (or (or (and), (and)), (and)), (and)) 4975 if (!isBSwapHWordElement(N1, Parts)) 4976 return SDValue(); 4977 if (!isBSwapHWordElement(N01, Parts)) 4978 return SDValue(); 4979 if (N00.getOpcode() != ISD::OR) 4980 return SDValue(); 4981 SDValue N000 = N00.getOperand(0); 4982 if (!isBSwapHWordElement(N000, Parts)) 4983 return SDValue(); 4984 SDValue N001 = N00.getOperand(1); 4985 if (!isBSwapHWordElement(N001, Parts)) 4986 return SDValue(); 4987 } 4988 4989 // Make sure the parts are all coming from the same node. 4990 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4991 return SDValue(); 4992 4993 SDLoc DL(N); 4994 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4995 SDValue(Parts[0], 0)); 4996 4997 // Result of the bswap should be rotated by 16. If it's not legal, then 4998 // do (x << 16) | (x >> 16). 4999 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 5000 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 5001 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 5002 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 5003 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 5004 return DAG.getNode(ISD::OR, DL, VT, 5005 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 5006 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 5007 } 5008 5009 /// This contains all DAGCombine rules which reduce two values combined by 5010 /// an Or operation to a single value \see visitANDLike(). 5011 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 5012 EVT VT = N1.getValueType(); 5013 SDLoc DL(N); 5014 5015 // fold (or x, undef) -> -1 5016 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 5017 return DAG.getAllOnesConstant(DL, VT); 5018 5019 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 5020 return V; 5021 5022 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 5023 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 5024 // Don't increase # computations. 5025 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 5026 // We can only do this xform if we know that bits from X that are set in C2 5027 // but not in C1 are already zero. Likewise for Y. 5028 if (const ConstantSDNode *N0O1C = 5029 getAsNonOpaqueConstant(N0.getOperand(1))) { 5030 if (const ConstantSDNode *N1O1C = 5031 getAsNonOpaqueConstant(N1.getOperand(1))) { 5032 // We can only do this xform if we know that bits from X that are set in 5033 // C2 but not in C1 are already zero. Likewise for Y. 5034 const APInt &LHSMask = N0O1C->getAPIntValue(); 5035 const APInt &RHSMask = N1O1C->getAPIntValue(); 5036 5037 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 5038 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 5039 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5040 N0.getOperand(0), N1.getOperand(0)); 5041 return DAG.getNode(ISD::AND, DL, VT, X, 5042 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 5043 } 5044 } 5045 } 5046 } 5047 5048 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 5049 if (N0.getOpcode() == ISD::AND && 5050 N1.getOpcode() == ISD::AND && 5051 N0.getOperand(0) == N1.getOperand(0) && 5052 // Don't increase # computations. 5053 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 5054 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5055 N0.getOperand(1), N1.getOperand(1)); 5056 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 5057 } 5058 5059 return SDValue(); 5060 } 5061 5062 SDValue DAGCombiner::visitOR(SDNode *N) { 5063 SDValue N0 = N->getOperand(0); 5064 SDValue N1 = N->getOperand(1); 5065 EVT VT = N1.getValueType(); 5066 5067 // x | x --> x 5068 if (N0 == N1) 5069 return N0; 5070 5071 // fold vector ops 5072 if (VT.isVector()) { 5073 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5074 return FoldedVOp; 5075 5076 // fold (or x, 0) -> x, vector edition 5077 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5078 return N1; 5079 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5080 return N0; 5081 5082 // fold (or x, -1) -> -1, vector edition 5083 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5084 // do not return N0, because undef node may exist in N0 5085 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 5086 if (ISD::isBuildVectorAllOnes(N1.getNode())) 5087 // do not return N1, because undef node may exist in N1 5088 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 5089 5090 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 5091 // Do this only if the resulting shuffle is legal. 5092 if (isa<ShuffleVectorSDNode>(N0) && 5093 isa<ShuffleVectorSDNode>(N1) && 5094 // Avoid folding a node with illegal type. 5095 TLI.isTypeLegal(VT)) { 5096 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 5097 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 5098 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5099 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 5100 // Ensure both shuffles have a zero input. 5101 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 5102 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 5103 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 5104 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 5105 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 5106 bool CanFold = true; 5107 int NumElts = VT.getVectorNumElements(); 5108 SmallVector<int, 4> Mask(NumElts); 5109 5110 for (int i = 0; i != NumElts; ++i) { 5111 int M0 = SV0->getMaskElt(i); 5112 int M1 = SV1->getMaskElt(i); 5113 5114 // Determine if either index is pointing to a zero vector. 5115 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 5116 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 5117 5118 // If one element is zero and the otherside is undef, keep undef. 5119 // This also handles the case that both are undef. 5120 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 5121 Mask[i] = -1; 5122 continue; 5123 } 5124 5125 // Make sure only one of the elements is zero. 5126 if (M0Zero == M1Zero) { 5127 CanFold = false; 5128 break; 5129 } 5130 5131 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 5132 5133 // We have a zero and non-zero element. If the non-zero came from 5134 // SV0 make the index a LHS index. If it came from SV1, make it 5135 // a RHS index. We need to mod by NumElts because we don't care 5136 // which operand it came from in the original shuffles. 5137 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 5138 } 5139 5140 if (CanFold) { 5141 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 5142 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 5143 5144 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5145 if (!LegalMask) { 5146 std::swap(NewLHS, NewRHS); 5147 ShuffleVectorSDNode::commuteMask(Mask); 5148 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5149 } 5150 5151 if (LegalMask) 5152 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 5153 } 5154 } 5155 } 5156 } 5157 5158 // fold (or c1, c2) -> c1|c2 5159 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5160 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5161 if (N0C && N1C && !N1C->isOpaque()) 5162 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 5163 // canonicalize constant to RHS 5164 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5165 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5166 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 5167 // fold (or x, 0) -> x 5168 if (isNullConstant(N1)) 5169 return N0; 5170 // fold (or x, -1) -> -1 5171 if (isAllOnesConstant(N1)) 5172 return N1; 5173 5174 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5175 return NewSel; 5176 5177 // fold (or x, c) -> c iff (x & ~c) == 0 5178 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 5179 return N1; 5180 5181 if (SDValue Combined = visitORLike(N0, N1, N)) 5182 return Combined; 5183 5184 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 5185 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 5186 return BSwap; 5187 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 5188 return BSwap; 5189 5190 // reassociate or 5191 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) 5192 return ROR; 5193 5194 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 5195 // iff (c1 & c2) != 0. 5196 auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 5197 return LHS->getAPIntValue().intersects(RHS->getAPIntValue()); 5198 }; 5199 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5200 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) { 5201 if (SDValue COR = DAG.FoldConstantArithmetic( 5202 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 5203 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 5204 AddToWorklist(IOR.getNode()); 5205 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 5206 } 5207 } 5208 5209 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 5210 if (N0.getOpcode() == N1.getOpcode()) 5211 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5212 return Tmp; 5213 5214 // See if this is some rotate idiom. 5215 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 5216 return SDValue(Rot, 0); 5217 5218 if (SDValue Load = MatchLoadCombine(N)) 5219 return Load; 5220 5221 // Simplify the operands using demanded-bits information. 5222 if (SimplifyDemandedBits(SDValue(N, 0))) 5223 return SDValue(N, 0); 5224 5225 return SDValue(); 5226 } 5227 5228 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 5229 if (Op.getOpcode() == ISD::AND && 5230 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 5231 Mask = Op.getOperand(1); 5232 return Op.getOperand(0); 5233 } 5234 return Op; 5235 } 5236 5237 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 5238 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 5239 SDValue &Mask) { 5240 Op = stripConstantMask(DAG, Op, Mask); 5241 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 5242 Shift = Op; 5243 return true; 5244 } 5245 return false; 5246 } 5247 5248 /// Helper function for visitOR to extract the needed side of a rotate idiom 5249 /// from a shl/srl/mul/udiv. This is meant to handle cases where 5250 /// InstCombine merged some outside op with one of the shifts from 5251 /// the rotate pattern. 5252 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 5253 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 5254 /// patterns: 5255 /// 5256 /// (or (mul v c0) (shrl (mul v c1) c2)): 5257 /// expands (mul v c0) -> (shl (mul v c1) c3) 5258 /// 5259 /// (or (udiv v c0) (shl (udiv v c1) c2)): 5260 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 5261 /// 5262 /// (or (shl v c0) (shrl (shl v c1) c2)): 5263 /// expands (shl v c0) -> (shl (shl v c1) c3) 5264 /// 5265 /// (or (shrl v c0) (shl (shrl v c1) c2)): 5266 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 5267 /// 5268 /// Such that in all cases, c3+c2==bitwidth(op v c1). 5269 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 5270 SDValue ExtractFrom, SDValue &Mask, 5271 const SDLoc &DL) { 5272 assert(OppShift && ExtractFrom && "Empty SDValue"); 5273 assert( 5274 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 5275 "Existing shift must be valid as a rotate half"); 5276 5277 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 5278 // Preconditions: 5279 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 5280 // 5281 // Find opcode of the needed shift to be extracted from (op0 v c0). 5282 unsigned Opcode = ISD::DELETED_NODE; 5283 bool IsMulOrDiv = false; 5284 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 5285 // opcode or its arithmetic (mul or udiv) variant. 5286 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 5287 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 5288 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 5289 return false; 5290 Opcode = NeededShift; 5291 return true; 5292 }; 5293 // op0 must be either the needed shift opcode or the mul/udiv equivalent 5294 // that the needed shift can be extracted from. 5295 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 5296 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 5297 return SDValue(); 5298 5299 // op0 must be the same opcode on both sides, have the same LHS argument, 5300 // and produce the same value type. 5301 SDValue OppShiftLHS = OppShift.getOperand(0); 5302 EVT ShiftedVT = OppShiftLHS.getValueType(); 5303 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 5304 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 5305 ShiftedVT != ExtractFrom.getValueType()) 5306 return SDValue(); 5307 5308 // Amount of the existing shift. 5309 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 5310 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 5311 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 5312 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 5313 ConstantSDNode *ExtractFromCst = 5314 isConstOrConstSplat(ExtractFrom.getOperand(1)); 5315 // TODO: We should be able to handle non-uniform constant vectors for these values 5316 // Check that we have constant values. 5317 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 5318 !OppLHSCst || !OppLHSCst->getAPIntValue() || 5319 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 5320 return SDValue(); 5321 5322 // Compute the shift amount we need to extract to complete the rotate. 5323 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 5324 if (OppShiftCst->getAPIntValue().ugt(VTWidth)) 5325 return SDValue(); 5326 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 5327 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 5328 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 5329 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 5330 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 5331 5332 // Now try extract the needed shift from the ExtractFrom op and see if the 5333 // result matches up with the existing shift's LHS op. 5334 if (IsMulOrDiv) { 5335 // Op to extract from is a mul or udiv by a constant. 5336 // Check: 5337 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 5338 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 5339 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 5340 NeededShiftAmt.getZExtValue()); 5341 APInt ResultAmt; 5342 APInt Rem; 5343 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 5344 if (Rem != 0 || ResultAmt != OppLHSAmt) 5345 return SDValue(); 5346 } else { 5347 // Op to extract from is a shift by a constant. 5348 // Check: 5349 // c2 - (bitwidth(op0 v c0) - c1) == c0 5350 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 5351 ExtractFromAmt.getBitWidth())) 5352 return SDValue(); 5353 } 5354 5355 // Return the expanded shift op that should allow a rotate to be formed. 5356 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 5357 EVT ResVT = ExtractFrom.getValueType(); 5358 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 5359 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 5360 } 5361 5362 // Return true if we can prove that, whenever Neg and Pos are both in the 5363 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 5364 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 5365 // 5366 // (or (shift1 X, Neg), (shift2 X, Pos)) 5367 // 5368 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 5369 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 5370 // to consider shift amounts with defined behavior. 5371 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 5372 SelectionDAG &DAG) { 5373 // If EltSize is a power of 2 then: 5374 // 5375 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 5376 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 5377 // 5378 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 5379 // for the stronger condition: 5380 // 5381 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 5382 // 5383 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 5384 // we can just replace Neg with Neg' for the rest of the function. 5385 // 5386 // In other cases we check for the even stronger condition: 5387 // 5388 // Neg == EltSize - Pos [B] 5389 // 5390 // for all Neg and Pos. Note that the (or ...) then invokes undefined 5391 // behavior if Pos == 0 (and consequently Neg == EltSize). 5392 // 5393 // We could actually use [A] whenever EltSize is a power of 2, but the 5394 // only extra cases that it would match are those uninteresting ones 5395 // where Neg and Pos are never in range at the same time. E.g. for 5396 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 5397 // as well as (sub 32, Pos), but: 5398 // 5399 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 5400 // 5401 // always invokes undefined behavior for 32-bit X. 5402 // 5403 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 5404 unsigned MaskLoBits = 0; 5405 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 5406 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 5407 KnownBits Known; 5408 DAG.computeKnownBits(Neg.getOperand(0), Known); 5409 unsigned Bits = Log2_64(EltSize); 5410 if (NegC->getAPIntValue().getActiveBits() <= Bits && 5411 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 5412 Neg = Neg.getOperand(0); 5413 MaskLoBits = Bits; 5414 } 5415 } 5416 } 5417 5418 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 5419 if (Neg.getOpcode() != ISD::SUB) 5420 return false; 5421 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 5422 if (!NegC) 5423 return false; 5424 SDValue NegOp1 = Neg.getOperand(1); 5425 5426 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 5427 // Pos'. The truncation is redundant for the purpose of the equality. 5428 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 5429 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 5430 KnownBits Known; 5431 DAG.computeKnownBits(Pos.getOperand(0), Known); 5432 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 5433 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 5434 MaskLoBits)) 5435 Pos = Pos.getOperand(0); 5436 } 5437 } 5438 5439 // The condition we need is now: 5440 // 5441 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 5442 // 5443 // If NegOp1 == Pos then we need: 5444 // 5445 // EltSize & Mask == NegC & Mask 5446 // 5447 // (because "x & Mask" is a truncation and distributes through subtraction). 5448 APInt Width; 5449 if (Pos == NegOp1) 5450 Width = NegC->getAPIntValue(); 5451 5452 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 5453 // Then the condition we want to prove becomes: 5454 // 5455 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 5456 // 5457 // which, again because "x & Mask" is a truncation, becomes: 5458 // 5459 // NegC & Mask == (EltSize - PosC) & Mask 5460 // EltSize & Mask == (NegC + PosC) & Mask 5461 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 5462 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 5463 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 5464 else 5465 return false; 5466 } else 5467 return false; 5468 5469 // Now we just need to check that EltSize & Mask == Width & Mask. 5470 if (MaskLoBits) 5471 // EltSize & Mask is 0 since Mask is EltSize - 1. 5472 return Width.getLoBits(MaskLoBits) == 0; 5473 return Width == EltSize; 5474 } 5475 5476 // A subroutine of MatchRotate used once we have found an OR of two opposite 5477 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 5478 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 5479 // former being preferred if supported. InnerPos and InnerNeg are Pos and 5480 // Neg with outer conversions stripped away. 5481 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 5482 SDValue Neg, SDValue InnerPos, 5483 SDValue InnerNeg, unsigned PosOpcode, 5484 unsigned NegOpcode, const SDLoc &DL) { 5485 // fold (or (shl x, (*ext y)), 5486 // (srl x, (*ext (sub 32, y)))) -> 5487 // (rotl x, y) or (rotr x, (sub 32, y)) 5488 // 5489 // fold (or (shl x, (*ext (sub 32, y))), 5490 // (srl x, (*ext y))) -> 5491 // (rotr x, y) or (rotl x, (sub 32, y)) 5492 EVT VT = Shifted.getValueType(); 5493 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) { 5494 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 5495 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 5496 HasPos ? Pos : Neg).getNode(); 5497 } 5498 5499 return nullptr; 5500 } 5501 5502 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 5503 // idioms for rotate, and if the target supports rotation instructions, generate 5504 // a rot[lr]. 5505 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 5506 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 5507 EVT VT = LHS.getValueType(); 5508 if (!TLI.isTypeLegal(VT)) return nullptr; 5509 5510 // The target must have at least one rotate flavor. 5511 bool HasROTL = hasOperation(ISD::ROTL, VT); 5512 bool HasROTR = hasOperation(ISD::ROTR, VT); 5513 if (!HasROTL && !HasROTR) return nullptr; 5514 5515 // Check for truncated rotate. 5516 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 5517 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 5518 assert(LHS.getValueType() == RHS.getValueType()); 5519 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 5520 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 5521 SDValue(Rot, 0)).getNode(); 5522 } 5523 } 5524 5525 // Match "(X shl/srl V1) & V2" where V2 may not be present. 5526 SDValue LHSShift; // The shift. 5527 SDValue LHSMask; // AND value if any. 5528 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 5529 5530 SDValue RHSShift; // The shift. 5531 SDValue RHSMask; // AND value if any. 5532 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 5533 5534 // If neither side matched a rotate half, bail 5535 if (!LHSShift && !RHSShift) 5536 return nullptr; 5537 5538 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 5539 // side of the rotate, so try to handle that here. In all cases we need to 5540 // pass the matched shift from the opposite side to compute the opcode and 5541 // needed shift amount to extract. We still want to do this if both sides 5542 // matched a rotate half because one half may be a potential overshift that 5543 // can be broken down (ie if InstCombine merged two shl or srl ops into a 5544 // single one). 5545 5546 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 5547 if (LHSShift) 5548 if (SDValue NewRHSShift = 5549 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 5550 RHSShift = NewRHSShift; 5551 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 5552 if (RHSShift) 5553 if (SDValue NewLHSShift = 5554 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 5555 LHSShift = NewLHSShift; 5556 5557 // If a side is still missing, nothing else we can do. 5558 if (!RHSShift || !LHSShift) 5559 return nullptr; 5560 5561 // At this point we've matched or extracted a shift op on each side. 5562 5563 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 5564 return nullptr; // Not shifting the same value. 5565 5566 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 5567 return nullptr; // Shifts must disagree. 5568 5569 // Canonicalize shl to left side in a shl/srl pair. 5570 if (RHSShift.getOpcode() == ISD::SHL) { 5571 std::swap(LHS, RHS); 5572 std::swap(LHSShift, RHSShift); 5573 std::swap(LHSMask, RHSMask); 5574 } 5575 5576 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5577 SDValue LHSShiftArg = LHSShift.getOperand(0); 5578 SDValue LHSShiftAmt = LHSShift.getOperand(1); 5579 SDValue RHSShiftArg = RHSShift.getOperand(0); 5580 SDValue RHSShiftAmt = RHSShift.getOperand(1); 5581 5582 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 5583 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 5584 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 5585 ConstantSDNode *RHS) { 5586 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 5587 }; 5588 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 5589 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 5590 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 5591 5592 // If there is an AND of either shifted operand, apply it to the result. 5593 if (LHSMask.getNode() || RHSMask.getNode()) { 5594 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 5595 SDValue Mask = AllOnes; 5596 5597 if (LHSMask.getNode()) { 5598 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 5599 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5600 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 5601 } 5602 if (RHSMask.getNode()) { 5603 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 5604 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5605 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 5606 } 5607 5608 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 5609 } 5610 5611 return Rot.getNode(); 5612 } 5613 5614 // If there is a mask here, and we have a variable shift, we can't be sure 5615 // that we're masking out the right stuff. 5616 if (LHSMask.getNode() || RHSMask.getNode()) 5617 return nullptr; 5618 5619 // If the shift amount is sign/zext/any-extended just peel it off. 5620 SDValue LExtOp0 = LHSShiftAmt; 5621 SDValue RExtOp0 = RHSShiftAmt; 5622 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5623 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5624 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5625 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 5626 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5627 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5628 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5629 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 5630 LExtOp0 = LHSShiftAmt.getOperand(0); 5631 RExtOp0 = RHSShiftAmt.getOperand(0); 5632 } 5633 5634 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 5635 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 5636 if (TryL) 5637 return TryL; 5638 5639 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 5640 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 5641 if (TryR) 5642 return TryR; 5643 5644 return nullptr; 5645 } 5646 5647 namespace { 5648 5649 /// Represents known origin of an individual byte in load combine pattern. The 5650 /// value of the byte is either constant zero or comes from memory. 5651 struct ByteProvider { 5652 // For constant zero providers Load is set to nullptr. For memory providers 5653 // Load represents the node which loads the byte from memory. 5654 // ByteOffset is the offset of the byte in the value produced by the load. 5655 LoadSDNode *Load = nullptr; 5656 unsigned ByteOffset = 0; 5657 5658 ByteProvider() = default; 5659 5660 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 5661 return ByteProvider(Load, ByteOffset); 5662 } 5663 5664 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 5665 5666 bool isConstantZero() const { return !Load; } 5667 bool isMemory() const { return Load; } 5668 5669 bool operator==(const ByteProvider &Other) const { 5670 return Other.Load == Load && Other.ByteOffset == ByteOffset; 5671 } 5672 5673 private: 5674 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 5675 : Load(Load), ByteOffset(ByteOffset) {} 5676 }; 5677 5678 } // end anonymous namespace 5679 5680 /// Recursively traverses the expression calculating the origin of the requested 5681 /// byte of the given value. Returns None if the provider can't be calculated. 5682 /// 5683 /// For all the values except the root of the expression verifies that the value 5684 /// has exactly one use and if it's not true return None. This way if the origin 5685 /// of the byte is returned it's guaranteed that the values which contribute to 5686 /// the byte are not used outside of this expression. 5687 /// 5688 /// Because the parts of the expression are not allowed to have more than one 5689 /// use this function iterates over trees, not DAGs. So it never visits the same 5690 /// node more than once. 5691 static const Optional<ByteProvider> 5692 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 5693 bool Root = false) { 5694 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 5695 if (Depth == 10) 5696 return None; 5697 5698 if (!Root && !Op.hasOneUse()) 5699 return None; 5700 5701 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 5702 unsigned BitWidth = Op.getValueSizeInBits(); 5703 if (BitWidth % 8 != 0) 5704 return None; 5705 unsigned ByteWidth = BitWidth / 8; 5706 assert(Index < ByteWidth && "invalid index requested"); 5707 (void) ByteWidth; 5708 5709 switch (Op.getOpcode()) { 5710 case ISD::OR: { 5711 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 5712 if (!LHS) 5713 return None; 5714 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 5715 if (!RHS) 5716 return None; 5717 5718 if (LHS->isConstantZero()) 5719 return RHS; 5720 if (RHS->isConstantZero()) 5721 return LHS; 5722 return None; 5723 } 5724 case ISD::SHL: { 5725 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 5726 if (!ShiftOp) 5727 return None; 5728 5729 uint64_t BitShift = ShiftOp->getZExtValue(); 5730 if (BitShift % 8 != 0) 5731 return None; 5732 uint64_t ByteShift = BitShift / 8; 5733 5734 return Index < ByteShift 5735 ? ByteProvider::getConstantZero() 5736 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 5737 Depth + 1); 5738 } 5739 case ISD::ANY_EXTEND: 5740 case ISD::SIGN_EXTEND: 5741 case ISD::ZERO_EXTEND: { 5742 SDValue NarrowOp = Op->getOperand(0); 5743 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 5744 if (NarrowBitWidth % 8 != 0) 5745 return None; 5746 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5747 5748 if (Index >= NarrowByteWidth) 5749 return Op.getOpcode() == ISD::ZERO_EXTEND 5750 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5751 : None; 5752 return calculateByteProvider(NarrowOp, Index, Depth + 1); 5753 } 5754 case ISD::BSWAP: 5755 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 5756 Depth + 1); 5757 case ISD::LOAD: { 5758 auto L = cast<LoadSDNode>(Op.getNode()); 5759 if (L->isVolatile() || L->isIndexed()) 5760 return None; 5761 5762 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 5763 if (NarrowBitWidth % 8 != 0) 5764 return None; 5765 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 5766 5767 if (Index >= NarrowByteWidth) 5768 return L->getExtensionType() == ISD::ZEXTLOAD 5769 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 5770 : None; 5771 return ByteProvider::getMemory(L, Index); 5772 } 5773 } 5774 5775 return None; 5776 } 5777 5778 /// Match a pattern where a wide type scalar value is loaded by several narrow 5779 /// loads and combined by shifts and ors. Fold it into a single load or a load 5780 /// and a BSWAP if the targets supports it. 5781 /// 5782 /// Assuming little endian target: 5783 /// i8 *a = ... 5784 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 5785 /// => 5786 /// i32 val = *((i32)a) 5787 /// 5788 /// i8 *a = ... 5789 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 5790 /// => 5791 /// i32 val = BSWAP(*((i32)a)) 5792 /// 5793 /// TODO: This rule matches complex patterns with OR node roots and doesn't 5794 /// interact well with the worklist mechanism. When a part of the pattern is 5795 /// updated (e.g. one of the loads) its direct users are put into the worklist, 5796 /// but the root node of the pattern which triggers the load combine is not 5797 /// necessarily a direct user of the changed node. For example, once the address 5798 /// of t28 load is reassociated load combine won't be triggered: 5799 /// t25: i32 = add t4, Constant:i32<2> 5800 /// t26: i64 = sign_extend t25 5801 /// t27: i64 = add t2, t26 5802 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 5803 /// t29: i32 = zero_extend t28 5804 /// t32: i32 = shl t29, Constant:i8<8> 5805 /// t33: i32 = or t23, t32 5806 /// As a possible fix visitLoad can check if the load can be a part of a load 5807 /// combine pattern and add corresponding OR roots to the worklist. 5808 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 5809 assert(N->getOpcode() == ISD::OR && 5810 "Can only match load combining against OR nodes"); 5811 5812 // Handles simple types only 5813 EVT VT = N->getValueType(0); 5814 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 5815 return SDValue(); 5816 unsigned ByteWidth = VT.getSizeInBits() / 8; 5817 5818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5819 // Before legalize we can introduce too wide illegal loads which will be later 5820 // split into legal sized loads. This enables us to combine i64 load by i8 5821 // patterns to a couple of i32 loads on 32 bit targets. 5822 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 5823 return SDValue(); 5824 5825 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 5826 unsigned BW, unsigned i) { return i; }; 5827 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 5828 unsigned BW, unsigned i) { return BW - i - 1; }; 5829 5830 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 5831 auto MemoryByteOffset = [&] (ByteProvider P) { 5832 assert(P.isMemory() && "Must be a memory byte provider"); 5833 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 5834 assert(LoadBitWidth % 8 == 0 && 5835 "can only analyze providers for individual bytes not bit"); 5836 unsigned LoadByteWidth = LoadBitWidth / 8; 5837 return IsBigEndianTarget 5838 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 5839 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 5840 }; 5841 5842 Optional<BaseIndexOffset> Base; 5843 SDValue Chain; 5844 5845 SmallPtrSet<LoadSDNode *, 8> Loads; 5846 Optional<ByteProvider> FirstByteProvider; 5847 int64_t FirstOffset = INT64_MAX; 5848 5849 // Check if all the bytes of the OR we are looking at are loaded from the same 5850 // base address. Collect bytes offsets from Base address in ByteOffsets. 5851 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5852 for (unsigned i = 0; i < ByteWidth; i++) { 5853 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5854 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5855 return SDValue(); 5856 5857 LoadSDNode *L = P->Load; 5858 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5859 "Must be enforced by calculateByteProvider"); 5860 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5861 5862 // All loads must share the same chain 5863 SDValue LChain = L->getChain(); 5864 if (!Chain) 5865 Chain = LChain; 5866 else if (Chain != LChain) 5867 return SDValue(); 5868 5869 // Loads must share the same base address 5870 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 5871 int64_t ByteOffsetFromBase = 0; 5872 if (!Base) 5873 Base = Ptr; 5874 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 5875 return SDValue(); 5876 5877 // Calculate the offset of the current byte from the base address 5878 ByteOffsetFromBase += MemoryByteOffset(*P); 5879 ByteOffsets[i] = ByteOffsetFromBase; 5880 5881 // Remember the first byte load 5882 if (ByteOffsetFromBase < FirstOffset) { 5883 FirstByteProvider = P; 5884 FirstOffset = ByteOffsetFromBase; 5885 } 5886 5887 Loads.insert(L); 5888 } 5889 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 5890 "memory, so there must be at least one load which produces the value"); 5891 assert(Base && "Base address of the accessed memory location must be set"); 5892 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5893 5894 // Check if the bytes of the OR we are looking at match with either big or 5895 // little endian value load 5896 bool BigEndian = true, LittleEndian = true; 5897 for (unsigned i = 0; i < ByteWidth; i++) { 5898 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5899 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5900 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5901 if (!BigEndian && !LittleEndian) 5902 return SDValue(); 5903 } 5904 assert((BigEndian != LittleEndian) && "should be either or"); 5905 assert(FirstByteProvider && "must be set"); 5906 5907 // Ensure that the first byte is loaded from zero offset of the first load. 5908 // So the combined value can be loaded from the first load address. 5909 if (MemoryByteOffset(*FirstByteProvider) != 0) 5910 return SDValue(); 5911 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5912 5913 // The node we are looking at matches with the pattern, check if we can 5914 // replace it with a single load and bswap if needed. 5915 5916 // If the load needs byte swap check if the target supports it 5917 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5918 5919 // Before legalize we can introduce illegal bswaps which will be later 5920 // converted to an explicit bswap sequence. This way we end up with a single 5921 // load and byte shuffling instead of several loads and byte shuffling. 5922 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5923 return SDValue(); 5924 5925 // Check that a load of the wide type is both allowed and fast on the target 5926 bool Fast = false; 5927 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5928 VT, FirstLoad->getAddressSpace(), 5929 FirstLoad->getAlignment(), &Fast); 5930 if (!Allowed || !Fast) 5931 return SDValue(); 5932 5933 SDValue NewLoad = 5934 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5935 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5936 5937 // Transfer chain users from old loads to the new load. 5938 for (LoadSDNode *L : Loads) 5939 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5940 5941 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5942 } 5943 5944 // If the target has andn, bsl, or a similar bit-select instruction, 5945 // we want to unfold masked merge, with canonical pattern of: 5946 // | A | |B| 5947 // ((x ^ y) & m) ^ y 5948 // | D | 5949 // Into: 5950 // (x & m) | (y & ~m) 5951 // If y is a constant, and the 'andn' does not work with immediates, 5952 // we unfold into a different pattern: 5953 // ~(~x & m) & (m | y) 5954 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 5955 // the very least that breaks andnpd / andnps patterns, and because those 5956 // patterns are simplified in IR and shouldn't be created in the DAG 5957 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 5958 assert(N->getOpcode() == ISD::XOR); 5959 5960 // Don't touch 'not' (i.e. where y = -1). 5961 if (isAllOnesConstantOrAllOnesSplatConstant(N->getOperand(1))) 5962 return SDValue(); 5963 5964 EVT VT = N->getValueType(0); 5965 5966 // There are 3 commutable operators in the pattern, 5967 // so we have to deal with 8 possible variants of the basic pattern. 5968 SDValue X, Y, M; 5969 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 5970 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 5971 return false; 5972 SDValue Xor = And.getOperand(XorIdx); 5973 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 5974 return false; 5975 SDValue Xor0 = Xor.getOperand(0); 5976 SDValue Xor1 = Xor.getOperand(1); 5977 // Don't touch 'not' (i.e. where y = -1). 5978 if (isAllOnesConstantOrAllOnesSplatConstant(Xor1)) 5979 return false; 5980 if (Other == Xor0) 5981 std::swap(Xor0, Xor1); 5982 if (Other != Xor1) 5983 return false; 5984 X = Xor0; 5985 Y = Xor1; 5986 M = And.getOperand(XorIdx ? 0 : 1); 5987 return true; 5988 }; 5989 5990 SDValue N0 = N->getOperand(0); 5991 SDValue N1 = N->getOperand(1); 5992 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 5993 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 5994 return SDValue(); 5995 5996 // Don't do anything if the mask is constant. This should not be reachable. 5997 // InstCombine should have already unfolded this pattern, and DAGCombiner 5998 // probably shouldn't produce it, too. 5999 if (isa<ConstantSDNode>(M.getNode())) 6000 return SDValue(); 6001 6002 // We can transform if the target has AndNot 6003 if (!TLI.hasAndNot(M)) 6004 return SDValue(); 6005 6006 SDLoc DL(N); 6007 6008 // If Y is a constant, check that 'andn' works with immediates. 6009 if (!TLI.hasAndNot(Y)) { 6010 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 6011 // If not, we need to do a bit more work to make sure andn is still used. 6012 SDValue NotX = DAG.getNOT(DL, X, VT); 6013 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 6014 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 6015 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 6016 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 6017 } 6018 6019 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 6020 SDValue NotM = DAG.getNOT(DL, M, VT); 6021 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 6022 6023 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 6024 } 6025 6026 SDValue DAGCombiner::visitXOR(SDNode *N) { 6027 SDValue N0 = N->getOperand(0); 6028 SDValue N1 = N->getOperand(1); 6029 EVT VT = N0.getValueType(); 6030 6031 // fold vector ops 6032 if (VT.isVector()) { 6033 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6034 return FoldedVOp; 6035 6036 // fold (xor x, 0) -> x, vector edition 6037 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6038 return N1; 6039 if (ISD::isBuildVectorAllZeros(N1.getNode())) 6040 return N0; 6041 } 6042 6043 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 6044 if (N0.isUndef() && N1.isUndef()) 6045 return DAG.getConstant(0, SDLoc(N), VT); 6046 // fold (xor x, undef) -> undef 6047 if (N0.isUndef()) 6048 return N0; 6049 if (N1.isUndef()) 6050 return N1; 6051 // fold (xor c1, c2) -> c1^c2 6052 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6053 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 6054 if (N0C && N1C) 6055 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 6056 // canonicalize constant to RHS 6057 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 6058 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 6059 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 6060 // fold (xor x, 0) -> x 6061 if (isNullConstant(N1)) 6062 return N0; 6063 6064 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6065 return NewSel; 6066 6067 // reassociate xor 6068 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1, N->getFlags())) 6069 return RXOR; 6070 6071 // fold !(x cc y) -> (x !cc y) 6072 SDValue LHS, RHS, CC; 6073 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 6074 bool isInt = LHS.getValueType().isInteger(); 6075 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 6076 isInt); 6077 6078 if (!LegalOperations || 6079 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 6080 switch (N0.getOpcode()) { 6081 default: 6082 llvm_unreachable("Unhandled SetCC Equivalent!"); 6083 case ISD::SETCC: 6084 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 6085 case ISD::SELECT_CC: 6086 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 6087 N0.getOperand(3), NotCC); 6088 } 6089 } 6090 } 6091 6092 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 6093 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 6094 N0.getNode()->hasOneUse() && 6095 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 6096 SDValue V = N0.getOperand(0); 6097 SDLoc DL(N0); 6098 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 6099 DAG.getConstant(1, DL, V.getValueType())); 6100 AddToWorklist(V.getNode()); 6101 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 6102 } 6103 6104 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 6105 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 6106 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6107 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6108 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 6109 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6110 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6111 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6112 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6113 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6114 } 6115 } 6116 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 6117 if (isAllOnesConstant(N1) && N0.hasOneUse() && 6118 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 6119 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6120 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 6121 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 6122 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6123 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6124 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6125 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 6126 } 6127 } 6128 // fold (xor (and x, y), y) -> (and (not x), y) 6129 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 6130 N0->getOperand(1) == N1) { 6131 SDValue X = N0->getOperand(0); 6132 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 6133 AddToWorklist(NotX.getNode()); 6134 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 6135 } 6136 6137 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 6138 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 6139 SDValue A = N0.getOpcode() == ISD::ADD ? N0 : N1; 6140 SDValue S = N0.getOpcode() == ISD::SRA ? N0 : N1; 6141 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 6142 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 6143 SDValue S0 = S.getOperand(0); 6144 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) { 6145 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6146 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 6147 if (C->getAPIntValue() == (OpSizeInBits - 1)) 6148 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 6149 } 6150 } 6151 } 6152 6153 // fold (xor x, x) -> 0 6154 if (N0 == N1) 6155 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 6156 6157 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 6158 // Here is a concrete example of this equivalence: 6159 // i16 x == 14 6160 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 6161 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 6162 // 6163 // => 6164 // 6165 // i16 ~1 == 0b1111111111111110 6166 // i16 rol(~1, 14) == 0b1011111111111111 6167 // 6168 // Some additional tips to help conceptualize this transform: 6169 // - Try to see the operation as placing a single zero in a value of all ones. 6170 // - There exists no value for x which would allow the result to contain zero. 6171 // - Values of x larger than the bitwidth are undefined and do not require a 6172 // consistent result. 6173 // - Pushing the zero left requires shifting one bits in from the right. 6174 // A rotate left of ~1 is a nice way of achieving the desired result. 6175 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 6176 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 6177 SDLoc DL(N); 6178 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 6179 N0.getOperand(1)); 6180 } 6181 6182 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 6183 if (N0.getOpcode() == N1.getOpcode()) 6184 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 6185 return Tmp; 6186 6187 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 6188 if (SDValue MM = unfoldMaskedMerge(N)) 6189 return MM; 6190 6191 // Simplify the expression using non-local knowledge. 6192 if (SimplifyDemandedBits(SDValue(N, 0))) 6193 return SDValue(N, 0); 6194 6195 return SDValue(); 6196 } 6197 6198 /// Handle transforms common to the three shifts, when the shift amount is a 6199 /// constant. 6200 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 6201 SDNode *LHS = N->getOperand(0).getNode(); 6202 if (!LHS->hasOneUse()) return SDValue(); 6203 6204 // We want to pull some binops through shifts, so that we have (and (shift)) 6205 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 6206 // thing happens with address calculations, so it's important to canonicalize 6207 // it. 6208 bool HighBitSet = false; // Can we transform this if the high bit is set? 6209 6210 switch (LHS->getOpcode()) { 6211 default: return SDValue(); 6212 case ISD::OR: 6213 case ISD::XOR: 6214 HighBitSet = false; // We can only transform sra if the high bit is clear. 6215 break; 6216 case ISD::AND: 6217 HighBitSet = true; // We can only transform sra if the high bit is set. 6218 break; 6219 case ISD::ADD: 6220 if (N->getOpcode() != ISD::SHL) 6221 return SDValue(); // only shl(add) not sr[al](add). 6222 HighBitSet = false; // We can only transform sra if the high bit is clear. 6223 break; 6224 } 6225 6226 // We require the RHS of the binop to be a constant and not opaque as well. 6227 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 6228 if (!BinOpCst) return SDValue(); 6229 6230 // FIXME: disable this unless the input to the binop is a shift by a constant 6231 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 6232 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 6233 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 6234 BinOpLHSVal->getOpcode() == ISD::SRA || 6235 BinOpLHSVal->getOpcode() == ISD::SRL; 6236 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 6237 BinOpLHSVal->getOpcode() == ISD::SELECT; 6238 6239 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 6240 !isCopyOrSelect) 6241 return SDValue(); 6242 6243 if (isCopyOrSelect && N->hasOneUse()) 6244 return SDValue(); 6245 6246 EVT VT = N->getValueType(0); 6247 6248 // If this is a signed shift right, and the high bit is modified by the 6249 // logical operation, do not perform the transformation. The highBitSet 6250 // boolean indicates the value of the high bit of the constant which would 6251 // cause it to be modified for this operation. 6252 if (N->getOpcode() == ISD::SRA) { 6253 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 6254 if (BinOpRHSSignSet != HighBitSet) 6255 return SDValue(); 6256 } 6257 6258 if (!TLI.isDesirableToCommuteWithShift(N, Level)) 6259 return SDValue(); 6260 6261 // Fold the constants, shifting the binop RHS by the shift amount. 6262 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 6263 N->getValueType(0), 6264 LHS->getOperand(1), N->getOperand(1)); 6265 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 6266 6267 // Create the new shift. 6268 SDValue NewShift = DAG.getNode(N->getOpcode(), 6269 SDLoc(LHS->getOperand(0)), 6270 VT, LHS->getOperand(0), N->getOperand(1)); 6271 6272 // Create the new binop. 6273 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 6274 } 6275 6276 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 6277 assert(N->getOpcode() == ISD::TRUNCATE); 6278 assert(N->getOperand(0).getOpcode() == ISD::AND); 6279 6280 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 6281 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 6282 SDValue N01 = N->getOperand(0).getOperand(1); 6283 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 6284 SDLoc DL(N); 6285 EVT TruncVT = N->getValueType(0); 6286 SDValue N00 = N->getOperand(0).getOperand(0); 6287 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 6288 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 6289 AddToWorklist(Trunc00.getNode()); 6290 AddToWorklist(Trunc01.getNode()); 6291 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 6292 } 6293 } 6294 6295 return SDValue(); 6296 } 6297 6298 SDValue DAGCombiner::visitRotate(SDNode *N) { 6299 SDLoc dl(N); 6300 SDValue N0 = N->getOperand(0); 6301 SDValue N1 = N->getOperand(1); 6302 EVT VT = N->getValueType(0); 6303 unsigned Bitsize = VT.getScalarSizeInBits(); 6304 6305 // fold (rot x, 0) -> x 6306 if (isNullConstantOrNullSplatConstant(N1)) 6307 return N0; 6308 6309 // fold (rot x, c) -> (rot x, c % BitSize) 6310 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 6311 if (Cst->getAPIntValue().uge(Bitsize)) { 6312 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 6313 return DAG.getNode(N->getOpcode(), dl, VT, N0, 6314 DAG.getConstant(RotAmt, dl, N1.getValueType())); 6315 } 6316 } 6317 6318 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 6319 if (N1.getOpcode() == ISD::TRUNCATE && 6320 N1.getOperand(0).getOpcode() == ISD::AND) { 6321 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6322 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 6323 } 6324 6325 unsigned NextOp = N0.getOpcode(); 6326 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 6327 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 6328 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 6329 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 6330 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 6331 EVT ShiftVT = C1->getValueType(0); 6332 bool SameSide = (N->getOpcode() == NextOp); 6333 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 6334 if (SDValue CombinedShift = 6335 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 6336 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 6337 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 6338 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 6339 BitsizeC.getNode()); 6340 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 6341 CombinedShiftNorm); 6342 } 6343 } 6344 } 6345 return SDValue(); 6346 } 6347 6348 SDValue DAGCombiner::visitSHL(SDNode *N) { 6349 SDValue N0 = N->getOperand(0); 6350 SDValue N1 = N->getOperand(1); 6351 EVT VT = N0.getValueType(); 6352 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6353 6354 // fold vector ops 6355 if (VT.isVector()) { 6356 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6357 return FoldedVOp; 6358 6359 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 6360 // If setcc produces all-one true value then: 6361 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 6362 if (N1CV && N1CV->isConstant()) { 6363 if (N0.getOpcode() == ISD::AND) { 6364 SDValue N00 = N0->getOperand(0); 6365 SDValue N01 = N0->getOperand(1); 6366 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 6367 6368 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 6369 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 6370 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6371 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 6372 N01CV, N1CV)) 6373 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 6374 } 6375 } 6376 } 6377 } 6378 6379 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6380 6381 // fold (shl c1, c2) -> c1<<c2 6382 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6383 if (N0C && N1C && !N1C->isOpaque()) 6384 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 6385 // fold (shl 0, x) -> 0 6386 if (isNullConstantOrNullSplatConstant(N0)) 6387 return N0; 6388 // fold (shl x, c >= size(x)) -> undef 6389 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6390 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6391 return Val->getAPIntValue().uge(OpSizeInBits); 6392 }; 6393 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6394 return DAG.getUNDEF(VT); 6395 // fold (shl x, 0) -> x 6396 if (N1C && N1C->isNullValue()) 6397 return N0; 6398 // fold (shl undef, x) -> 0 6399 if (N0.isUndef()) 6400 return DAG.getConstant(0, SDLoc(N), VT); 6401 6402 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6403 return NewSel; 6404 6405 // if (shl x, c) is known to be zero, return 0 6406 if (DAG.MaskedValueIsZero(SDValue(N, 0), 6407 APInt::getAllOnesValue(OpSizeInBits))) 6408 return DAG.getConstant(0, SDLoc(N), VT); 6409 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 6410 if (N1.getOpcode() == ISD::TRUNCATE && 6411 N1.getOperand(0).getOpcode() == ISD::AND) { 6412 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6413 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 6414 } 6415 6416 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6417 return SDValue(N, 0); 6418 6419 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 6420 if (N0.getOpcode() == ISD::SHL) { 6421 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6422 ConstantSDNode *RHS) { 6423 APInt c1 = LHS->getAPIntValue(); 6424 APInt c2 = RHS->getAPIntValue(); 6425 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6426 return (c1 + c2).uge(OpSizeInBits); 6427 }; 6428 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6429 return DAG.getConstant(0, SDLoc(N), VT); 6430 6431 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6432 ConstantSDNode *RHS) { 6433 APInt c1 = LHS->getAPIntValue(); 6434 APInt c2 = RHS->getAPIntValue(); 6435 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6436 return (c1 + c2).ult(OpSizeInBits); 6437 }; 6438 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6439 SDLoc DL(N); 6440 EVT ShiftVT = N1.getValueType(); 6441 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6442 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 6443 } 6444 } 6445 6446 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 6447 // For this to be valid, the second form must not preserve any of the bits 6448 // that are shifted out by the inner shift in the first form. This means 6449 // the outer shift size must be >= the number of bits added by the ext. 6450 // As a corollary, we don't care what kind of ext it is. 6451 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 6452 N0.getOpcode() == ISD::ANY_EXTEND || 6453 N0.getOpcode() == ISD::SIGN_EXTEND) && 6454 N0.getOperand(0).getOpcode() == ISD::SHL) { 6455 SDValue N0Op0 = N0.getOperand(0); 6456 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6457 APInt c1 = N0Op0C1->getAPIntValue(); 6458 APInt c2 = N1C->getAPIntValue(); 6459 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6460 6461 EVT InnerShiftVT = N0Op0.getValueType(); 6462 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6463 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 6464 SDLoc DL(N0); 6465 APInt Sum = c1 + c2; 6466 if (Sum.uge(OpSizeInBits)) 6467 return DAG.getConstant(0, DL, VT); 6468 6469 return DAG.getNode( 6470 ISD::SHL, DL, VT, 6471 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 6472 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 6473 } 6474 } 6475 } 6476 6477 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 6478 // Only fold this if the inner zext has no other uses to avoid increasing 6479 // the total number of instructions. 6480 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 6481 N0.getOperand(0).getOpcode() == ISD::SRL) { 6482 SDValue N0Op0 = N0.getOperand(0); 6483 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6484 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 6485 uint64_t c1 = N0Op0C1->getZExtValue(); 6486 uint64_t c2 = N1C->getZExtValue(); 6487 if (c1 == c2) { 6488 SDValue NewOp0 = N0.getOperand(0); 6489 EVT CountVT = NewOp0.getOperand(1).getValueType(); 6490 SDLoc DL(N); 6491 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 6492 NewOp0, 6493 DAG.getConstant(c2, DL, CountVT)); 6494 AddToWorklist(NewSHL.getNode()); 6495 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 6496 } 6497 } 6498 } 6499 } 6500 6501 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 6502 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 6503 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 6504 N0->getFlags().hasExact()) { 6505 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6506 uint64_t C1 = N0C1->getZExtValue(); 6507 uint64_t C2 = N1C->getZExtValue(); 6508 SDLoc DL(N); 6509 if (C1 <= C2) 6510 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6511 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 6512 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 6513 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 6514 } 6515 } 6516 6517 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 6518 // (and (srl x, (sub c1, c2), MASK) 6519 // Only fold this if the inner shift has no other uses -- if it does, folding 6520 // this will increase the total number of instructions. 6521 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6522 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6523 uint64_t c1 = N0C1->getZExtValue(); 6524 if (c1 < OpSizeInBits) { 6525 uint64_t c2 = N1C->getZExtValue(); 6526 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 6527 SDValue Shift; 6528 if (c2 > c1) { 6529 Mask <<= c2 - c1; 6530 SDLoc DL(N); 6531 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6532 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 6533 } else { 6534 Mask.lshrInPlace(c1 - c2); 6535 SDLoc DL(N); 6536 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 6537 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 6538 } 6539 SDLoc DL(N0); 6540 return DAG.getNode(ISD::AND, DL, VT, Shift, 6541 DAG.getConstant(Mask, DL, VT)); 6542 } 6543 } 6544 } 6545 6546 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 6547 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 6548 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 6549 SDLoc DL(N); 6550 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 6551 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 6552 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 6553 } 6554 6555 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 6556 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 6557 // Variant of version done on multiply, except mul by a power of 2 is turned 6558 // into a shift. 6559 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 6560 N0.getNode()->hasOneUse() && 6561 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6562 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 6563 TLI.isDesirableToCommuteWithShift(N, Level)) { 6564 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 6565 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6566 AddToWorklist(Shl0.getNode()); 6567 AddToWorklist(Shl1.getNode()); 6568 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 6569 } 6570 6571 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 6572 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 6573 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6574 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 6575 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6576 if (isConstantOrConstantVector(Shl)) 6577 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 6578 } 6579 6580 if (N1C && !N1C->isOpaque()) 6581 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 6582 return NewSHL; 6583 6584 return SDValue(); 6585 } 6586 6587 SDValue DAGCombiner::visitSRA(SDNode *N) { 6588 SDValue N0 = N->getOperand(0); 6589 SDValue N1 = N->getOperand(1); 6590 EVT VT = N0.getValueType(); 6591 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6592 6593 // Arithmetic shifting an all-sign-bit value is a no-op. 6594 // fold (sra 0, x) -> 0 6595 // fold (sra -1, x) -> -1 6596 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 6597 return N0; 6598 6599 // fold vector ops 6600 if (VT.isVector()) 6601 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6602 return FoldedVOp; 6603 6604 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6605 6606 // fold (sra c1, c2) -> (sra c1, c2) 6607 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6608 if (N0C && N1C && !N1C->isOpaque()) 6609 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 6610 // fold (sra x, c >= size(x)) -> undef 6611 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6612 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6613 return Val->getAPIntValue().uge(OpSizeInBits); 6614 }; 6615 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6616 return DAG.getUNDEF(VT); 6617 // fold (sra x, 0) -> x 6618 if (N1C && N1C->isNullValue()) 6619 return N0; 6620 6621 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6622 return NewSel; 6623 6624 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 6625 // sext_inreg. 6626 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 6627 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 6628 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 6629 if (VT.isVector()) 6630 ExtVT = EVT::getVectorVT(*DAG.getContext(), 6631 ExtVT, VT.getVectorNumElements()); 6632 if ((!LegalOperations || 6633 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 6634 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6635 N0.getOperand(0), DAG.getValueType(ExtVT)); 6636 } 6637 6638 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 6639 // clamp (add c1, c2) to max shift. 6640 if (N0.getOpcode() == ISD::SRA) { 6641 SDLoc DL(N); 6642 EVT ShiftVT = N1.getValueType(); 6643 EVT ShiftSVT = ShiftVT.getScalarType(); 6644 SmallVector<SDValue, 16> ShiftValues; 6645 6646 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { 6647 APInt c1 = LHS->getAPIntValue(); 6648 APInt c2 = RHS->getAPIntValue(); 6649 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6650 APInt Sum = c1 + c2; 6651 unsigned ShiftSum = 6652 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); 6653 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); 6654 return true; 6655 }; 6656 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { 6657 SDValue ShiftValue; 6658 if (VT.isVector()) 6659 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); 6660 else 6661 ShiftValue = ShiftValues[0]; 6662 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); 6663 } 6664 } 6665 6666 // fold (sra (shl X, m), (sub result_size, n)) 6667 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 6668 // result_size - n != m. 6669 // If truncate is free for the target sext(shl) is likely to result in better 6670 // code. 6671 if (N0.getOpcode() == ISD::SHL && N1C) { 6672 // Get the two constanst of the shifts, CN0 = m, CN = n. 6673 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 6674 if (N01C) { 6675 LLVMContext &Ctx = *DAG.getContext(); 6676 // Determine what the truncate's result bitsize and type would be. 6677 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 6678 6679 if (VT.isVector()) 6680 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 6681 6682 // Determine the residual right-shift amount. 6683 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 6684 6685 // If the shift is not a no-op (in which case this should be just a sign 6686 // extend already), the truncated to type is legal, sign_extend is legal 6687 // on that type, and the truncate to that type is both legal and free, 6688 // perform the transform. 6689 if ((ShiftAmt > 0) && 6690 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 6691 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 6692 TLI.isTruncateFree(VT, TruncVT)) { 6693 SDLoc DL(N); 6694 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 6695 getShiftAmountTy(N0.getOperand(0).getValueType())); 6696 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 6697 N0.getOperand(0), Amt); 6698 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 6699 Shift); 6700 return DAG.getNode(ISD::SIGN_EXTEND, DL, 6701 N->getValueType(0), Trunc); 6702 } 6703 } 6704 } 6705 6706 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 6707 if (N1.getOpcode() == ISD::TRUNCATE && 6708 N1.getOperand(0).getOpcode() == ISD::AND) { 6709 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6710 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 6711 } 6712 6713 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 6714 // if c1 is equal to the number of bits the trunc removes 6715 if (N0.getOpcode() == ISD::TRUNCATE && 6716 (N0.getOperand(0).getOpcode() == ISD::SRL || 6717 N0.getOperand(0).getOpcode() == ISD::SRA) && 6718 N0.getOperand(0).hasOneUse() && 6719 N0.getOperand(0).getOperand(1).hasOneUse() && 6720 N1C) { 6721 SDValue N0Op0 = N0.getOperand(0); 6722 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 6723 unsigned LargeShiftVal = LargeShift->getZExtValue(); 6724 EVT LargeVT = N0Op0.getValueType(); 6725 6726 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 6727 SDLoc DL(N); 6728 SDValue Amt = 6729 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 6730 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 6731 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 6732 N0Op0.getOperand(0), Amt); 6733 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 6734 } 6735 } 6736 } 6737 6738 // Simplify, based on bits shifted out of the LHS. 6739 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6740 return SDValue(N, 0); 6741 6742 // If the sign bit is known to be zero, switch this to a SRL. 6743 if (DAG.SignBitIsZero(N0)) 6744 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 6745 6746 if (N1C && !N1C->isOpaque()) 6747 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 6748 return NewSRA; 6749 6750 return SDValue(); 6751 } 6752 6753 SDValue DAGCombiner::visitSRL(SDNode *N) { 6754 SDValue N0 = N->getOperand(0); 6755 SDValue N1 = N->getOperand(1); 6756 EVT VT = N0.getValueType(); 6757 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6758 6759 // fold vector ops 6760 if (VT.isVector()) 6761 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6762 return FoldedVOp; 6763 6764 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6765 6766 // fold (srl c1, c2) -> c1 >>u c2 6767 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6768 if (N0C && N1C && !N1C->isOpaque()) 6769 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 6770 // fold (srl 0, x) -> 0 6771 if (isNullConstantOrNullSplatConstant(N0)) 6772 return N0; 6773 // fold (srl x, c >= size(x)) -> undef 6774 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 6775 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 6776 return Val->getAPIntValue().uge(OpSizeInBits); 6777 }; 6778 if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig)) 6779 return DAG.getUNDEF(VT); 6780 // fold (srl x, 0) -> x 6781 if (N1C && N1C->isNullValue()) 6782 return N0; 6783 6784 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6785 return NewSel; 6786 6787 // if (srl x, c) is known to be zero, return 0 6788 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 6789 APInt::getAllOnesValue(OpSizeInBits))) 6790 return DAG.getConstant(0, SDLoc(N), VT); 6791 6792 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 6793 if (N0.getOpcode() == ISD::SRL) { 6794 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6795 ConstantSDNode *RHS) { 6796 APInt c1 = LHS->getAPIntValue(); 6797 APInt c2 = RHS->getAPIntValue(); 6798 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6799 return (c1 + c2).uge(OpSizeInBits); 6800 }; 6801 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6802 return DAG.getConstant(0, SDLoc(N), VT); 6803 6804 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6805 ConstantSDNode *RHS) { 6806 APInt c1 = LHS->getAPIntValue(); 6807 APInt c2 = RHS->getAPIntValue(); 6808 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6809 return (c1 + c2).ult(OpSizeInBits); 6810 }; 6811 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6812 SDLoc DL(N); 6813 EVT ShiftVT = N1.getValueType(); 6814 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6815 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 6816 } 6817 } 6818 6819 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 6820 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 6821 N0.getOperand(0).getOpcode() == ISD::SRL) { 6822 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 6823 uint64_t c1 = N001C->getZExtValue(); 6824 uint64_t c2 = N1C->getZExtValue(); 6825 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 6826 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 6827 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6828 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 6829 if (c1 + OpSizeInBits == InnerShiftSize) { 6830 SDLoc DL(N0); 6831 if (c1 + c2 >= InnerShiftSize) 6832 return DAG.getConstant(0, DL, VT); 6833 return DAG.getNode(ISD::TRUNCATE, DL, VT, 6834 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 6835 N0.getOperand(0).getOperand(0), 6836 DAG.getConstant(c1 + c2, DL, 6837 ShiftCountVT))); 6838 } 6839 } 6840 } 6841 6842 // fold (srl (shl x, c), c) -> (and x, cst2) 6843 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 6844 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 6845 SDLoc DL(N); 6846 SDValue Mask = 6847 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 6848 AddToWorklist(Mask.getNode()); 6849 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 6850 } 6851 6852 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 6853 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 6854 // Shifting in all undef bits? 6855 EVT SmallVT = N0.getOperand(0).getValueType(); 6856 unsigned BitSize = SmallVT.getScalarSizeInBits(); 6857 if (N1C->getZExtValue() >= BitSize) 6858 return DAG.getUNDEF(VT); 6859 6860 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 6861 uint64_t ShiftAmt = N1C->getZExtValue(); 6862 SDLoc DL0(N0); 6863 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 6864 N0.getOperand(0), 6865 DAG.getConstant(ShiftAmt, DL0, 6866 getShiftAmountTy(SmallVT))); 6867 AddToWorklist(SmallShift.getNode()); 6868 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 6869 SDLoc DL(N); 6870 return DAG.getNode(ISD::AND, DL, VT, 6871 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 6872 DAG.getConstant(Mask, DL, VT)); 6873 } 6874 } 6875 6876 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 6877 // bit, which is unmodified by sra. 6878 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 6879 if (N0.getOpcode() == ISD::SRA) 6880 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 6881 } 6882 6883 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 6884 if (N1C && N0.getOpcode() == ISD::CTLZ && 6885 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 6886 KnownBits Known; 6887 DAG.computeKnownBits(N0.getOperand(0), Known); 6888 6889 // If any of the input bits are KnownOne, then the input couldn't be all 6890 // zeros, thus the result of the srl will always be zero. 6891 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 6892 6893 // If all of the bits input the to ctlz node are known to be zero, then 6894 // the result of the ctlz is "32" and the result of the shift is one. 6895 APInt UnknownBits = ~Known.Zero; 6896 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 6897 6898 // Otherwise, check to see if there is exactly one bit input to the ctlz. 6899 if (UnknownBits.isPowerOf2()) { 6900 // Okay, we know that only that the single bit specified by UnknownBits 6901 // could be set on input to the CTLZ node. If this bit is set, the SRL 6902 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 6903 // to an SRL/XOR pair, which is likely to simplify more. 6904 unsigned ShAmt = UnknownBits.countTrailingZeros(); 6905 SDValue Op = N0.getOperand(0); 6906 6907 if (ShAmt) { 6908 SDLoc DL(N0); 6909 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 6910 DAG.getConstant(ShAmt, DL, 6911 getShiftAmountTy(Op.getValueType()))); 6912 AddToWorklist(Op.getNode()); 6913 } 6914 6915 SDLoc DL(N); 6916 return DAG.getNode(ISD::XOR, DL, VT, 6917 Op, DAG.getConstant(1, DL, VT)); 6918 } 6919 } 6920 6921 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 6922 if (N1.getOpcode() == ISD::TRUNCATE && 6923 N1.getOperand(0).getOpcode() == ISD::AND) { 6924 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6925 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 6926 } 6927 6928 // fold operands of srl based on knowledge that the low bits are not 6929 // demanded. 6930 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6931 return SDValue(N, 0); 6932 6933 if (N1C && !N1C->isOpaque()) 6934 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 6935 return NewSRL; 6936 6937 // Attempt to convert a srl of a load into a narrower zero-extending load. 6938 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6939 return NarrowLoad; 6940 6941 // Here is a common situation. We want to optimize: 6942 // 6943 // %a = ... 6944 // %b = and i32 %a, 2 6945 // %c = srl i32 %b, 1 6946 // brcond i32 %c ... 6947 // 6948 // into 6949 // 6950 // %a = ... 6951 // %b = and %a, 2 6952 // %c = setcc eq %b, 0 6953 // brcond %c ... 6954 // 6955 // However when after the source operand of SRL is optimized into AND, the SRL 6956 // itself may not be optimized further. Look for it and add the BRCOND into 6957 // the worklist. 6958 if (N->hasOneUse()) { 6959 SDNode *Use = *N->use_begin(); 6960 if (Use->getOpcode() == ISD::BRCOND) 6961 AddToWorklist(Use); 6962 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 6963 // Also look pass the truncate. 6964 Use = *Use->use_begin(); 6965 if (Use->getOpcode() == ISD::BRCOND) 6966 AddToWorklist(Use); 6967 } 6968 } 6969 6970 return SDValue(); 6971 } 6972 6973 SDValue DAGCombiner::visitABS(SDNode *N) { 6974 SDValue N0 = N->getOperand(0); 6975 EVT VT = N->getValueType(0); 6976 6977 // fold (abs c1) -> c2 6978 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6979 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6980 // fold (abs (abs x)) -> (abs x) 6981 if (N0.getOpcode() == ISD::ABS) 6982 return N0; 6983 // fold (abs x) -> x iff not-negative 6984 if (DAG.SignBitIsZero(N0)) 6985 return N0; 6986 return SDValue(); 6987 } 6988 6989 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6990 SDValue N0 = N->getOperand(0); 6991 EVT VT = N->getValueType(0); 6992 6993 // fold (bswap c1) -> c2 6994 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6995 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6996 // fold (bswap (bswap x)) -> x 6997 if (N0.getOpcode() == ISD::BSWAP) 6998 return N0->getOperand(0); 6999 return SDValue(); 7000 } 7001 7002 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 7003 SDValue N0 = N->getOperand(0); 7004 EVT VT = N->getValueType(0); 7005 7006 // fold (bitreverse c1) -> c2 7007 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7008 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 7009 // fold (bitreverse (bitreverse x)) -> x 7010 if (N0.getOpcode() == ISD::BITREVERSE) 7011 return N0.getOperand(0); 7012 return SDValue(); 7013 } 7014 7015 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 7016 SDValue N0 = N->getOperand(0); 7017 EVT VT = N->getValueType(0); 7018 7019 // fold (ctlz c1) -> c2 7020 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7021 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 7022 7023 // If the value is known never to be zero, switch to the undef version. 7024 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 7025 if (DAG.isKnownNeverZero(N0)) 7026 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7027 } 7028 7029 return SDValue(); 7030 } 7031 7032 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 7033 SDValue N0 = N->getOperand(0); 7034 EVT VT = N->getValueType(0); 7035 7036 // fold (ctlz_zero_undef c1) -> c2 7037 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7038 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7039 return SDValue(); 7040 } 7041 7042 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 7043 SDValue N0 = N->getOperand(0); 7044 EVT VT = N->getValueType(0); 7045 7046 // fold (cttz c1) -> c2 7047 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7048 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 7049 7050 // If the value is known never to be zero, switch to the undef version. 7051 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 7052 if (DAG.isKnownNeverZero(N0)) 7053 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7054 } 7055 7056 return SDValue(); 7057 } 7058 7059 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 7060 SDValue N0 = N->getOperand(0); 7061 EVT VT = N->getValueType(0); 7062 7063 // fold (cttz_zero_undef c1) -> c2 7064 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7065 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7066 return SDValue(); 7067 } 7068 7069 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 7070 SDValue N0 = N->getOperand(0); 7071 EVT VT = N->getValueType(0); 7072 7073 // fold (ctpop c1) -> c2 7074 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7075 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 7076 return SDValue(); 7077 } 7078 7079 // FIXME: This should be checking for no signed zeros on individual operands, as 7080 // well as no nans. 7081 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, SDValue RHS) { 7082 const TargetOptions &Options = DAG.getTarget().Options; 7083 EVT VT = LHS.getValueType(); 7084 7085 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && 7086 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); 7087 } 7088 7089 /// Generate Min/Max node 7090 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 7091 SDValue RHS, SDValue True, SDValue False, 7092 ISD::CondCode CC, const TargetLowering &TLI, 7093 SelectionDAG &DAG) { 7094 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 7095 return SDValue(); 7096 7097 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 7098 switch (CC) { 7099 case ISD::SETOLT: 7100 case ISD::SETOLE: 7101 case ISD::SETLT: 7102 case ISD::SETLE: 7103 case ISD::SETULT: 7104 case ISD::SETULE: { 7105 // Since it's known never nan to get here already, either fminnum or 7106 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is 7107 // expanded in terms of it. 7108 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7109 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 7110 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 7111 7112 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 7113 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7114 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7115 return SDValue(); 7116 } 7117 case ISD::SETOGT: 7118 case ISD::SETOGE: 7119 case ISD::SETGT: 7120 case ISD::SETGE: 7121 case ISD::SETUGT: 7122 case ISD::SETUGE: { 7123 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 7124 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 7125 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 7126 7127 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 7128 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7129 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7130 return SDValue(); 7131 } 7132 default: 7133 return SDValue(); 7134 } 7135 } 7136 7137 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 7138 SDValue Cond = N->getOperand(0); 7139 SDValue N1 = N->getOperand(1); 7140 SDValue N2 = N->getOperand(2); 7141 EVT VT = N->getValueType(0); 7142 EVT CondVT = Cond.getValueType(); 7143 SDLoc DL(N); 7144 7145 if (!VT.isInteger()) 7146 return SDValue(); 7147 7148 auto *C1 = dyn_cast<ConstantSDNode>(N1); 7149 auto *C2 = dyn_cast<ConstantSDNode>(N2); 7150 if (!C1 || !C2) 7151 return SDValue(); 7152 7153 // Only do this before legalization to avoid conflicting with target-specific 7154 // transforms in the other direction (create a select from a zext/sext). There 7155 // is also a target-independent combine here in DAGCombiner in the other 7156 // direction for (select Cond, -1, 0) when the condition is not i1. 7157 if (CondVT == MVT::i1 && !LegalOperations) { 7158 if (C1->isNullValue() && C2->isOne()) { 7159 // select Cond, 0, 1 --> zext (!Cond) 7160 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7161 if (VT != MVT::i1) 7162 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 7163 return NotCond; 7164 } 7165 if (C1->isNullValue() && C2->isAllOnesValue()) { 7166 // select Cond, 0, -1 --> sext (!Cond) 7167 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7168 if (VT != MVT::i1) 7169 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 7170 return NotCond; 7171 } 7172 if (C1->isOne() && C2->isNullValue()) { 7173 // select Cond, 1, 0 --> zext (Cond) 7174 if (VT != MVT::i1) 7175 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7176 return Cond; 7177 } 7178 if (C1->isAllOnesValue() && C2->isNullValue()) { 7179 // select Cond, -1, 0 --> sext (Cond) 7180 if (VT != MVT::i1) 7181 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7182 return Cond; 7183 } 7184 7185 // For any constants that differ by 1, we can transform the select into an 7186 // extend and add. Use a target hook because some targets may prefer to 7187 // transform in the other direction. 7188 if (TLI.convertSelectOfConstantsToMath(VT)) { 7189 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 7190 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 7191 if (VT != MVT::i1) 7192 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7193 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7194 } 7195 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 7196 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 7197 if (VT != MVT::i1) 7198 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7199 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7200 } 7201 } 7202 7203 return SDValue(); 7204 } 7205 7206 // fold (select Cond, 0, 1) -> (xor Cond, 1) 7207 // We can't do this reliably if integer based booleans have different contents 7208 // to floating point based booleans. This is because we can't tell whether we 7209 // have an integer-based boolean or a floating-point-based boolean unless we 7210 // can find the SETCC that produced it and inspect its operands. This is 7211 // fairly easy if C is the SETCC node, but it can potentially be 7212 // undiscoverable (or not reasonably discoverable). For example, it could be 7213 // in another basic block or it could require searching a complicated 7214 // expression. 7215 if (CondVT.isInteger() && 7216 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 7217 TargetLowering::ZeroOrOneBooleanContent && 7218 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 7219 TargetLowering::ZeroOrOneBooleanContent && 7220 C1->isNullValue() && C2->isOne()) { 7221 SDValue NotCond = 7222 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 7223 if (VT.bitsEq(CondVT)) 7224 return NotCond; 7225 return DAG.getZExtOrTrunc(NotCond, DL, VT); 7226 } 7227 7228 return SDValue(); 7229 } 7230 7231 SDValue DAGCombiner::visitSELECT(SDNode *N) { 7232 SDValue N0 = N->getOperand(0); 7233 SDValue N1 = N->getOperand(1); 7234 SDValue N2 = N->getOperand(2); 7235 EVT VT = N->getValueType(0); 7236 EVT VT0 = N0.getValueType(); 7237 SDLoc DL(N); 7238 7239 // fold (select C, X, X) -> X 7240 if (N1 == N2) 7241 return N1; 7242 7243 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 7244 // fold (select true, X, Y) -> X 7245 // fold (select false, X, Y) -> Y 7246 return !N0C->isNullValue() ? N1 : N2; 7247 } 7248 7249 // fold (select X, X, Y) -> (or X, Y) 7250 // fold (select X, 1, Y) -> (or C, Y) 7251 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 7252 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 7253 7254 if (SDValue V = foldSelectOfConstants(N)) 7255 return V; 7256 7257 // fold (select C, 0, X) -> (and (not C), X) 7258 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 7259 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7260 AddToWorklist(NOTNode.getNode()); 7261 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 7262 } 7263 // fold (select C, X, 1) -> (or (not C), X) 7264 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 7265 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7266 AddToWorklist(NOTNode.getNode()); 7267 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 7268 } 7269 // fold (select X, Y, X) -> (and X, Y) 7270 // fold (select X, Y, 0) -> (and X, Y) 7271 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 7272 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 7273 7274 // If we can fold this based on the true/false value, do so. 7275 if (SimplifySelectOps(N, N1, N2)) 7276 return SDValue(N, 0); // Don't revisit N. 7277 7278 if (VT0 == MVT::i1) { 7279 // The code in this block deals with the following 2 equivalences: 7280 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 7281 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 7282 // The target can specify its preferred form with the 7283 // shouldNormalizeToSelectSequence() callback. However we always transform 7284 // to the right anyway if we find the inner select exists in the DAG anyway 7285 // and we always transform to the left side if we know that we can further 7286 // optimize the combination of the conditions. 7287 bool normalizeToSequence = 7288 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 7289 // select (and Cond0, Cond1), X, Y 7290 // -> select Cond0, (select Cond1, X, Y), Y 7291 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 7292 SDValue Cond0 = N0->getOperand(0); 7293 SDValue Cond1 = N0->getOperand(1); 7294 SDValue InnerSelect = 7295 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7296 if (normalizeToSequence || !InnerSelect.use_empty()) 7297 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 7298 InnerSelect, N2); 7299 } 7300 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 7301 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 7302 SDValue Cond0 = N0->getOperand(0); 7303 SDValue Cond1 = N0->getOperand(1); 7304 SDValue InnerSelect = 7305 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7306 if (normalizeToSequence || !InnerSelect.use_empty()) 7307 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 7308 InnerSelect); 7309 } 7310 7311 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 7312 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 7313 SDValue N1_0 = N1->getOperand(0); 7314 SDValue N1_1 = N1->getOperand(1); 7315 SDValue N1_2 = N1->getOperand(2); 7316 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 7317 // Create the actual and node if we can generate good code for it. 7318 if (!normalizeToSequence) { 7319 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 7320 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 7321 } 7322 // Otherwise see if we can optimize the "and" to a better pattern. 7323 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 7324 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 7325 N2); 7326 } 7327 } 7328 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 7329 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 7330 SDValue N2_0 = N2->getOperand(0); 7331 SDValue N2_1 = N2->getOperand(1); 7332 SDValue N2_2 = N2->getOperand(2); 7333 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 7334 // Create the actual or node if we can generate good code for it. 7335 if (!normalizeToSequence) { 7336 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 7337 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 7338 } 7339 // Otherwise see if we can optimize to a better pattern. 7340 if (SDValue Combined = visitORLike(N0, N2_0, N)) 7341 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 7342 N2_2); 7343 } 7344 } 7345 } 7346 7347 if (VT0 == MVT::i1) { 7348 // select (not Cond), N1, N2 -> select Cond, N2, N1 7349 if (isBitwiseNot(N0)) 7350 return DAG.getNode(ISD::SELECT, DL, VT, N0->getOperand(0), N2, N1); 7351 } 7352 7353 // Fold selects based on a setcc into other things, such as min/max/abs. 7354 if (N0.getOpcode() == ISD::SETCC) { 7355 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1); 7356 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7357 7358 // select (fcmp lt x, y), x, y -> fminnum x, y 7359 // select (fcmp gt x, y), x, y -> fmaxnum x, y 7360 // 7361 // This is OK if we don't care what happens if either operand is a NaN. 7362 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2)) 7363 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, 7364 CC, TLI, DAG)) 7365 return FMinMax; 7366 7367 // Use 'unsigned add with overflow' to optimize an unsigned saturating add. 7368 // This is conservatively limited to pre-legal-operations to give targets 7369 // a chance to reverse the transform if they want to do that. Also, it is 7370 // unlikely that the pattern would be formed late, so it's probably not 7371 // worth going through the other checks. 7372 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) && 7373 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) && 7374 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) { 7375 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1)); 7376 auto *NotC = dyn_cast<ConstantSDNode>(Cond1); 7377 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) { 7378 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) --> 7379 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0 7380 // 7381 // The IR equivalent of this transform would have this form: 7382 // %a = add %x, C 7383 // %c = icmp ugt %x, ~C 7384 // %r = select %c, -1, %a 7385 // => 7386 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C) 7387 // %u0 = extractvalue %u, 0 7388 // %u1 = extractvalue %u, 1 7389 // %r = select %u1, -1, %u0 7390 SDVTList VTs = DAG.getVTList(VT, VT0); 7391 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1)); 7392 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0)); 7393 } 7394 } 7395 7396 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) || 7397 (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) 7398 return DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, N2, 7399 N0.getOperand(2)); 7400 7401 return SimplifySelect(DL, N0, N1, N2); 7402 } 7403 7404 return SDValue(); 7405 } 7406 7407 static 7408 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 7409 SDLoc DL(N); 7410 EVT LoVT, HiVT; 7411 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 7412 7413 // Split the inputs. 7414 SDValue Lo, Hi, LL, LH, RL, RH; 7415 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 7416 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 7417 7418 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 7419 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 7420 7421 return std::make_pair(Lo, Hi); 7422 } 7423 7424 // This function assumes all the vselect's arguments are CONCAT_VECTOR 7425 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 7426 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 7427 SDLoc DL(N); 7428 SDValue Cond = N->getOperand(0); 7429 SDValue LHS = N->getOperand(1); 7430 SDValue RHS = N->getOperand(2); 7431 EVT VT = N->getValueType(0); 7432 int NumElems = VT.getVectorNumElements(); 7433 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 7434 RHS.getOpcode() == ISD::CONCAT_VECTORS && 7435 Cond.getOpcode() == ISD::BUILD_VECTOR); 7436 7437 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 7438 // binary ones here. 7439 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 7440 return SDValue(); 7441 7442 // We're sure we have an even number of elements due to the 7443 // concat_vectors we have as arguments to vselect. 7444 // Skip BV elements until we find one that's not an UNDEF 7445 // After we find an UNDEF element, keep looping until we get to half the 7446 // length of the BV and see if all the non-undef nodes are the same. 7447 ConstantSDNode *BottomHalf = nullptr; 7448 for (int i = 0; i < NumElems / 2; ++i) { 7449 if (Cond->getOperand(i)->isUndef()) 7450 continue; 7451 7452 if (BottomHalf == nullptr) 7453 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7454 else if (Cond->getOperand(i).getNode() != BottomHalf) 7455 return SDValue(); 7456 } 7457 7458 // Do the same for the second half of the BuildVector 7459 ConstantSDNode *TopHalf = nullptr; 7460 for (int i = NumElems / 2; i < NumElems; ++i) { 7461 if (Cond->getOperand(i)->isUndef()) 7462 continue; 7463 7464 if (TopHalf == nullptr) 7465 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7466 else if (Cond->getOperand(i).getNode() != TopHalf) 7467 return SDValue(); 7468 } 7469 7470 assert(TopHalf && BottomHalf && 7471 "One half of the selector was all UNDEFs and the other was all the " 7472 "same value. This should have been addressed before this function."); 7473 return DAG.getNode( 7474 ISD::CONCAT_VECTORS, DL, VT, 7475 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 7476 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 7477 } 7478 7479 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 7480 if (Level >= AfterLegalizeTypes) 7481 return SDValue(); 7482 7483 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 7484 SDValue Mask = MSC->getMask(); 7485 SDValue Data = MSC->getValue(); 7486 SDLoc DL(N); 7487 7488 // If the MSCATTER data type requires splitting and the mask is provided by a 7489 // SETCC, then split both nodes and its operands before legalization. This 7490 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7491 // and enables future optimizations (e.g. min/max pattern matching on X86). 7492 if (Mask.getOpcode() != ISD::SETCC) 7493 return SDValue(); 7494 7495 // Check if any splitting is required. 7496 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 7497 TargetLowering::TypeSplitVector) 7498 return SDValue(); 7499 SDValue MaskLo, MaskHi; 7500 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7501 7502 EVT LoVT, HiVT; 7503 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 7504 7505 SDValue Chain = MSC->getChain(); 7506 7507 EVT MemoryVT = MSC->getMemoryVT(); 7508 unsigned Alignment = MSC->getOriginalAlignment(); 7509 7510 EVT LoMemVT, HiMemVT; 7511 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7512 7513 SDValue DataLo, DataHi; 7514 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7515 7516 SDValue Scale = MSC->getScale(); 7517 SDValue BasePtr = MSC->getBasePtr(); 7518 SDValue IndexLo, IndexHi; 7519 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 7520 7521 MachineMemOperand *MMO = DAG.getMachineFunction(). 7522 getMachineMemOperand(MSC->getPointerInfo(), 7523 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7524 Alignment, MSC->getAAInfo(), MSC->getRanges()); 7525 7526 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale }; 7527 SDValue Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), 7528 DataLo.getValueType(), DL, OpsLo, MMO); 7529 7530 // The order of the Scatter operation after split is well defined. The "Hi" 7531 // part comes after the "Lo". So these two operations should be chained one 7532 // after another. 7533 SDValue OpsHi[] = { Lo, DataHi, MaskHi, BasePtr, IndexHi, Scale }; 7534 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 7535 DL, OpsHi, MMO); 7536 } 7537 7538 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 7539 if (Level >= AfterLegalizeTypes) 7540 return SDValue(); 7541 7542 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 7543 SDValue Mask = MST->getMask(); 7544 SDValue Data = MST->getValue(); 7545 EVT VT = Data.getValueType(); 7546 SDLoc DL(N); 7547 7548 // If the MSTORE data type requires splitting and the mask is provided by a 7549 // SETCC, then split both nodes and its operands before legalization. This 7550 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7551 // and enables future optimizations (e.g. min/max pattern matching on X86). 7552 if (Mask.getOpcode() == ISD::SETCC) { 7553 // Check if any splitting is required. 7554 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7555 TargetLowering::TypeSplitVector) 7556 return SDValue(); 7557 7558 SDValue MaskLo, MaskHi, Lo, Hi; 7559 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7560 7561 SDValue Chain = MST->getChain(); 7562 SDValue Ptr = MST->getBasePtr(); 7563 7564 EVT MemoryVT = MST->getMemoryVT(); 7565 unsigned Alignment = MST->getOriginalAlignment(); 7566 7567 // if Alignment is equal to the vector size, 7568 // take the half of it for the second part 7569 unsigned SecondHalfAlignment = 7570 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 7571 7572 EVT LoMemVT, HiMemVT; 7573 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7574 7575 SDValue DataLo, DataHi; 7576 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7577 7578 MachineMemOperand *MMO = DAG.getMachineFunction(). 7579 getMachineMemOperand(MST->getPointerInfo(), 7580 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7581 Alignment, MST->getAAInfo(), MST->getRanges()); 7582 7583 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 7584 MST->isTruncatingStore(), 7585 MST->isCompressingStore()); 7586 7587 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7588 MST->isCompressingStore()); 7589 unsigned HiOffset = LoMemVT.getStoreSize(); 7590 7591 MMO = DAG.getMachineFunction().getMachineMemOperand( 7592 MST->getPointerInfo().getWithOffset(HiOffset), 7593 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment, 7594 MST->getAAInfo(), MST->getRanges()); 7595 7596 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 7597 MST->isTruncatingStore(), 7598 MST->isCompressingStore()); 7599 7600 AddToWorklist(Lo.getNode()); 7601 AddToWorklist(Hi.getNode()); 7602 7603 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 7604 } 7605 return SDValue(); 7606 } 7607 7608 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 7609 if (Level >= AfterLegalizeTypes) 7610 return SDValue(); 7611 7612 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 7613 SDValue Mask = MGT->getMask(); 7614 SDLoc DL(N); 7615 7616 // If the MGATHER result requires splitting and the mask is provided by a 7617 // SETCC, then split both nodes and its operands before legalization. This 7618 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7619 // and enables future optimizations (e.g. min/max pattern matching on X86). 7620 7621 if (Mask.getOpcode() != ISD::SETCC) 7622 return SDValue(); 7623 7624 EVT VT = N->getValueType(0); 7625 7626 // Check if any splitting is required. 7627 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7628 TargetLowering::TypeSplitVector) 7629 return SDValue(); 7630 7631 SDValue MaskLo, MaskHi, Lo, Hi; 7632 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7633 7634 SDValue PassThru = MGT->getPassThru(); 7635 SDValue PassThruLo, PassThruHi; 7636 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 7637 7638 EVT LoVT, HiVT; 7639 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 7640 7641 SDValue Chain = MGT->getChain(); 7642 EVT MemoryVT = MGT->getMemoryVT(); 7643 unsigned Alignment = MGT->getOriginalAlignment(); 7644 7645 EVT LoMemVT, HiMemVT; 7646 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7647 7648 SDValue Scale = MGT->getScale(); 7649 SDValue BasePtr = MGT->getBasePtr(); 7650 SDValue Index = MGT->getIndex(); 7651 SDValue IndexLo, IndexHi; 7652 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 7653 7654 MachineMemOperand *MMO = DAG.getMachineFunction(). 7655 getMachineMemOperand(MGT->getPointerInfo(), 7656 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7657 Alignment, MGT->getAAInfo(), MGT->getRanges()); 7658 7659 SDValue OpsLo[] = { Chain, PassThruLo, MaskLo, BasePtr, IndexLo, Scale }; 7660 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 7661 MMO); 7662 7663 SDValue OpsHi[] = { Chain, PassThruHi, MaskHi, BasePtr, IndexHi, Scale }; 7664 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 7665 MMO); 7666 7667 AddToWorklist(Lo.getNode()); 7668 AddToWorklist(Hi.getNode()); 7669 7670 // Build a factor node to remember that this load is independent of the 7671 // other one. 7672 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7673 Hi.getValue(1)); 7674 7675 // Legalized the chain result - switch anything that used the old chain to 7676 // use the new one. 7677 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 7678 7679 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7680 7681 SDValue RetOps[] = { GatherRes, Chain }; 7682 return DAG.getMergeValues(RetOps, DL); 7683 } 7684 7685 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 7686 if (Level >= AfterLegalizeTypes) 7687 return SDValue(); 7688 7689 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 7690 SDValue Mask = MLD->getMask(); 7691 SDLoc DL(N); 7692 7693 // If the MLOAD result requires splitting and the mask is provided by a 7694 // SETCC, then split both nodes and its operands before legalization. This 7695 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7696 // and enables future optimizations (e.g. min/max pattern matching on X86). 7697 if (Mask.getOpcode() == ISD::SETCC) { 7698 EVT VT = N->getValueType(0); 7699 7700 // Check if any splitting is required. 7701 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7702 TargetLowering::TypeSplitVector) 7703 return SDValue(); 7704 7705 SDValue MaskLo, MaskHi, Lo, Hi; 7706 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7707 7708 SDValue PassThru = MLD->getPassThru(); 7709 SDValue PassThruLo, PassThruHi; 7710 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 7711 7712 EVT LoVT, HiVT; 7713 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 7714 7715 SDValue Chain = MLD->getChain(); 7716 SDValue Ptr = MLD->getBasePtr(); 7717 EVT MemoryVT = MLD->getMemoryVT(); 7718 unsigned Alignment = MLD->getOriginalAlignment(); 7719 7720 // if Alignment is equal to the vector size, 7721 // take the half of it for the second part 7722 unsigned SecondHalfAlignment = 7723 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 7724 Alignment/2 : Alignment; 7725 7726 EVT LoMemVT, HiMemVT; 7727 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7728 7729 MachineMemOperand *MMO = DAG.getMachineFunction(). 7730 getMachineMemOperand(MLD->getPointerInfo(), 7731 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 7732 Alignment, MLD->getAAInfo(), MLD->getRanges()); 7733 7734 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, PassThruLo, LoMemVT, 7735 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7736 7737 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 7738 MLD->isExpandingLoad()); 7739 unsigned HiOffset = LoMemVT.getStoreSize(); 7740 7741 MMO = DAG.getMachineFunction().getMachineMemOperand( 7742 MLD->getPointerInfo().getWithOffset(HiOffset), 7743 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment, 7744 MLD->getAAInfo(), MLD->getRanges()); 7745 7746 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, PassThruHi, HiMemVT, 7747 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 7748 7749 AddToWorklist(Lo.getNode()); 7750 AddToWorklist(Hi.getNode()); 7751 7752 // Build a factor node to remember that this load is independent of the 7753 // other one. 7754 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 7755 Hi.getValue(1)); 7756 7757 // Legalized the chain result - switch anything that used the old chain to 7758 // use the new one. 7759 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 7760 7761 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 7762 7763 SDValue RetOps[] = { LoadRes, Chain }; 7764 return DAG.getMergeValues(RetOps, DL); 7765 } 7766 return SDValue(); 7767 } 7768 7769 /// A vector select of 2 constant vectors can be simplified to math/logic to 7770 /// avoid a variable select instruction and possibly avoid constant loads. 7771 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 7772 SDValue Cond = N->getOperand(0); 7773 SDValue N1 = N->getOperand(1); 7774 SDValue N2 = N->getOperand(2); 7775 EVT VT = N->getValueType(0); 7776 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 7777 !TLI.convertSelectOfConstantsToMath(VT) || 7778 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 7779 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 7780 return SDValue(); 7781 7782 // Check if we can use the condition value to increment/decrement a single 7783 // constant value. This simplifies a select to an add and removes a constant 7784 // load/materialization from the general case. 7785 bool AllAddOne = true; 7786 bool AllSubOne = true; 7787 unsigned Elts = VT.getVectorNumElements(); 7788 for (unsigned i = 0; i != Elts; ++i) { 7789 SDValue N1Elt = N1.getOperand(i); 7790 SDValue N2Elt = N2.getOperand(i); 7791 if (N1Elt.isUndef() || N2Elt.isUndef()) 7792 continue; 7793 7794 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 7795 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 7796 if (C1 != C2 + 1) 7797 AllAddOne = false; 7798 if (C1 != C2 - 1) 7799 AllSubOne = false; 7800 } 7801 7802 // Further simplifications for the extra-special cases where the constants are 7803 // all 0 or all -1 should be implemented as folds of these patterns. 7804 SDLoc DL(N); 7805 if (AllAddOne || AllSubOne) { 7806 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 7807 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 7808 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 7809 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 7810 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 7811 } 7812 7813 // The general case for select-of-constants: 7814 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 7815 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 7816 // leave that to a machine-specific pass. 7817 return SDValue(); 7818 } 7819 7820 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 7821 SDValue N0 = N->getOperand(0); 7822 SDValue N1 = N->getOperand(1); 7823 SDValue N2 = N->getOperand(2); 7824 SDLoc DL(N); 7825 7826 // fold (vselect C, X, X) -> X 7827 if (N1 == N2) 7828 return N1; 7829 7830 // Canonicalize integer abs. 7831 // vselect (setg[te] X, 0), X, -X -> 7832 // vselect (setgt X, -1), X, -X -> 7833 // vselect (setl[te] X, 0), -X, X -> 7834 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 7835 if (N0.getOpcode() == ISD::SETCC) { 7836 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 7837 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7838 bool isAbs = false; 7839 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 7840 7841 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 7842 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 7843 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 7844 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 7845 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 7846 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 7847 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 7848 7849 if (isAbs) { 7850 EVT VT = LHS.getValueType(); 7851 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 7852 return DAG.getNode(ISD::ABS, DL, VT, LHS); 7853 7854 SDValue Shift = DAG.getNode( 7855 ISD::SRA, DL, VT, LHS, 7856 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 7857 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 7858 AddToWorklist(Shift.getNode()); 7859 AddToWorklist(Add.getNode()); 7860 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 7861 } 7862 7863 // vselect x, y (fcmp lt x, y) -> fminnum x, y 7864 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y 7865 // 7866 // This is OK if we don't care about what happens if either operand is a 7867 // NaN. 7868 // 7869 EVT VT = N->getValueType(0); 7870 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N0.getOperand(0), N0.getOperand(1))) { 7871 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7872 if (SDValue FMinMax = combineMinNumMaxNum( 7873 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 7874 return FMinMax; 7875 } 7876 7877 // If this select has a condition (setcc) with narrower operands than the 7878 // select, try to widen the compare to match the select width. 7879 // TODO: This should be extended to handle any constant. 7880 // TODO: This could be extended to handle non-loading patterns, but that 7881 // requires thorough testing to avoid regressions. 7882 if (isNullConstantOrNullSplatConstant(RHS)) { 7883 EVT NarrowVT = LHS.getValueType(); 7884 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 7885 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 7886 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 7887 unsigned WideWidth = WideVT.getScalarSizeInBits(); 7888 bool IsSigned = isSignedIntSetCC(CC); 7889 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7890 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 7891 SetCCWidth != 1 && SetCCWidth < WideWidth && 7892 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 7893 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 7894 // Both compare operands can be widened for free. The LHS can use an 7895 // extended load, and the RHS is a constant: 7896 // vselect (ext (setcc load(X), C)), N1, N2 --> 7897 // vselect (setcc extload(X), C'), N1, N2 7898 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7899 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 7900 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 7901 EVT WideSetCCVT = getSetCCResultType(WideVT); 7902 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 7903 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 7904 } 7905 } 7906 } 7907 7908 if (SimplifySelectOps(N, N1, N2)) 7909 return SDValue(N, 0); // Don't revisit N. 7910 7911 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 7912 if (ISD::isBuildVectorAllOnes(N0.getNode())) 7913 return N1; 7914 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 7915 if (ISD::isBuildVectorAllZeros(N0.getNode())) 7916 return N2; 7917 7918 // The ConvertSelectToConcatVector function is assuming both the above 7919 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 7920 // and addressed. 7921 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 7922 N2.getOpcode() == ISD::CONCAT_VECTORS && 7923 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 7924 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 7925 return CV; 7926 } 7927 7928 if (SDValue V = foldVSelectOfConstants(N)) 7929 return V; 7930 7931 return SDValue(); 7932 } 7933 7934 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 7935 SDValue N0 = N->getOperand(0); 7936 SDValue N1 = N->getOperand(1); 7937 SDValue N2 = N->getOperand(2); 7938 SDValue N3 = N->getOperand(3); 7939 SDValue N4 = N->getOperand(4); 7940 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 7941 7942 // fold select_cc lhs, rhs, x, x, cc -> x 7943 if (N2 == N3) 7944 return N2; 7945 7946 // Determine if the condition we're dealing with is constant 7947 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 7948 CC, SDLoc(N), false)) { 7949 AddToWorklist(SCC.getNode()); 7950 7951 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 7952 if (!SCCC->isNullValue()) 7953 return N2; // cond always true -> true val 7954 else 7955 return N3; // cond always false -> false val 7956 } else if (SCC->isUndef()) { 7957 // When the condition is UNDEF, just return the first operand. This is 7958 // coherent the DAG creation, no setcc node is created in this case 7959 return N2; 7960 } else if (SCC.getOpcode() == ISD::SETCC) { 7961 // Fold to a simpler select_cc 7962 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 7963 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 7964 SCC.getOperand(2)); 7965 } 7966 } 7967 7968 // If we can fold this based on the true/false value, do so. 7969 if (SimplifySelectOps(N, N2, N3)) 7970 return SDValue(N, 0); // Don't revisit N. 7971 7972 // fold select_cc into other things, such as min/max/abs 7973 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 7974 } 7975 7976 SDValue DAGCombiner::visitSETCC(SDNode *N) { 7977 // setcc is very commonly used as an argument to brcond. This pattern 7978 // also lend itself to numerous combines and, as a result, it is desired 7979 // we keep the argument to a brcond as a setcc as much as possible. 7980 bool PreferSetCC = 7981 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 7982 7983 SDValue Combined = SimplifySetCC( 7984 N->getValueType(0), N->getOperand(0), N->getOperand(1), 7985 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 7986 7987 if (!Combined) 7988 return SDValue(); 7989 7990 // If we prefer to have a setcc, and we don't, we'll try our best to 7991 // recreate one using rebuildSetCC. 7992 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 7993 SDValue NewSetCC = rebuildSetCC(Combined); 7994 7995 // We don't have anything interesting to combine to. 7996 if (NewSetCC.getNode() == N) 7997 return SDValue(); 7998 7999 if (NewSetCC) 8000 return NewSetCC; 8001 } 8002 8003 return Combined; 8004 } 8005 8006 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 8007 SDValue LHS = N->getOperand(0); 8008 SDValue RHS = N->getOperand(1); 8009 SDValue Carry = N->getOperand(2); 8010 SDValue Cond = N->getOperand(3); 8011 8012 // If Carry is false, fold to a regular SETCC. 8013 if (isNullConstant(Carry)) 8014 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 8015 8016 return SDValue(); 8017 } 8018 8019 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 8020 /// a build_vector of constants. 8021 /// This function is called by the DAGCombiner when visiting sext/zext/aext 8022 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 8023 /// Vector extends are not folded if operations are legal; this is to 8024 /// avoid introducing illegal build_vector dag nodes. 8025 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 8026 SelectionDAG &DAG, bool LegalTypes, 8027 bool LegalOperations) { 8028 unsigned Opcode = N->getOpcode(); 8029 SDValue N0 = N->getOperand(0); 8030 EVT VT = N->getValueType(0); 8031 8032 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 8033 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 8034 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 8035 && "Expected EXTEND dag node in input!"); 8036 8037 // fold (sext c1) -> c1 8038 // fold (zext c1) -> c1 8039 // fold (aext c1) -> c1 8040 if (isa<ConstantSDNode>(N0)) 8041 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 8042 8043 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 8044 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 8045 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 8046 EVT SVT = VT.getScalarType(); 8047 if (!(VT.isVector() && 8048 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 8049 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 8050 return nullptr; 8051 8052 // We can fold this node into a build_vector. 8053 unsigned VTBits = SVT.getSizeInBits(); 8054 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 8055 SmallVector<SDValue, 8> Elts; 8056 unsigned NumElts = VT.getVectorNumElements(); 8057 SDLoc DL(N); 8058 8059 for (unsigned i=0; i != NumElts; ++i) { 8060 SDValue Op = N0->getOperand(i); 8061 if (Op->isUndef()) { 8062 Elts.push_back(DAG.getUNDEF(SVT)); 8063 continue; 8064 } 8065 8066 SDLoc DL(Op); 8067 // Get the constant value and if needed trunc it to the size of the type. 8068 // Nodes like build_vector might have constants wider than the scalar type. 8069 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 8070 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 8071 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 8072 else 8073 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 8074 } 8075 8076 return DAG.getBuildVector(VT, DL, Elts).getNode(); 8077 } 8078 8079 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 8080 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 8081 // transformation. Returns true if extension are possible and the above 8082 // mentioned transformation is profitable. 8083 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 8084 unsigned ExtOpc, 8085 SmallVectorImpl<SDNode *> &ExtendNodes, 8086 const TargetLowering &TLI) { 8087 bool HasCopyToRegUses = false; 8088 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 8089 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 8090 UE = N0.getNode()->use_end(); 8091 UI != UE; ++UI) { 8092 SDNode *User = *UI; 8093 if (User == N) 8094 continue; 8095 if (UI.getUse().getResNo() != N0.getResNo()) 8096 continue; 8097 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 8098 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 8099 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 8100 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 8101 // Sign bits will be lost after a zext. 8102 return false; 8103 bool Add = false; 8104 for (unsigned i = 0; i != 2; ++i) { 8105 SDValue UseOp = User->getOperand(i); 8106 if (UseOp == N0) 8107 continue; 8108 if (!isa<ConstantSDNode>(UseOp)) 8109 return false; 8110 Add = true; 8111 } 8112 if (Add) 8113 ExtendNodes.push_back(User); 8114 continue; 8115 } 8116 // If truncates aren't free and there are users we can't 8117 // extend, it isn't worthwhile. 8118 if (!isTruncFree) 8119 return false; 8120 // Remember if this value is live-out. 8121 if (User->getOpcode() == ISD::CopyToReg) 8122 HasCopyToRegUses = true; 8123 } 8124 8125 if (HasCopyToRegUses) { 8126 bool BothLiveOut = false; 8127 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8128 UI != UE; ++UI) { 8129 SDUse &Use = UI.getUse(); 8130 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 8131 BothLiveOut = true; 8132 break; 8133 } 8134 } 8135 if (BothLiveOut) 8136 // Both unextended and extended values are live out. There had better be 8137 // a good reason for the transformation. 8138 return ExtendNodes.size(); 8139 } 8140 return true; 8141 } 8142 8143 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 8144 SDValue OrigLoad, SDValue ExtLoad, 8145 ISD::NodeType ExtType) { 8146 // Extend SetCC uses if necessary. 8147 SDLoc DL(ExtLoad); 8148 for (SDNode *SetCC : SetCCs) { 8149 SmallVector<SDValue, 4> Ops; 8150 8151 for (unsigned j = 0; j != 2; ++j) { 8152 SDValue SOp = SetCC->getOperand(j); 8153 if (SOp == OrigLoad) 8154 Ops.push_back(ExtLoad); 8155 else 8156 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 8157 } 8158 8159 Ops.push_back(SetCC->getOperand(2)); 8160 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 8161 } 8162 } 8163 8164 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 8165 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 8166 SDValue N0 = N->getOperand(0); 8167 EVT DstVT = N->getValueType(0); 8168 EVT SrcVT = N0.getValueType(); 8169 8170 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8171 N->getOpcode() == ISD::ZERO_EXTEND) && 8172 "Unexpected node type (not an extend)!"); 8173 8174 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 8175 // For example, on a target with legal v4i32, but illegal v8i32, turn: 8176 // (v8i32 (sext (v8i16 (load x)))) 8177 // into: 8178 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8179 // (v4i32 (sextload (x + 16))))) 8180 // Where uses of the original load, i.e.: 8181 // (v8i16 (load x)) 8182 // are replaced with: 8183 // (v8i16 (truncate 8184 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8185 // (v4i32 (sextload (x + 16))))))) 8186 // 8187 // This combine is only applicable to illegal, but splittable, vectors. 8188 // All legal types, and illegal non-vector types, are handled elsewhere. 8189 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 8190 // 8191 if (N0->getOpcode() != ISD::LOAD) 8192 return SDValue(); 8193 8194 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8195 8196 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 8197 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 8198 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 8199 return SDValue(); 8200 8201 SmallVector<SDNode *, 4> SetCCs; 8202 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 8203 return SDValue(); 8204 8205 ISD::LoadExtType ExtType = 8206 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 8207 8208 // Try to split the vector types to get down to legal types. 8209 EVT SplitSrcVT = SrcVT; 8210 EVT SplitDstVT = DstVT; 8211 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 8212 SplitSrcVT.getVectorNumElements() > 1) { 8213 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 8214 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 8215 } 8216 8217 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 8218 return SDValue(); 8219 8220 SDLoc DL(N); 8221 const unsigned NumSplits = 8222 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 8223 const unsigned Stride = SplitSrcVT.getStoreSize(); 8224 SmallVector<SDValue, 4> Loads; 8225 SmallVector<SDValue, 4> Chains; 8226 8227 SDValue BasePtr = LN0->getBasePtr(); 8228 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 8229 const unsigned Offset = Idx * Stride; 8230 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 8231 8232 SDValue SplitLoad = DAG.getExtLoad( 8233 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 8234 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 8235 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8236 8237 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 8238 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 8239 8240 Loads.push_back(SplitLoad.getValue(0)); 8241 Chains.push_back(SplitLoad.getValue(1)); 8242 } 8243 8244 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 8245 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 8246 8247 // Simplify TF. 8248 AddToWorklist(NewChain.getNode()); 8249 8250 CombineTo(N, NewValue); 8251 8252 // Replace uses of the original load (before extension) 8253 // with a truncate of the concatenated sextloaded vectors. 8254 SDValue Trunc = 8255 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 8256 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 8257 CombineTo(N0.getNode(), Trunc, NewChain); 8258 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8259 } 8260 8261 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8262 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8263 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 8264 assert(N->getOpcode() == ISD::ZERO_EXTEND); 8265 EVT VT = N->getValueType(0); 8266 8267 // and/or/xor 8268 SDValue N0 = N->getOperand(0); 8269 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8270 N0.getOpcode() == ISD::XOR) || 8271 N0.getOperand(1).getOpcode() != ISD::Constant || 8272 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 8273 return SDValue(); 8274 8275 // shl/shr 8276 SDValue N1 = N0->getOperand(0); 8277 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 8278 N1.getOperand(1).getOpcode() != ISD::Constant || 8279 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 8280 return SDValue(); 8281 8282 // load 8283 if (!isa<LoadSDNode>(N1.getOperand(0))) 8284 return SDValue(); 8285 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 8286 EVT MemVT = Load->getMemoryVT(); 8287 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 8288 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 8289 return SDValue(); 8290 8291 8292 // If the shift op is SHL, the logic op must be AND, otherwise the result 8293 // will be wrong. 8294 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 8295 return SDValue(); 8296 8297 if (!N0.hasOneUse() || !N1.hasOneUse()) 8298 return SDValue(); 8299 8300 SmallVector<SDNode*, 4> SetCCs; 8301 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 8302 ISD::ZERO_EXTEND, SetCCs, TLI)) 8303 return SDValue(); 8304 8305 // Actually do the transformation. 8306 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 8307 Load->getChain(), Load->getBasePtr(), 8308 Load->getMemoryVT(), Load->getMemOperand()); 8309 8310 SDLoc DL1(N1); 8311 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 8312 N1.getOperand(1)); 8313 8314 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8315 Mask = Mask.zext(VT.getSizeInBits()); 8316 SDLoc DL0(N0); 8317 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 8318 DAG.getConstant(Mask, DL0, VT)); 8319 8320 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8321 CombineTo(N, And); 8322 if (SDValue(Load, 0).hasOneUse()) { 8323 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 8324 } else { 8325 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 8326 Load->getValueType(0), ExtLoad); 8327 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 8328 } 8329 return SDValue(N,0); // Return N so it doesn't get rechecked! 8330 } 8331 8332 /// If we're narrowing or widening the result of a vector select and the final 8333 /// size is the same size as a setcc (compare) feeding the select, then try to 8334 /// apply the cast operation to the select's operands because matching vector 8335 /// sizes for a select condition and other operands should be more efficient. 8336 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 8337 unsigned CastOpcode = Cast->getOpcode(); 8338 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 8339 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 8340 CastOpcode == ISD::FP_ROUND) && 8341 "Unexpected opcode for vector select narrowing/widening"); 8342 8343 // We only do this transform before legal ops because the pattern may be 8344 // obfuscated by target-specific operations after legalization. Do not create 8345 // an illegal select op, however, because that may be difficult to lower. 8346 EVT VT = Cast->getValueType(0); 8347 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 8348 return SDValue(); 8349 8350 SDValue VSel = Cast->getOperand(0); 8351 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 8352 VSel.getOperand(0).getOpcode() != ISD::SETCC) 8353 return SDValue(); 8354 8355 // Does the setcc have the same vector size as the casted select? 8356 SDValue SetCC = VSel.getOperand(0); 8357 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 8358 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 8359 return SDValue(); 8360 8361 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 8362 SDValue A = VSel.getOperand(1); 8363 SDValue B = VSel.getOperand(2); 8364 SDValue CastA, CastB; 8365 SDLoc DL(Cast); 8366 if (CastOpcode == ISD::FP_ROUND) { 8367 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 8368 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 8369 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 8370 } else { 8371 CastA = DAG.getNode(CastOpcode, DL, VT, A); 8372 CastB = DAG.getNode(CastOpcode, DL, VT, B); 8373 } 8374 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 8375 } 8376 8377 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8378 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8379 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 8380 const TargetLowering &TLI, EVT VT, 8381 bool LegalOperations, SDNode *N, 8382 SDValue N0, ISD::LoadExtType ExtLoadType) { 8383 SDNode *N0Node = N0.getNode(); 8384 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 8385 : ISD::isZEXTLoad(N0Node); 8386 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 8387 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 8388 return {}; 8389 8390 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8391 EVT MemVT = LN0->getMemoryVT(); 8392 if ((LegalOperations || LN0->isVolatile()) && 8393 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 8394 return {}; 8395 8396 SDValue ExtLoad = 8397 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8398 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 8399 Combiner.CombineTo(N, ExtLoad); 8400 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8401 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8402 } 8403 8404 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8405 // Only generate vector extloads when 1) they're legal, and 2) they are 8406 // deemed desirable by the target. 8407 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 8408 const TargetLowering &TLI, EVT VT, 8409 bool LegalOperations, SDNode *N, SDValue N0, 8410 ISD::LoadExtType ExtLoadType, 8411 ISD::NodeType ExtOpc) { 8412 if (!ISD::isNON_EXTLoad(N0.getNode()) || 8413 !ISD::isUNINDEXEDLoad(N0.getNode()) || 8414 ((LegalOperations || VT.isVector() || 8415 cast<LoadSDNode>(N0)->isVolatile()) && 8416 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 8417 return {}; 8418 8419 bool DoXform = true; 8420 SmallVector<SDNode *, 4> SetCCs; 8421 if (!N0.hasOneUse()) 8422 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 8423 if (VT.isVector()) 8424 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 8425 if (!DoXform) 8426 return {}; 8427 8428 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8429 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8430 LN0->getBasePtr(), N0.getValueType(), 8431 LN0->getMemOperand()); 8432 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 8433 // If the load value is used only by N, replace it via CombineTo N. 8434 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 8435 Combiner.CombineTo(N, ExtLoad); 8436 if (NoReplaceTrunc) { 8437 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8438 } else { 8439 SDValue Trunc = 8440 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 8441 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8442 } 8443 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8444 } 8445 8446 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 8447 bool LegalOperations) { 8448 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8449 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 8450 8451 SDValue SetCC = N->getOperand(0); 8452 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 8453 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 8454 return SDValue(); 8455 8456 SDValue X = SetCC.getOperand(0); 8457 SDValue Ones = SetCC.getOperand(1); 8458 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 8459 EVT VT = N->getValueType(0); 8460 EVT XVT = X.getValueType(); 8461 // setge X, C is canonicalized to setgt, so we do not need to match that 8462 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 8463 // not require the 'not' op. 8464 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 8465 // Invert and smear/shift the sign bit: 8466 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 8467 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 8468 SDLoc DL(N); 8469 SDValue NotX = DAG.getNOT(DL, X, VT); 8470 SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT); 8471 auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 8472 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 8473 } 8474 return SDValue(); 8475 } 8476 8477 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 8478 SDValue N0 = N->getOperand(0); 8479 EVT VT = N->getValueType(0); 8480 SDLoc DL(N); 8481 8482 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8483 LegalOperations)) 8484 return SDValue(Res, 0); 8485 8486 // fold (sext (sext x)) -> (sext x) 8487 // fold (sext (aext x)) -> (sext x) 8488 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8489 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 8490 8491 if (N0.getOpcode() == ISD::TRUNCATE) { 8492 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 8493 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 8494 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8495 SDNode *oye = N0.getOperand(0).getNode(); 8496 if (NarrowLoad.getNode() != N0.getNode()) { 8497 CombineTo(N0.getNode(), NarrowLoad); 8498 // CombineTo deleted the truncate, if needed, but not what's under it. 8499 AddToWorklist(oye); 8500 } 8501 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8502 } 8503 8504 // See if the value being truncated is already sign extended. If so, just 8505 // eliminate the trunc/sext pair. 8506 SDValue Op = N0.getOperand(0); 8507 unsigned OpBits = Op.getScalarValueSizeInBits(); 8508 unsigned MidBits = N0.getScalarValueSizeInBits(); 8509 unsigned DestBits = VT.getScalarSizeInBits(); 8510 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 8511 8512 if (OpBits == DestBits) { 8513 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 8514 // bits, it is already ready. 8515 if (NumSignBits > DestBits-MidBits) 8516 return Op; 8517 } else if (OpBits < DestBits) { 8518 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 8519 // bits, just sext from i32. 8520 if (NumSignBits > OpBits-MidBits) 8521 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 8522 } else { 8523 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 8524 // bits, just truncate to i32. 8525 if (NumSignBits > OpBits-MidBits) 8526 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 8527 } 8528 8529 // fold (sext (truncate x)) -> (sextinreg x). 8530 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 8531 N0.getValueType())) { 8532 if (OpBits < DestBits) 8533 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 8534 else if (OpBits > DestBits) 8535 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 8536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 8537 DAG.getValueType(N0.getValueType())); 8538 } 8539 } 8540 8541 // Try to simplify (sext (load x)). 8542 if (SDValue foldedExt = 8543 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8544 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 8545 return foldedExt; 8546 8547 // fold (sext (load x)) to multiple smaller sextloads. 8548 // Only on illegal but splittable vectors. 8549 if (SDValue ExtLoad = CombineExtLoad(N)) 8550 return ExtLoad; 8551 8552 // Try to simplify (sext (sextload x)). 8553 if (SDValue foldedExt = tryToFoldExtOfExtload( 8554 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 8555 return foldedExt; 8556 8557 // fold (sext (and/or/xor (load x), cst)) -> 8558 // (and/or/xor (sextload x), (sext cst)) 8559 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8560 N0.getOpcode() == ISD::XOR) && 8561 isa<LoadSDNode>(N0.getOperand(0)) && 8562 N0.getOperand(1).getOpcode() == ISD::Constant && 8563 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8564 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8565 EVT MemVT = LN00->getMemoryVT(); 8566 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 8567 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 8568 SmallVector<SDNode*, 4> SetCCs; 8569 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8570 ISD::SIGN_EXTEND, SetCCs, TLI); 8571 if (DoXform) { 8572 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 8573 LN00->getChain(), LN00->getBasePtr(), 8574 LN00->getMemoryVT(), 8575 LN00->getMemOperand()); 8576 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8577 Mask = Mask.sext(VT.getSizeInBits()); 8578 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8579 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8580 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 8581 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8582 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8583 CombineTo(N, And); 8584 // If N0 has multiple uses, change other uses as well. 8585 if (NoReplaceTruncAnd) { 8586 SDValue TruncAnd = 8587 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8588 CombineTo(N0.getNode(), TruncAnd); 8589 } 8590 if (NoReplaceTrunc) { 8591 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8592 } else { 8593 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8594 LN00->getValueType(0), ExtLoad); 8595 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8596 } 8597 return SDValue(N,0); // Return N so it doesn't get rechecked! 8598 } 8599 } 8600 } 8601 8602 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8603 return V; 8604 8605 if (N0.getOpcode() == ISD::SETCC) { 8606 SDValue N00 = N0.getOperand(0); 8607 SDValue N01 = N0.getOperand(1); 8608 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 8609 EVT N00VT = N0.getOperand(0).getValueType(); 8610 8611 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 8612 // Only do this before legalize for now. 8613 if (VT.isVector() && !LegalOperations && 8614 TLI.getBooleanContents(N00VT) == 8615 TargetLowering::ZeroOrNegativeOneBooleanContent) { 8616 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 8617 // of the same size as the compared operands. Only optimize sext(setcc()) 8618 // if this is the case. 8619 EVT SVT = getSetCCResultType(N00VT); 8620 8621 // We know that the # elements of the results is the same as the 8622 // # elements of the compare (and the # elements of the compare result 8623 // for that matter). Check to see that they are the same size. If so, 8624 // we know that the element size of the sext'd result matches the 8625 // element size of the compare operands. 8626 if (VT.getSizeInBits() == SVT.getSizeInBits()) 8627 return DAG.getSetCC(DL, VT, N00, N01, CC); 8628 8629 // If the desired elements are smaller or larger than the source 8630 // elements, we can use a matching integer vector type and then 8631 // truncate/sign extend. 8632 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 8633 if (SVT == MatchingVecType) { 8634 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 8635 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 8636 } 8637 } 8638 8639 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 8640 // Here, T can be 1 or -1, depending on the type of the setcc and 8641 // getBooleanContents(). 8642 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 8643 8644 // To determine the "true" side of the select, we need to know the high bit 8645 // of the value returned by the setcc if it evaluates to true. 8646 // If the type of the setcc is i1, then the true case of the select is just 8647 // sext(i1 1), that is, -1. 8648 // If the type of the setcc is larger (say, i8) then the value of the high 8649 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 8650 // of the appropriate width. 8651 SDValue ExtTrueVal = (SetCCWidth == 1) 8652 ? DAG.getAllOnesConstant(DL, VT) 8653 : DAG.getBoolConstant(true, DL, VT, N00VT); 8654 SDValue Zero = DAG.getConstant(0, DL, VT); 8655 if (SDValue SCC = 8656 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 8657 return SCC; 8658 8659 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 8660 EVT SetCCVT = getSetCCResultType(N00VT); 8661 // Don't do this transform for i1 because there's a select transform 8662 // that would reverse it. 8663 // TODO: We should not do this transform at all without a target hook 8664 // because a sext is likely cheaper than a select? 8665 if (SetCCVT.getScalarSizeInBits() != 1 && 8666 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 8667 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 8668 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 8669 } 8670 } 8671 } 8672 8673 // fold (sext x) -> (zext x) if the sign bit is known zero. 8674 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 8675 DAG.SignBitIsZero(N0)) 8676 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 8677 8678 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8679 return NewVSel; 8680 8681 return SDValue(); 8682 } 8683 8684 // isTruncateOf - If N is a truncate of some other value, return true, record 8685 // the value being truncated in Op and which of Op's bits are zero/one in Known. 8686 // This function computes KnownBits to avoid a duplicated call to 8687 // computeKnownBits in the caller. 8688 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 8689 KnownBits &Known) { 8690 if (N->getOpcode() == ISD::TRUNCATE) { 8691 Op = N->getOperand(0); 8692 DAG.computeKnownBits(Op, Known); 8693 return true; 8694 } 8695 8696 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 8697 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 8698 return false; 8699 8700 SDValue Op0 = N->getOperand(0); 8701 SDValue Op1 = N->getOperand(1); 8702 assert(Op0.getValueType() == Op1.getValueType()); 8703 8704 if (isNullConstant(Op0)) 8705 Op = Op1; 8706 else if (isNullConstant(Op1)) 8707 Op = Op0; 8708 else 8709 return false; 8710 8711 DAG.computeKnownBits(Op, Known); 8712 8713 if (!(Known.Zero | 1).isAllOnesValue()) 8714 return false; 8715 8716 return true; 8717 } 8718 8719 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 8720 SDValue N0 = N->getOperand(0); 8721 EVT VT = N->getValueType(0); 8722 8723 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8724 LegalOperations)) 8725 return SDValue(Res, 0); 8726 8727 // fold (zext (zext x)) -> (zext x) 8728 // fold (zext (aext x)) -> (zext x) 8729 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8730 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 8731 N0.getOperand(0)); 8732 8733 // fold (zext (truncate x)) -> (zext x) or 8734 // (zext (truncate x)) -> (truncate x) 8735 // This is valid when the truncated bits of x are already zero. 8736 // FIXME: We should extend this to work for vectors too. 8737 SDValue Op; 8738 KnownBits Known; 8739 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 8740 APInt TruncatedBits = 8741 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 8742 APInt(Op.getValueSizeInBits(), 0) : 8743 APInt::getBitsSet(Op.getValueSizeInBits(), 8744 N0.getValueSizeInBits(), 8745 std::min(Op.getValueSizeInBits(), 8746 VT.getSizeInBits())); 8747 if (TruncatedBits.isSubsetOf(Known.Zero)) 8748 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8749 } 8750 8751 // fold (zext (truncate x)) -> (and x, mask) 8752 if (N0.getOpcode() == ISD::TRUNCATE) { 8753 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 8754 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 8755 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8756 SDNode *oye = N0.getOperand(0).getNode(); 8757 if (NarrowLoad.getNode() != N0.getNode()) { 8758 CombineTo(N0.getNode(), NarrowLoad); 8759 // CombineTo deleted the truncate, if needed, but not what's under it. 8760 AddToWorklist(oye); 8761 } 8762 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8763 } 8764 8765 EVT SrcVT = N0.getOperand(0).getValueType(); 8766 EVT MinVT = N0.getValueType(); 8767 8768 // Try to mask before the extension to avoid having to generate a larger mask, 8769 // possibly over several sub-vectors. 8770 if (SrcVT.bitsLT(VT) && VT.isVector()) { 8771 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 8772 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 8773 SDValue Op = N0.getOperand(0); 8774 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8775 AddToWorklist(Op.getNode()); 8776 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 8777 // Transfer the debug info; the new node is equivalent to N0. 8778 DAG.transferDbgValues(N0, ZExtOrTrunc); 8779 return ZExtOrTrunc; 8780 } 8781 } 8782 8783 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 8784 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 8785 AddToWorklist(Op.getNode()); 8786 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 8787 // We may safely transfer the debug info describing the truncate node over 8788 // to the equivalent and operation. 8789 DAG.transferDbgValues(N0, And); 8790 return And; 8791 } 8792 } 8793 8794 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 8795 // if either of the casts is not free. 8796 if (N0.getOpcode() == ISD::AND && 8797 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 8798 N0.getOperand(1).getOpcode() == ISD::Constant && 8799 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 8800 N0.getValueType()) || 8801 !TLI.isZExtFree(N0.getValueType(), VT))) { 8802 SDValue X = N0.getOperand(0).getOperand(0); 8803 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 8804 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8805 Mask = Mask.zext(VT.getSizeInBits()); 8806 SDLoc DL(N); 8807 return DAG.getNode(ISD::AND, DL, VT, 8808 X, DAG.getConstant(Mask, DL, VT)); 8809 } 8810 8811 // Try to simplify (zext (load x)). 8812 if (SDValue foldedExt = 8813 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8814 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 8815 return foldedExt; 8816 8817 // fold (zext (load x)) to multiple smaller zextloads. 8818 // Only on illegal but splittable vectors. 8819 if (SDValue ExtLoad = CombineExtLoad(N)) 8820 return ExtLoad; 8821 8822 // fold (zext (and/or/xor (load x), cst)) -> 8823 // (and/or/xor (zextload x), (zext cst)) 8824 // Unless (and (load x) cst) will match as a zextload already and has 8825 // additional users. 8826 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8827 N0.getOpcode() == ISD::XOR) && 8828 isa<LoadSDNode>(N0.getOperand(0)) && 8829 N0.getOperand(1).getOpcode() == ISD::Constant && 8830 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 8831 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 8832 EVT MemVT = LN00->getMemoryVT(); 8833 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 8834 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 8835 bool DoXform = true; 8836 SmallVector<SDNode*, 4> SetCCs; 8837 if (!N0.hasOneUse()) { 8838 if (N0.getOpcode() == ISD::AND) { 8839 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 8840 EVT LoadResultTy = AndC->getValueType(0); 8841 EVT ExtVT; 8842 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 8843 DoXform = false; 8844 } 8845 } 8846 if (DoXform) 8847 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 8848 ISD::ZERO_EXTEND, SetCCs, TLI); 8849 if (DoXform) { 8850 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 8851 LN00->getChain(), LN00->getBasePtr(), 8852 LN00->getMemoryVT(), 8853 LN00->getMemOperand()); 8854 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8855 Mask = Mask.zext(VT.getSizeInBits()); 8856 SDLoc DL(N); 8857 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 8858 ExtLoad, DAG.getConstant(Mask, DL, VT)); 8859 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8860 bool NoReplaceTruncAnd = !N0.hasOneUse(); 8861 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 8862 CombineTo(N, And); 8863 // If N0 has multiple uses, change other uses as well. 8864 if (NoReplaceTruncAnd) { 8865 SDValue TruncAnd = 8866 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 8867 CombineTo(N0.getNode(), TruncAnd); 8868 } 8869 if (NoReplaceTrunc) { 8870 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 8871 } else { 8872 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 8873 LN00->getValueType(0), ExtLoad); 8874 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 8875 } 8876 return SDValue(N,0); // Return N so it doesn't get rechecked! 8877 } 8878 } 8879 } 8880 8881 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8882 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8883 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 8884 return ZExtLoad; 8885 8886 // Try to simplify (zext (zextload x)). 8887 if (SDValue foldedExt = tryToFoldExtOfExtload( 8888 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 8889 return foldedExt; 8890 8891 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 8892 return V; 8893 8894 if (N0.getOpcode() == ISD::SETCC) { 8895 // Only do this before legalize for now. 8896 if (!LegalOperations && VT.isVector() && 8897 N0.getValueType().getVectorElementType() == MVT::i1) { 8898 EVT N00VT = N0.getOperand(0).getValueType(); 8899 if (getSetCCResultType(N00VT) == N0.getValueType()) 8900 return SDValue(); 8901 8902 // We know that the # elements of the results is the same as the # 8903 // elements of the compare (and the # elements of the compare result for 8904 // that matter). Check to see that they are the same size. If so, we know 8905 // that the element size of the sext'd result matches the element size of 8906 // the compare operands. 8907 SDLoc DL(N); 8908 SDValue VecOnes = DAG.getConstant(1, DL, VT); 8909 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 8910 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 8911 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 8912 N0.getOperand(1), N0.getOperand(2)); 8913 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 8914 } 8915 8916 // If the desired elements are smaller or larger than the source 8917 // elements we can use a matching integer vector type and then 8918 // truncate/sign extend. 8919 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 8920 SDValue VsetCC = 8921 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 8922 N0.getOperand(1), N0.getOperand(2)); 8923 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 8924 VecOnes); 8925 } 8926 8927 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 8928 SDLoc DL(N); 8929 if (SDValue SCC = SimplifySelectCC( 8930 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 8931 DAG.getConstant(0, DL, VT), 8932 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 8933 return SCC; 8934 } 8935 8936 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 8937 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 8938 isa<ConstantSDNode>(N0.getOperand(1)) && 8939 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 8940 N0.hasOneUse()) { 8941 SDValue ShAmt = N0.getOperand(1); 8942 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8943 if (N0.getOpcode() == ISD::SHL) { 8944 SDValue InnerZExt = N0.getOperand(0); 8945 // If the original shl may be shifting out bits, do not perform this 8946 // transformation. 8947 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 8948 InnerZExt.getOperand(0).getValueSizeInBits(); 8949 if (ShAmtVal > KnownZeroBits) 8950 return SDValue(); 8951 } 8952 8953 SDLoc DL(N); 8954 8955 // Ensure that the shift amount is wide enough for the shifted value. 8956 if (VT.getSizeInBits() >= 256) 8957 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 8958 8959 return DAG.getNode(N0.getOpcode(), DL, VT, 8960 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 8961 ShAmt); 8962 } 8963 8964 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8965 return NewVSel; 8966 8967 return SDValue(); 8968 } 8969 8970 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 8971 SDValue N0 = N->getOperand(0); 8972 EVT VT = N->getValueType(0); 8973 8974 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8975 LegalOperations)) 8976 return SDValue(Res, 0); 8977 8978 // fold (aext (aext x)) -> (aext x) 8979 // fold (aext (zext x)) -> (zext x) 8980 // fold (aext (sext x)) -> (sext x) 8981 if (N0.getOpcode() == ISD::ANY_EXTEND || 8982 N0.getOpcode() == ISD::ZERO_EXTEND || 8983 N0.getOpcode() == ISD::SIGN_EXTEND) 8984 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8985 8986 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 8987 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 8988 if (N0.getOpcode() == ISD::TRUNCATE) { 8989 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8990 SDNode *oye = N0.getOperand(0).getNode(); 8991 if (NarrowLoad.getNode() != N0.getNode()) { 8992 CombineTo(N0.getNode(), NarrowLoad); 8993 // CombineTo deleted the truncate, if needed, but not what's under it. 8994 AddToWorklist(oye); 8995 } 8996 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8997 } 8998 } 8999 9000 // fold (aext (truncate x)) 9001 if (N0.getOpcode() == ISD::TRUNCATE) 9002 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 9003 9004 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 9005 // if the trunc is not free. 9006 if (N0.getOpcode() == ISD::AND && 9007 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 9008 N0.getOperand(1).getOpcode() == ISD::Constant && 9009 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 9010 N0.getValueType())) { 9011 SDLoc DL(N); 9012 SDValue X = N0.getOperand(0).getOperand(0); 9013 X = DAG.getAnyExtOrTrunc(X, DL, VT); 9014 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 9015 Mask = Mask.zext(VT.getSizeInBits()); 9016 return DAG.getNode(ISD::AND, DL, VT, 9017 X, DAG.getConstant(Mask, DL, VT)); 9018 } 9019 9020 // fold (aext (load x)) -> (aext (truncate (extload x))) 9021 // None of the supported targets knows how to perform load and any_ext 9022 // on vectors in one instruction. We only perform this transformation on 9023 // scalars. 9024 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 9025 ISD::isUNINDEXEDLoad(N0.getNode()) && 9026 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9027 bool DoXform = true; 9028 SmallVector<SDNode*, 4> SetCCs; 9029 if (!N0.hasOneUse()) 9030 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, 9031 TLI); 9032 if (DoXform) { 9033 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9034 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9035 LN0->getChain(), 9036 LN0->getBasePtr(), N0.getValueType(), 9037 LN0->getMemOperand()); 9038 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 9039 // If the load value is used only by N, replace it via CombineTo N. 9040 bool NoReplaceTrunc = N0.hasOneUse(); 9041 CombineTo(N, ExtLoad); 9042 if (NoReplaceTrunc) { 9043 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 9044 } else { 9045 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 9046 N0.getValueType(), ExtLoad); 9047 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 9048 } 9049 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9050 } 9051 } 9052 9053 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 9054 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 9055 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 9056 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 9057 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 9058 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9059 ISD::LoadExtType ExtType = LN0->getExtensionType(); 9060 EVT MemVT = LN0->getMemoryVT(); 9061 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 9062 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 9063 VT, LN0->getChain(), LN0->getBasePtr(), 9064 MemVT, LN0->getMemOperand()); 9065 CombineTo(N, ExtLoad); 9066 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 9067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9068 } 9069 } 9070 9071 if (N0.getOpcode() == ISD::SETCC) { 9072 // For vectors: 9073 // aext(setcc) -> vsetcc 9074 // aext(setcc) -> truncate(vsetcc) 9075 // aext(setcc) -> aext(vsetcc) 9076 // Only do this before legalize for now. 9077 if (VT.isVector() && !LegalOperations) { 9078 EVT N00VT = N0.getOperand(0).getValueType(); 9079 if (getSetCCResultType(N00VT) == N0.getValueType()) 9080 return SDValue(); 9081 9082 // We know that the # elements of the results is the same as the 9083 // # elements of the compare (and the # elements of the compare result 9084 // for that matter). Check to see that they are the same size. If so, 9085 // we know that the element size of the sext'd result matches the 9086 // element size of the compare operands. 9087 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 9088 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 9089 N0.getOperand(1), 9090 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9091 // If the desired elements are smaller or larger than the source 9092 // elements we can use a matching integer vector type and then 9093 // truncate/any extend 9094 else { 9095 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 9096 SDValue VsetCC = 9097 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 9098 N0.getOperand(1), 9099 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9100 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 9101 } 9102 } 9103 9104 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 9105 SDLoc DL(N); 9106 if (SDValue SCC = SimplifySelectCC( 9107 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 9108 DAG.getConstant(0, DL, VT), 9109 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 9110 return SCC; 9111 } 9112 9113 return SDValue(); 9114 } 9115 9116 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 9117 unsigned Opcode = N->getOpcode(); 9118 SDValue N0 = N->getOperand(0); 9119 SDValue N1 = N->getOperand(1); 9120 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 9121 9122 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 9123 if (N0.getOpcode() == Opcode && 9124 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 9125 return N0; 9126 9127 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 9128 N0.getOperand(0).getOpcode() == Opcode) { 9129 // We have an assert, truncate, assert sandwich. Make one stronger assert 9130 // by asserting on the smallest asserted type to the larger source type. 9131 // This eliminates the later assert: 9132 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 9133 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 9134 SDValue BigA = N0.getOperand(0); 9135 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 9136 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 9137 "Asserting zero/sign-extended bits to a type larger than the " 9138 "truncated destination does not provide information"); 9139 9140 SDLoc DL(N); 9141 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 9142 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 9143 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 9144 BigA.getOperand(0), MinAssertVTVal); 9145 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 9146 } 9147 9148 return SDValue(); 9149 } 9150 9151 /// If the result of a wider load is shifted to right of N bits and then 9152 /// truncated to a narrower type and where N is a multiple of number of bits of 9153 /// the narrower type, transform it to a narrower load from address + N / num of 9154 /// bits of new type. Also narrow the load if the result is masked with an AND 9155 /// to effectively produce a smaller type. If the result is to be extended, also 9156 /// fold the extension to form a extending load. 9157 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 9158 unsigned Opc = N->getOpcode(); 9159 9160 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 9161 SDValue N0 = N->getOperand(0); 9162 EVT VT = N->getValueType(0); 9163 EVT ExtVT = VT; 9164 9165 // This transformation isn't valid for vector loads. 9166 if (VT.isVector()) 9167 return SDValue(); 9168 9169 unsigned ShAmt = 0; 9170 bool HasShiftedOffset = false; 9171 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 9172 // extended to VT. 9173 if (Opc == ISD::SIGN_EXTEND_INREG) { 9174 ExtType = ISD::SEXTLOAD; 9175 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9176 } else if (Opc == ISD::SRL) { 9177 // Another special-case: SRL is basically zero-extending a narrower value, 9178 // or it maybe shifting a higher subword, half or byte into the lowest 9179 // bits. 9180 ExtType = ISD::ZEXTLOAD; 9181 N0 = SDValue(N, 0); 9182 9183 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 9184 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9185 if (!N01 || !LN0) 9186 return SDValue(); 9187 9188 uint64_t ShiftAmt = N01->getZExtValue(); 9189 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 9190 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 9191 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 9192 else 9193 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 9194 VT.getSizeInBits() - ShiftAmt); 9195 } else if (Opc == ISD::AND) { 9196 // An AND with a constant mask is the same as a truncate + zero-extend. 9197 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9198 if (!AndC) 9199 return SDValue(); 9200 9201 const APInt &Mask = AndC->getAPIntValue(); 9202 unsigned ActiveBits = 0; 9203 if (Mask.isMask()) { 9204 ActiveBits = Mask.countTrailingOnes(); 9205 } else if (Mask.isShiftedMask()) { 9206 ShAmt = Mask.countTrailingZeros(); 9207 APInt ShiftedMask = Mask.lshr(ShAmt); 9208 ActiveBits = ShiftedMask.countTrailingOnes(); 9209 HasShiftedOffset = true; 9210 } else 9211 return SDValue(); 9212 9213 ExtType = ISD::ZEXTLOAD; 9214 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 9215 } 9216 9217 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 9218 SDValue SRL = N0; 9219 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 9220 ShAmt = ConstShift->getZExtValue(); 9221 unsigned EVTBits = ExtVT.getSizeInBits(); 9222 // Is the shift amount a multiple of size of VT? 9223 if ((ShAmt & (EVTBits-1)) == 0) { 9224 N0 = N0.getOperand(0); 9225 // Is the load width a multiple of size of VT? 9226 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 9227 return SDValue(); 9228 } 9229 9230 // At this point, we must have a load or else we can't do the transform. 9231 if (!isa<LoadSDNode>(N0)) return SDValue(); 9232 9233 auto *LN0 = cast<LoadSDNode>(N0); 9234 9235 // Because a SRL must be assumed to *need* to zero-extend the high bits 9236 // (as opposed to anyext the high bits), we can't combine the zextload 9237 // lowering of SRL and an sextload. 9238 if (LN0->getExtensionType() == ISD::SEXTLOAD) 9239 return SDValue(); 9240 9241 // If the shift amount is larger than the input type then we're not 9242 // accessing any of the loaded bytes. If the load was a zextload/extload 9243 // then the result of the shift+trunc is zero/undef (handled elsewhere). 9244 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 9245 return SDValue(); 9246 9247 // If the SRL is only used by a masking AND, we may be able to adjust 9248 // the ExtVT to make the AND redundant. 9249 SDNode *Mask = *(SRL->use_begin()); 9250 if (Mask->getOpcode() == ISD::AND && 9251 isa<ConstantSDNode>(Mask->getOperand(1))) { 9252 const APInt &ShiftMask = 9253 cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue(); 9254 if (ShiftMask.isMask()) { 9255 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 9256 ShiftMask.countTrailingOnes()); 9257 // If the mask is smaller, recompute the type. 9258 if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) && 9259 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 9260 ExtVT = MaskedVT; 9261 } 9262 } 9263 } 9264 } 9265 9266 // If the load is shifted left (and the result isn't shifted back right), 9267 // we can fold the truncate through the shift. 9268 unsigned ShLeftAmt = 0; 9269 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9270 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 9271 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 9272 ShLeftAmt = N01->getZExtValue(); 9273 N0 = N0.getOperand(0); 9274 } 9275 } 9276 9277 // If we haven't found a load, we can't narrow it. 9278 if (!isa<LoadSDNode>(N0)) 9279 return SDValue(); 9280 9281 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9282 if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 9283 return SDValue(); 9284 9285 auto AdjustBigEndianShift = [&](unsigned ShAmt) { 9286 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 9287 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 9288 return LVTStoreBits - EVTStoreBits - ShAmt; 9289 }; 9290 9291 // For big endian targets, we need to adjust the offset to the pointer to 9292 // load the correct bytes. 9293 if (DAG.getDataLayout().isBigEndian()) 9294 ShAmt = AdjustBigEndianShift(ShAmt); 9295 9296 EVT PtrType = N0.getOperand(1).getValueType(); 9297 uint64_t PtrOff = ShAmt / 8; 9298 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 9299 SDLoc DL(LN0); 9300 // The original load itself didn't wrap, so an offset within it doesn't. 9301 SDNodeFlags Flags; 9302 Flags.setNoUnsignedWrap(true); 9303 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 9304 PtrType, LN0->getBasePtr(), 9305 DAG.getConstant(PtrOff, DL, PtrType), 9306 Flags); 9307 AddToWorklist(NewPtr.getNode()); 9308 9309 SDValue Load; 9310 if (ExtType == ISD::NON_EXTLOAD) 9311 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 9312 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9313 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9314 else 9315 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 9316 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 9317 NewAlign, LN0->getMemOperand()->getFlags(), 9318 LN0->getAAInfo()); 9319 9320 // Replace the old load's chain with the new load's chain. 9321 WorklistRemover DeadNodes(*this); 9322 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9323 9324 // Shift the result left, if we've swallowed a left shift. 9325 SDValue Result = Load; 9326 if (ShLeftAmt != 0) { 9327 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 9328 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 9329 ShImmTy = VT; 9330 // If the shift amount is as large as the result size (but, presumably, 9331 // no larger than the source) then the useful bits of the result are 9332 // zero; we can't simply return the shortened shift, because the result 9333 // of that operation is undefined. 9334 SDLoc DL(N0); 9335 if (ShLeftAmt >= VT.getSizeInBits()) 9336 Result = DAG.getConstant(0, DL, VT); 9337 else 9338 Result = DAG.getNode(ISD::SHL, DL, VT, 9339 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 9340 } 9341 9342 if (HasShiftedOffset) { 9343 // Recalculate the shift amount after it has been altered to calculate 9344 // the offset. 9345 if (DAG.getDataLayout().isBigEndian()) 9346 ShAmt = AdjustBigEndianShift(ShAmt); 9347 9348 // We're using a shifted mask, so the load now has an offset. This means we 9349 // now need to shift right the mask to match the new load and then shift 9350 // right the result of the AND. 9351 const APInt &Mask = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue(); 9352 APInt ShiftedMask = Mask.lshr(ShAmt); 9353 DAG.UpdateNodeOperands(N, Result, DAG.getConstant(ShiftedMask, DL, VT)); 9354 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); 9355 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, SDValue(N, 0), 9356 ShiftC); 9357 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shifted); 9358 DAG.UpdateNodeOperands(Shifted.getNode(), SDValue(N, 0), ShiftC); 9359 } 9360 // Return the new loaded value. 9361 return Result; 9362 } 9363 9364 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 9365 SDValue N0 = N->getOperand(0); 9366 SDValue N1 = N->getOperand(1); 9367 EVT VT = N->getValueType(0); 9368 EVT EVT = cast<VTSDNode>(N1)->getVT(); 9369 unsigned VTBits = VT.getScalarSizeInBits(); 9370 unsigned EVTBits = EVT.getScalarSizeInBits(); 9371 9372 if (N0.isUndef()) 9373 return DAG.getUNDEF(VT); 9374 9375 // fold (sext_in_reg c1) -> c1 9376 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9377 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 9378 9379 // If the input is already sign extended, just drop the extension. 9380 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 9381 return N0; 9382 9383 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 9384 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 9385 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 9386 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9387 N0.getOperand(0), N1); 9388 9389 // fold (sext_in_reg (sext x)) -> (sext x) 9390 // fold (sext_in_reg (aext x)) -> (sext x) 9391 // if x is small enough. 9392 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 9393 SDValue N00 = N0.getOperand(0); 9394 if (N00.getScalarValueSizeInBits() <= EVTBits && 9395 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9396 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9397 } 9398 9399 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 9400 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 9401 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 9402 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 9403 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 9404 if (!LegalOperations || 9405 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 9406 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 9407 } 9408 9409 // fold (sext_in_reg (zext x)) -> (sext x) 9410 // iff we are extending the source sign bit. 9411 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 9412 SDValue N00 = N0.getOperand(0); 9413 if (N00.getScalarValueSizeInBits() == EVTBits && 9414 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9415 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9416 } 9417 9418 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 9419 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 9420 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 9421 9422 // fold operands of sext_in_reg based on knowledge that the top bits are not 9423 // demanded. 9424 if (SimplifyDemandedBits(SDValue(N, 0))) 9425 return SDValue(N, 0); 9426 9427 // fold (sext_in_reg (load x)) -> (smaller sextload x) 9428 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 9429 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 9430 return NarrowLoad; 9431 9432 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 9433 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 9434 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 9435 if (N0.getOpcode() == ISD::SRL) { 9436 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 9437 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 9438 // We can turn this into an SRA iff the input to the SRL is already sign 9439 // extended enough. 9440 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 9441 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 9442 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 9443 N0.getOperand(0), N0.getOperand(1)); 9444 } 9445 } 9446 9447 // fold (sext_inreg (extload x)) -> (sextload x) 9448 // If sextload is not supported by target, we can only do the combine when 9449 // load has one use. Doing otherwise can block folding the extload with other 9450 // extends that the target does support. 9451 if (ISD::isEXTLoad(N0.getNode()) && 9452 ISD::isUNINDEXEDLoad(N0.getNode()) && 9453 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9454 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 9455 N0.hasOneUse()) || 9456 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9457 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9458 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9459 LN0->getChain(), 9460 LN0->getBasePtr(), EVT, 9461 LN0->getMemOperand()); 9462 CombineTo(N, ExtLoad); 9463 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9464 AddToWorklist(ExtLoad.getNode()); 9465 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9466 } 9467 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 9468 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 9469 N0.hasOneUse() && 9470 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9471 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9472 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9473 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9474 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9475 LN0->getChain(), 9476 LN0->getBasePtr(), EVT, 9477 LN0->getMemOperand()); 9478 CombineTo(N, ExtLoad); 9479 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9480 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9481 } 9482 9483 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 9484 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 9485 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 9486 N0.getOperand(1), false)) 9487 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9488 BSwap, N1); 9489 } 9490 9491 return SDValue(); 9492 } 9493 9494 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 9495 SDValue N0 = N->getOperand(0); 9496 EVT VT = N->getValueType(0); 9497 9498 if (N0.isUndef()) 9499 return DAG.getUNDEF(VT); 9500 9501 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9502 LegalOperations)) 9503 return SDValue(Res, 0); 9504 9505 return SDValue(); 9506 } 9507 9508 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 9509 SDValue N0 = N->getOperand(0); 9510 EVT VT = N->getValueType(0); 9511 9512 if (N0.isUndef()) 9513 return DAG.getUNDEF(VT); 9514 9515 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 9516 LegalOperations)) 9517 return SDValue(Res, 0); 9518 9519 return SDValue(); 9520 } 9521 9522 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 9523 SDValue N0 = N->getOperand(0); 9524 EVT VT = N->getValueType(0); 9525 bool isLE = DAG.getDataLayout().isLittleEndian(); 9526 9527 // noop truncate 9528 if (N0.getValueType() == N->getValueType(0)) 9529 return N0; 9530 9531 // fold (truncate (truncate x)) -> (truncate x) 9532 if (N0.getOpcode() == ISD::TRUNCATE) 9533 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9534 9535 // fold (truncate c1) -> c1 9536 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 9537 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 9538 if (C.getNode() != N) 9539 return C; 9540 } 9541 9542 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 9543 if (N0.getOpcode() == ISD::ZERO_EXTEND || 9544 N0.getOpcode() == ISD::SIGN_EXTEND || 9545 N0.getOpcode() == ISD::ANY_EXTEND) { 9546 // if the source is smaller than the dest, we still need an extend. 9547 if (N0.getOperand(0).getValueType().bitsLT(VT)) 9548 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 9549 // if the source is larger than the dest, than we just need the truncate. 9550 if (N0.getOperand(0).getValueType().bitsGT(VT)) 9551 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 9552 // if the source and dest are the same type, we can drop both the extend 9553 // and the truncate. 9554 return N0.getOperand(0); 9555 } 9556 9557 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 9558 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 9559 return SDValue(); 9560 9561 // Fold extract-and-trunc into a narrow extract. For example: 9562 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 9563 // i32 y = TRUNCATE(i64 x) 9564 // -- becomes -- 9565 // v16i8 b = BITCAST (v2i64 val) 9566 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 9567 // 9568 // Note: We only run this optimization after type legalization (which often 9569 // creates this pattern) and before operation legalization after which 9570 // we need to be more careful about the vector instructions that we generate. 9571 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 9572 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 9573 EVT VecTy = N0.getOperand(0).getValueType(); 9574 EVT ExTy = N0.getValueType(); 9575 EVT TrTy = N->getValueType(0); 9576 9577 unsigned NumElem = VecTy.getVectorNumElements(); 9578 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 9579 9580 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 9581 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 9582 9583 SDValue EltNo = N0->getOperand(1); 9584 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 9585 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9586 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 9587 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 9588 9589 SDLoc DL(N); 9590 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 9591 DAG.getBitcast(NVT, N0.getOperand(0)), 9592 DAG.getConstant(Index, DL, IndexTy)); 9593 } 9594 } 9595 9596 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 9597 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 9598 EVT SrcVT = N0.getValueType(); 9599 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 9600 TLI.isTruncateFree(SrcVT, VT)) { 9601 SDLoc SL(N0); 9602 SDValue Cond = N0.getOperand(0); 9603 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9604 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 9605 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 9606 } 9607 } 9608 9609 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 9610 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9611 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 9612 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 9613 SDValue Amt = N0.getOperand(1); 9614 KnownBits Known; 9615 DAG.computeKnownBits(Amt, Known); 9616 unsigned Size = VT.getScalarSizeInBits(); 9617 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 9618 SDLoc SL(N); 9619 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 9620 9621 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9622 if (AmtVT != Amt.getValueType()) { 9623 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 9624 AddToWorklist(Amt.getNode()); 9625 } 9626 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 9627 } 9628 } 9629 9630 // Fold a series of buildvector, bitcast, and truncate if possible. 9631 // For example fold 9632 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 9633 // (2xi32 (buildvector x, y)). 9634 if (Level == AfterLegalizeVectorOps && VT.isVector() && 9635 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 9636 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 9637 N0.getOperand(0).hasOneUse()) { 9638 SDValue BuildVect = N0.getOperand(0); 9639 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 9640 EVT TruncVecEltTy = VT.getVectorElementType(); 9641 9642 // Check that the element types match. 9643 if (BuildVectEltTy == TruncVecEltTy) { 9644 // Now we only need to compute the offset of the truncated elements. 9645 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 9646 unsigned TruncVecNumElts = VT.getVectorNumElements(); 9647 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 9648 9649 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 9650 "Invalid number of elements"); 9651 9652 SmallVector<SDValue, 8> Opnds; 9653 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 9654 Opnds.push_back(BuildVect.getOperand(i)); 9655 9656 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 9657 } 9658 } 9659 9660 // See if we can simplify the input to this truncate through knowledge that 9661 // only the low bits are being used. 9662 // For example "trunc (or (shl x, 8), y)" // -> trunc y 9663 // Currently we only perform this optimization on scalars because vectors 9664 // may have different active low bits. 9665 if (!VT.isVector()) { 9666 APInt Mask = 9667 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 9668 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 9669 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 9670 } 9671 9672 // fold (truncate (load x)) -> (smaller load x) 9673 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 9674 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 9675 if (SDValue Reduced = ReduceLoadWidth(N)) 9676 return Reduced; 9677 9678 // Handle the case where the load remains an extending load even 9679 // after truncation. 9680 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 9681 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9682 if (!LN0->isVolatile() && 9683 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 9684 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 9685 VT, LN0->getChain(), LN0->getBasePtr(), 9686 LN0->getMemoryVT(), 9687 LN0->getMemOperand()); 9688 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 9689 return NewLoad; 9690 } 9691 } 9692 } 9693 9694 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 9695 // where ... are all 'undef'. 9696 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 9697 SmallVector<EVT, 8> VTs; 9698 SDValue V; 9699 unsigned Idx = 0; 9700 unsigned NumDefs = 0; 9701 9702 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 9703 SDValue X = N0.getOperand(i); 9704 if (!X.isUndef()) { 9705 V = X; 9706 Idx = i; 9707 NumDefs++; 9708 } 9709 // Stop if more than one members are non-undef. 9710 if (NumDefs > 1) 9711 break; 9712 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 9713 VT.getVectorElementType(), 9714 X.getValueType().getVectorNumElements())); 9715 } 9716 9717 if (NumDefs == 0) 9718 return DAG.getUNDEF(VT); 9719 9720 if (NumDefs == 1) { 9721 assert(V.getNode() && "The single defined operand is empty!"); 9722 SmallVector<SDValue, 8> Opnds; 9723 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 9724 if (i != Idx) { 9725 Opnds.push_back(DAG.getUNDEF(VTs[i])); 9726 continue; 9727 } 9728 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 9729 AddToWorklist(NV.getNode()); 9730 Opnds.push_back(NV); 9731 } 9732 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 9733 } 9734 } 9735 9736 // Fold truncate of a bitcast of a vector to an extract of the low vector 9737 // element. 9738 // 9739 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 9740 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 9741 SDValue VecSrc = N0.getOperand(0); 9742 EVT SrcVT = VecSrc.getValueType(); 9743 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 9744 (!LegalOperations || 9745 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 9746 SDLoc SL(N); 9747 9748 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 9749 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 9750 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 9751 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 9752 } 9753 } 9754 9755 // Simplify the operands using demanded-bits information. 9756 if (!VT.isVector() && 9757 SimplifyDemandedBits(SDValue(N, 0))) 9758 return SDValue(N, 0); 9759 9760 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 9761 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 9762 // When the adde's carry is not used. 9763 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 9764 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 9765 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 9766 SDLoc SL(N); 9767 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 9768 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 9769 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 9770 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 9771 } 9772 9773 // fold (truncate (extract_subvector(ext x))) -> 9774 // (extract_subvector x) 9775 // TODO: This can be generalized to cover cases where the truncate and extract 9776 // do not fully cancel each other out. 9777 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 9778 SDValue N00 = N0.getOperand(0); 9779 if (N00.getOpcode() == ISD::SIGN_EXTEND || 9780 N00.getOpcode() == ISD::ZERO_EXTEND || 9781 N00.getOpcode() == ISD::ANY_EXTEND) { 9782 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 9783 VT.getVectorElementType()) 9784 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 9785 N00.getOperand(0), N0.getOperand(1)); 9786 } 9787 } 9788 9789 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 9790 return NewVSel; 9791 9792 return SDValue(); 9793 } 9794 9795 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 9796 SDValue Elt = N->getOperand(i); 9797 if (Elt.getOpcode() != ISD::MERGE_VALUES) 9798 return Elt.getNode(); 9799 return Elt.getOperand(Elt.getResNo()).getNode(); 9800 } 9801 9802 /// build_pair (load, load) -> load 9803 /// if load locations are consecutive. 9804 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 9805 assert(N->getOpcode() == ISD::BUILD_PAIR); 9806 9807 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 9808 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 9809 9810 // A BUILD_PAIR is always having the least significant part in elt 0 and the 9811 // most significant part in elt 1. So when combining into one large load, we 9812 // need to consider the endianness. 9813 if (DAG.getDataLayout().isBigEndian()) 9814 std::swap(LD1, LD2); 9815 9816 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 9817 LD1->getAddressSpace() != LD2->getAddressSpace()) 9818 return SDValue(); 9819 EVT LD1VT = LD1->getValueType(0); 9820 unsigned LD1Bytes = LD1VT.getStoreSize(); 9821 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 9822 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 9823 unsigned Align = LD1->getAlignment(); 9824 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 9825 VT.getTypeForEVT(*DAG.getContext())); 9826 9827 if (NewAlign <= Align && 9828 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 9829 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 9830 LD1->getPointerInfo(), Align); 9831 } 9832 9833 return SDValue(); 9834 } 9835 9836 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 9837 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 9838 // and Lo parts; on big-endian machines it doesn't. 9839 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 9840 } 9841 9842 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 9843 const TargetLowering &TLI) { 9844 // If this is not a bitcast to an FP type or if the target doesn't have 9845 // IEEE754-compliant FP logic, we're done. 9846 EVT VT = N->getValueType(0); 9847 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 9848 return SDValue(); 9849 9850 // TODO: Handle cases where the integer constant is a different scalar 9851 // bitwidth to the FP. 9852 SDValue N0 = N->getOperand(0); 9853 EVT SourceVT = N0.getValueType(); 9854 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits()) 9855 return SDValue(); 9856 9857 unsigned FPOpcode; 9858 APInt SignMask; 9859 switch (N0.getOpcode()) { 9860 case ISD::AND: 9861 FPOpcode = ISD::FABS; 9862 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits()); 9863 break; 9864 case ISD::XOR: 9865 FPOpcode = ISD::FNEG; 9866 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 9867 break; 9868 case ISD::OR: 9869 FPOpcode = ISD::FABS; 9870 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 9871 break; 9872 default: 9873 return SDValue(); 9874 } 9875 9876 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 9877 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 9878 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) -> 9879 // fneg (fabs X) 9880 SDValue LogicOp0 = N0.getOperand(0); 9881 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true); 9882 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 9883 LogicOp0.getOpcode() == ISD::BITCAST && 9884 LogicOp0.getOperand(0).getValueType() == VT) { 9885 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0)); 9886 NumFPLogicOpsConv++; 9887 if (N0.getOpcode() == ISD::OR) 9888 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp); 9889 return FPOp; 9890 } 9891 9892 return SDValue(); 9893 } 9894 9895 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 9896 SDValue N0 = N->getOperand(0); 9897 EVT VT = N->getValueType(0); 9898 9899 if (N0.isUndef()) 9900 return DAG.getUNDEF(VT); 9901 9902 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 9903 // Only do this before legalize types, since we might create an illegal 9904 // scalar type. Even if we knew we wouldn't create an illegal scalar type 9905 // we can only do this before legalize ops, since the target maybe 9906 // depending on the bitcast. 9907 // First check to see if this is all constant. 9908 if (!LegalTypes && 9909 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 9910 VT.isVector() && cast<BuildVectorSDNode>(N0)->isConstant()) 9911 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), 9912 VT.getVectorElementType()); 9913 9914 // If the input is a constant, let getNode fold it. 9915 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 9916 // If we can't allow illegal operations, we need to check that this is just 9917 // a fp -> int or int -> conversion and that the resulting operation will 9918 // be legal. 9919 if (!LegalOperations || 9920 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 9921 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 9922 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 9923 TLI.isOperationLegal(ISD::Constant, VT))) { 9924 SDValue C = DAG.getBitcast(VT, N0); 9925 if (C.getNode() != N) 9926 return C; 9927 } 9928 } 9929 9930 // (conv (conv x, t1), t2) -> (conv x, t2) 9931 if (N0.getOpcode() == ISD::BITCAST) 9932 return DAG.getBitcast(VT, N0.getOperand(0)); 9933 9934 // fold (conv (load x)) -> (load (conv*)x) 9935 // If the resultant load doesn't need a higher alignment than the original! 9936 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9937 // Do not remove the cast if the types differ in endian layout. 9938 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 9939 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 9940 // If the load is volatile, we only want to change the load type if the 9941 // resulting load is legal. Otherwise we might increase the number of 9942 // memory accesses. We don't care if the original type was legal or not 9943 // as we assume software couldn't rely on the number of accesses of an 9944 // illegal type. 9945 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9946 TLI.isOperationLegal(ISD::LOAD, VT)) && 9947 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 9948 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9949 unsigned OrigAlign = LN0->getAlignment(); 9950 9951 bool Fast = false; 9952 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9953 LN0->getAddressSpace(), OrigAlign, &Fast) && 9954 Fast) { 9955 SDValue Load = 9956 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9957 LN0->getPointerInfo(), OrigAlign, 9958 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9959 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9960 return Load; 9961 } 9962 } 9963 9964 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 9965 return V; 9966 9967 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 9968 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 9969 // 9970 // For ppc_fp128: 9971 // fold (bitcast (fneg x)) -> 9972 // flipbit = signbit 9973 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9974 // 9975 // fold (bitcast (fabs x)) -> 9976 // flipbit = (and (extract_element (bitcast x), 0), signbit) 9977 // (xor (bitcast x) (build_pair flipbit, flipbit)) 9978 // This often reduces constant pool loads. 9979 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 9980 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 9981 N0.getNode()->hasOneUse() && VT.isInteger() && 9982 !VT.isVector() && !N0.getValueType().isVector()) { 9983 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 9984 AddToWorklist(NewConv.getNode()); 9985 9986 SDLoc DL(N); 9987 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 9988 assert(VT.getSizeInBits() == 128); 9989 SDValue SignBit = DAG.getConstant( 9990 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 9991 SDValue FlipBit; 9992 if (N0.getOpcode() == ISD::FNEG) { 9993 FlipBit = SignBit; 9994 AddToWorklist(FlipBit.getNode()); 9995 } else { 9996 assert(N0.getOpcode() == ISD::FABS); 9997 SDValue Hi = 9998 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 9999 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 10000 SDLoc(NewConv))); 10001 AddToWorklist(Hi.getNode()); 10002 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 10003 AddToWorklist(FlipBit.getNode()); 10004 } 10005 SDValue FlipBits = 10006 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 10007 AddToWorklist(FlipBits.getNode()); 10008 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 10009 } 10010 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 10011 if (N0.getOpcode() == ISD::FNEG) 10012 return DAG.getNode(ISD::XOR, DL, VT, 10013 NewConv, DAG.getConstant(SignBit, DL, VT)); 10014 assert(N0.getOpcode() == ISD::FABS); 10015 return DAG.getNode(ISD::AND, DL, VT, 10016 NewConv, DAG.getConstant(~SignBit, DL, VT)); 10017 } 10018 10019 // fold (bitconvert (fcopysign cst, x)) -> 10020 // (or (and (bitconvert x), sign), (and cst, (not sign))) 10021 // Note that we don't handle (copysign x, cst) because this can always be 10022 // folded to an fneg or fabs. 10023 // 10024 // For ppc_fp128: 10025 // fold (bitcast (fcopysign cst, x)) -> 10026 // flipbit = (and (extract_element 10027 // (xor (bitcast cst), (bitcast x)), 0), 10028 // signbit) 10029 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 10030 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 10031 isa<ConstantFPSDNode>(N0.getOperand(0)) && 10032 VT.isInteger() && !VT.isVector()) { 10033 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 10034 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 10035 if (isTypeLegal(IntXVT)) { 10036 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 10037 AddToWorklist(X.getNode()); 10038 10039 // If X has a different width than the result/lhs, sext it or truncate it. 10040 unsigned VTWidth = VT.getSizeInBits(); 10041 if (OrigXWidth < VTWidth) { 10042 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 10043 AddToWorklist(X.getNode()); 10044 } else if (OrigXWidth > VTWidth) { 10045 // To get the sign bit in the right place, we have to shift it right 10046 // before truncating. 10047 SDLoc DL(X); 10048 X = DAG.getNode(ISD::SRL, DL, 10049 X.getValueType(), X, 10050 DAG.getConstant(OrigXWidth-VTWidth, DL, 10051 X.getValueType())); 10052 AddToWorklist(X.getNode()); 10053 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 10054 AddToWorklist(X.getNode()); 10055 } 10056 10057 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 10058 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 10059 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 10060 AddToWorklist(Cst.getNode()); 10061 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 10062 AddToWorklist(X.getNode()); 10063 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 10064 AddToWorklist(XorResult.getNode()); 10065 SDValue XorResult64 = DAG.getNode( 10066 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 10067 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 10068 SDLoc(XorResult))); 10069 AddToWorklist(XorResult64.getNode()); 10070 SDValue FlipBit = 10071 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 10072 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 10073 AddToWorklist(FlipBit.getNode()); 10074 SDValue FlipBits = 10075 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 10076 AddToWorklist(FlipBits.getNode()); 10077 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 10078 } 10079 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 10080 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 10081 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 10082 AddToWorklist(X.getNode()); 10083 10084 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 10085 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 10086 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 10087 AddToWorklist(Cst.getNode()); 10088 10089 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 10090 } 10091 } 10092 10093 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 10094 if (N0.getOpcode() == ISD::BUILD_PAIR) 10095 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 10096 return CombineLD; 10097 10098 // Remove double bitcasts from shuffles - this is often a legacy of 10099 // XformToShuffleWithZero being used to combine bitmaskings (of 10100 // float vectors bitcast to integer vectors) into shuffles. 10101 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 10102 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 10103 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 10104 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 10105 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 10106 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 10107 10108 // If operands are a bitcast, peek through if it casts the original VT. 10109 // If operands are a constant, just bitcast back to original VT. 10110 auto PeekThroughBitcast = [&](SDValue Op) { 10111 if (Op.getOpcode() == ISD::BITCAST && 10112 Op.getOperand(0).getValueType() == VT) 10113 return SDValue(Op.getOperand(0)); 10114 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 10115 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 10116 return DAG.getBitcast(VT, Op); 10117 return SDValue(); 10118 }; 10119 10120 // FIXME: If either input vector is bitcast, try to convert the shuffle to 10121 // the result type of this bitcast. This would eliminate at least one 10122 // bitcast. See the transform in InstCombine. 10123 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 10124 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 10125 if (!(SV0 && SV1)) 10126 return SDValue(); 10127 10128 int MaskScale = 10129 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 10130 SmallVector<int, 8> NewMask; 10131 for (int M : SVN->getMask()) 10132 for (int i = 0; i != MaskScale; ++i) 10133 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 10134 10135 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10136 if (!LegalMask) { 10137 std::swap(SV0, SV1); 10138 ShuffleVectorSDNode::commuteMask(NewMask); 10139 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10140 } 10141 10142 if (LegalMask) 10143 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 10144 } 10145 10146 return SDValue(); 10147 } 10148 10149 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 10150 EVT VT = N->getValueType(0); 10151 return CombineConsecutiveLoads(N, VT); 10152 } 10153 10154 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 10155 /// operands. DstEltVT indicates the destination element value type. 10156 SDValue DAGCombiner:: 10157 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 10158 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 10159 10160 // If this is already the right type, we're done. 10161 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 10162 10163 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 10164 unsigned DstBitSize = DstEltVT.getSizeInBits(); 10165 10166 // If this is a conversion of N elements of one type to N elements of another 10167 // type, convert each element. This handles FP<->INT cases. 10168 if (SrcBitSize == DstBitSize) { 10169 SmallVector<SDValue, 8> Ops; 10170 for (SDValue Op : BV->op_values()) { 10171 // If the vector element type is not legal, the BUILD_VECTOR operands 10172 // are promoted and implicitly truncated. Make that explicit here. 10173 if (Op.getValueType() != SrcEltVT) 10174 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 10175 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 10176 AddToWorklist(Ops.back().getNode()); 10177 } 10178 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10179 BV->getValueType(0).getVectorNumElements()); 10180 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 10181 } 10182 10183 // Otherwise, we're growing or shrinking the elements. To avoid having to 10184 // handle annoying details of growing/shrinking FP values, we convert them to 10185 // int first. 10186 if (SrcEltVT.isFloatingPoint()) { 10187 // Convert the input float vector to a int vector where the elements are the 10188 // same sizes. 10189 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 10190 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 10191 SrcEltVT = IntVT; 10192 } 10193 10194 // Now we know the input is an integer vector. If the output is a FP type, 10195 // convert to integer first, then to FP of the right size. 10196 if (DstEltVT.isFloatingPoint()) { 10197 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 10198 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 10199 10200 // Next, convert to FP elements of the same size. 10201 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 10202 } 10203 10204 SDLoc DL(BV); 10205 10206 // Okay, we know the src/dst types are both integers of differing types. 10207 // Handling growing first. 10208 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 10209 if (SrcBitSize < DstBitSize) { 10210 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 10211 10212 SmallVector<SDValue, 8> Ops; 10213 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 10214 i += NumInputsPerOutput) { 10215 bool isLE = DAG.getDataLayout().isLittleEndian(); 10216 APInt NewBits = APInt(DstBitSize, 0); 10217 bool EltIsUndef = true; 10218 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 10219 // Shift the previously computed bits over. 10220 NewBits <<= SrcBitSize; 10221 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 10222 if (Op.isUndef()) continue; 10223 EltIsUndef = false; 10224 10225 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 10226 zextOrTrunc(SrcBitSize).zext(DstBitSize); 10227 } 10228 10229 if (EltIsUndef) 10230 Ops.push_back(DAG.getUNDEF(DstEltVT)); 10231 else 10232 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 10233 } 10234 10235 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 10236 return DAG.getBuildVector(VT, DL, Ops); 10237 } 10238 10239 // Finally, this must be the case where we are shrinking elements: each input 10240 // turns into multiple outputs. 10241 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 10242 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10243 NumOutputsPerInput*BV->getNumOperands()); 10244 SmallVector<SDValue, 8> Ops; 10245 10246 for (const SDValue &Op : BV->op_values()) { 10247 if (Op.isUndef()) { 10248 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 10249 continue; 10250 } 10251 10252 APInt OpVal = cast<ConstantSDNode>(Op)-> 10253 getAPIntValue().zextOrTrunc(SrcBitSize); 10254 10255 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 10256 APInt ThisVal = OpVal.trunc(DstBitSize); 10257 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 10258 OpVal.lshrInPlace(DstBitSize); 10259 } 10260 10261 // For big endian targets, swap the order of the pieces of each element. 10262 if (DAG.getDataLayout().isBigEndian()) 10263 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 10264 } 10265 10266 return DAG.getBuildVector(VT, DL, Ops); 10267 } 10268 10269 static bool isContractable(SDNode *N) { 10270 SDNodeFlags F = N->getFlags(); 10271 return F.hasAllowContract() || F.hasAllowReassociation(); 10272 } 10273 10274 /// Try to perform FMA combining on a given FADD node. 10275 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 10276 SDValue N0 = N->getOperand(0); 10277 SDValue N1 = N->getOperand(1); 10278 EVT VT = N->getValueType(0); 10279 SDLoc SL(N); 10280 10281 const TargetOptions &Options = DAG.getTarget().Options; 10282 10283 // Floating-point multiply-add with intermediate rounding. 10284 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10285 10286 // Floating-point multiply-add without intermediate rounding. 10287 bool HasFMA = 10288 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10289 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10290 10291 // No valid opcode, do not combine. 10292 if (!HasFMAD && !HasFMA) 10293 return SDValue(); 10294 10295 SDNodeFlags Flags = N->getFlags(); 10296 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10297 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10298 CanFuse || HasFMAD); 10299 // If the addition is not contractable, do not combine. 10300 if (!AllowFusionGlobally && !isContractable(N)) 10301 return SDValue(); 10302 10303 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10304 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10305 return SDValue(); 10306 10307 // Always prefer FMAD to FMA for precision. 10308 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10309 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10310 10311 // Is the node an FMUL and contractable either due to global flags or 10312 // SDNodeFlags. 10313 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10314 if (N.getOpcode() != ISD::FMUL) 10315 return false; 10316 return AllowFusionGlobally || isContractable(N.getNode()); 10317 }; 10318 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 10319 // prefer to fold the multiply with fewer uses. 10320 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 10321 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 10322 std::swap(N0, N1); 10323 } 10324 10325 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 10326 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10327 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10328 N0.getOperand(0), N0.getOperand(1), N1, Flags); 10329 } 10330 10331 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 10332 // Note: Commutes FADD operands. 10333 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10334 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10335 N1.getOperand(0), N1.getOperand(1), N0, Flags); 10336 } 10337 10338 // Look through FP_EXTEND nodes to do more combining. 10339 10340 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 10341 if (N0.getOpcode() == ISD::FP_EXTEND) { 10342 SDValue N00 = N0.getOperand(0); 10343 if (isContractableFMUL(N00) && 10344 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10345 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10346 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10347 N00.getOperand(0)), 10348 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10349 N00.getOperand(1)), N1, Flags); 10350 } 10351 } 10352 10353 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 10354 // Note: Commutes FADD operands. 10355 if (N1.getOpcode() == ISD::FP_EXTEND) { 10356 SDValue N10 = N1.getOperand(0); 10357 if (isContractableFMUL(N10) && 10358 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10359 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10360 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10361 N10.getOperand(0)), 10362 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10363 N10.getOperand(1)), N0, Flags); 10364 } 10365 } 10366 10367 // More folding opportunities when target permits. 10368 if (Aggressive) { 10369 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 10370 if (CanFuse && 10371 N0.getOpcode() == PreferredFusedOpcode && 10372 N0.getOperand(2).getOpcode() == ISD::FMUL && 10373 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 10374 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10375 N0.getOperand(0), N0.getOperand(1), 10376 DAG.getNode(PreferredFusedOpcode, SL, VT, 10377 N0.getOperand(2).getOperand(0), 10378 N0.getOperand(2).getOperand(1), 10379 N1, Flags), Flags); 10380 } 10381 10382 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 10383 if (CanFuse && 10384 N1->getOpcode() == PreferredFusedOpcode && 10385 N1.getOperand(2).getOpcode() == ISD::FMUL && 10386 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 10387 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10388 N1.getOperand(0), N1.getOperand(1), 10389 DAG.getNode(PreferredFusedOpcode, SL, VT, 10390 N1.getOperand(2).getOperand(0), 10391 N1.getOperand(2).getOperand(1), 10392 N0, Flags), Flags); 10393 } 10394 10395 10396 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 10397 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 10398 auto FoldFAddFMAFPExtFMul = [&] ( 10399 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10400 SDNodeFlags Flags) { 10401 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 10402 DAG.getNode(PreferredFusedOpcode, SL, VT, 10403 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10404 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10405 Z, Flags), Flags); 10406 }; 10407 if (N0.getOpcode() == PreferredFusedOpcode) { 10408 SDValue N02 = N0.getOperand(2); 10409 if (N02.getOpcode() == ISD::FP_EXTEND) { 10410 SDValue N020 = N02.getOperand(0); 10411 if (isContractableFMUL(N020) && 10412 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10413 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 10414 N020.getOperand(0), N020.getOperand(1), 10415 N1, Flags); 10416 } 10417 } 10418 } 10419 10420 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 10421 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 10422 // FIXME: This turns two single-precision and one double-precision 10423 // operation into two double-precision operations, which might not be 10424 // interesting for all targets, especially GPUs. 10425 auto FoldFAddFPExtFMAFMul = [&] ( 10426 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10427 SDNodeFlags Flags) { 10428 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10429 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 10430 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 10431 DAG.getNode(PreferredFusedOpcode, SL, VT, 10432 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10433 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10434 Z, Flags), Flags); 10435 }; 10436 if (N0.getOpcode() == ISD::FP_EXTEND) { 10437 SDValue N00 = N0.getOperand(0); 10438 if (N00.getOpcode() == PreferredFusedOpcode) { 10439 SDValue N002 = N00.getOperand(2); 10440 if (isContractableFMUL(N002) && 10441 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10442 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 10443 N002.getOperand(0), N002.getOperand(1), 10444 N1, Flags); 10445 } 10446 } 10447 } 10448 10449 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 10450 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 10451 if (N1.getOpcode() == PreferredFusedOpcode) { 10452 SDValue N12 = N1.getOperand(2); 10453 if (N12.getOpcode() == ISD::FP_EXTEND) { 10454 SDValue N120 = N12.getOperand(0); 10455 if (isContractableFMUL(N120) && 10456 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10457 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 10458 N120.getOperand(0), N120.getOperand(1), 10459 N0, Flags); 10460 } 10461 } 10462 } 10463 10464 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 10465 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 10466 // FIXME: This turns two single-precision and one double-precision 10467 // operation into two double-precision operations, which might not be 10468 // interesting for all targets, especially GPUs. 10469 if (N1.getOpcode() == ISD::FP_EXTEND) { 10470 SDValue N10 = N1.getOperand(0); 10471 if (N10.getOpcode() == PreferredFusedOpcode) { 10472 SDValue N102 = N10.getOperand(2); 10473 if (isContractableFMUL(N102) && 10474 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10475 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 10476 N102.getOperand(0), N102.getOperand(1), 10477 N0, Flags); 10478 } 10479 } 10480 } 10481 } 10482 10483 return SDValue(); 10484 } 10485 10486 /// Try to perform FMA combining on a given FSUB node. 10487 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 10488 SDValue N0 = N->getOperand(0); 10489 SDValue N1 = N->getOperand(1); 10490 EVT VT = N->getValueType(0); 10491 SDLoc SL(N); 10492 10493 const TargetOptions &Options = DAG.getTarget().Options; 10494 // Floating-point multiply-add with intermediate rounding. 10495 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10496 10497 // Floating-point multiply-add without intermediate rounding. 10498 bool HasFMA = 10499 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10500 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10501 10502 // No valid opcode, do not combine. 10503 if (!HasFMAD && !HasFMA) 10504 return SDValue(); 10505 10506 const SDNodeFlags Flags = N->getFlags(); 10507 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10508 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10509 CanFuse || HasFMAD); 10510 10511 // If the subtraction is not contractable, do not combine. 10512 if (!AllowFusionGlobally && !isContractable(N)) 10513 return SDValue(); 10514 10515 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10516 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10517 return SDValue(); 10518 10519 // Always prefer FMAD to FMA for precision. 10520 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10521 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10522 10523 // Is the node an FMUL and contractable either due to global flags or 10524 // SDNodeFlags. 10525 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10526 if (N.getOpcode() != ISD::FMUL) 10527 return false; 10528 return AllowFusionGlobally || isContractable(N.getNode()); 10529 }; 10530 10531 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 10532 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10533 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10534 N0.getOperand(0), N0.getOperand(1), 10535 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10536 } 10537 10538 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 10539 // Note: Commutes FSUB operands. 10540 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10541 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10542 DAG.getNode(ISD::FNEG, SL, VT, 10543 N1.getOperand(0)), 10544 N1.getOperand(1), N0, Flags); 10545 } 10546 10547 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 10548 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 10549 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 10550 SDValue N00 = N0.getOperand(0).getOperand(0); 10551 SDValue N01 = N0.getOperand(0).getOperand(1); 10552 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10553 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 10554 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10555 } 10556 10557 // Look through FP_EXTEND nodes to do more combining. 10558 10559 // fold (fsub (fpext (fmul x, y)), z) 10560 // -> (fma (fpext x), (fpext y), (fneg z)) 10561 if (N0.getOpcode() == ISD::FP_EXTEND) { 10562 SDValue N00 = N0.getOperand(0); 10563 if (isContractableFMUL(N00) && 10564 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10565 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10566 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10567 N00.getOperand(0)), 10568 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10569 N00.getOperand(1)), 10570 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 10571 } 10572 } 10573 10574 // fold (fsub x, (fpext (fmul y, z))) 10575 // -> (fma (fneg (fpext y)), (fpext z), x) 10576 // Note: Commutes FSUB operands. 10577 if (N1.getOpcode() == ISD::FP_EXTEND) { 10578 SDValue N10 = N1.getOperand(0); 10579 if (isContractableFMUL(N10) && 10580 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10581 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10582 DAG.getNode(ISD::FNEG, SL, VT, 10583 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10584 N10.getOperand(0))), 10585 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10586 N10.getOperand(1)), 10587 N0, Flags); 10588 } 10589 } 10590 10591 // fold (fsub (fpext (fneg (fmul, x, y))), z) 10592 // -> (fneg (fma (fpext x), (fpext y), z)) 10593 // Note: This could be removed with appropriate canonicalization of the 10594 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10595 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10596 // from implementing the canonicalization in visitFSUB. 10597 if (N0.getOpcode() == ISD::FP_EXTEND) { 10598 SDValue N00 = N0.getOperand(0); 10599 if (N00.getOpcode() == ISD::FNEG) { 10600 SDValue N000 = N00.getOperand(0); 10601 if (isContractableFMUL(N000) && 10602 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10603 return DAG.getNode(ISD::FNEG, SL, VT, 10604 DAG.getNode(PreferredFusedOpcode, SL, VT, 10605 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10606 N000.getOperand(0)), 10607 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10608 N000.getOperand(1)), 10609 N1, Flags)); 10610 } 10611 } 10612 } 10613 10614 // fold (fsub (fneg (fpext (fmul, x, y))), z) 10615 // -> (fneg (fma (fpext x)), (fpext y), z) 10616 // Note: This could be removed with appropriate canonicalization of the 10617 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 10618 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 10619 // from implementing the canonicalization in visitFSUB. 10620 if (N0.getOpcode() == ISD::FNEG) { 10621 SDValue N00 = N0.getOperand(0); 10622 if (N00.getOpcode() == ISD::FP_EXTEND) { 10623 SDValue N000 = N00.getOperand(0); 10624 if (isContractableFMUL(N000) && 10625 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 10626 return DAG.getNode(ISD::FNEG, SL, VT, 10627 DAG.getNode(PreferredFusedOpcode, SL, VT, 10628 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10629 N000.getOperand(0)), 10630 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10631 N000.getOperand(1)), 10632 N1, Flags)); 10633 } 10634 } 10635 } 10636 10637 // More folding opportunities when target permits. 10638 if (Aggressive) { 10639 // fold (fsub (fma x, y, (fmul u, v)), z) 10640 // -> (fma x, y (fma u, v, (fneg z))) 10641 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && 10642 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 10643 N0.getOperand(2)->hasOneUse()) { 10644 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10645 N0.getOperand(0), N0.getOperand(1), 10646 DAG.getNode(PreferredFusedOpcode, SL, VT, 10647 N0.getOperand(2).getOperand(0), 10648 N0.getOperand(2).getOperand(1), 10649 DAG.getNode(ISD::FNEG, SL, VT, 10650 N1), Flags), Flags); 10651 } 10652 10653 // fold (fsub x, (fma y, z, (fmul u, v))) 10654 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 10655 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && 10656 isContractableFMUL(N1.getOperand(2))) { 10657 SDValue N20 = N1.getOperand(2).getOperand(0); 10658 SDValue N21 = N1.getOperand(2).getOperand(1); 10659 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10660 DAG.getNode(ISD::FNEG, SL, VT, 10661 N1.getOperand(0)), 10662 N1.getOperand(1), 10663 DAG.getNode(PreferredFusedOpcode, SL, VT, 10664 DAG.getNode(ISD::FNEG, SL, VT, N20), 10665 N21, N0, Flags), Flags); 10666 } 10667 10668 10669 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 10670 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 10671 if (N0.getOpcode() == PreferredFusedOpcode) { 10672 SDValue N02 = N0.getOperand(2); 10673 if (N02.getOpcode() == ISD::FP_EXTEND) { 10674 SDValue N020 = N02.getOperand(0); 10675 if (isContractableFMUL(N020) && 10676 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10677 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10678 N0.getOperand(0), N0.getOperand(1), 10679 DAG.getNode(PreferredFusedOpcode, SL, VT, 10680 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10681 N020.getOperand(0)), 10682 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10683 N020.getOperand(1)), 10684 DAG.getNode(ISD::FNEG, SL, VT, 10685 N1), Flags), Flags); 10686 } 10687 } 10688 } 10689 10690 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 10691 // -> (fma (fpext x), (fpext y), 10692 // (fma (fpext u), (fpext v), (fneg z))) 10693 // FIXME: This turns two single-precision and one double-precision 10694 // operation into two double-precision operations, which might not be 10695 // interesting for all targets, especially GPUs. 10696 if (N0.getOpcode() == ISD::FP_EXTEND) { 10697 SDValue N00 = N0.getOperand(0); 10698 if (N00.getOpcode() == PreferredFusedOpcode) { 10699 SDValue N002 = N00.getOperand(2); 10700 if (isContractableFMUL(N002) && 10701 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10702 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10703 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10704 N00.getOperand(0)), 10705 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10706 N00.getOperand(1)), 10707 DAG.getNode(PreferredFusedOpcode, SL, VT, 10708 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10709 N002.getOperand(0)), 10710 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10711 N002.getOperand(1)), 10712 DAG.getNode(ISD::FNEG, SL, VT, 10713 N1), Flags), Flags); 10714 } 10715 } 10716 } 10717 10718 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 10719 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 10720 if (N1.getOpcode() == PreferredFusedOpcode && 10721 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 10722 SDValue N120 = N1.getOperand(2).getOperand(0); 10723 if (isContractableFMUL(N120) && 10724 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10725 SDValue N1200 = N120.getOperand(0); 10726 SDValue N1201 = N120.getOperand(1); 10727 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10728 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 10729 N1.getOperand(1), 10730 DAG.getNode(PreferredFusedOpcode, SL, VT, 10731 DAG.getNode(ISD::FNEG, SL, VT, 10732 DAG.getNode(ISD::FP_EXTEND, SL, 10733 VT, N1200)), 10734 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10735 N1201), 10736 N0, Flags), Flags); 10737 } 10738 } 10739 10740 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 10741 // -> (fma (fneg (fpext y)), (fpext z), 10742 // (fma (fneg (fpext u)), (fpext v), x)) 10743 // FIXME: This turns two single-precision and one double-precision 10744 // operation into two double-precision operations, which might not be 10745 // interesting for all targets, especially GPUs. 10746 if (N1.getOpcode() == ISD::FP_EXTEND && 10747 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 10748 SDValue CvtSrc = N1.getOperand(0); 10749 SDValue N100 = CvtSrc.getOperand(0); 10750 SDValue N101 = CvtSrc.getOperand(1); 10751 SDValue N102 = CvtSrc.getOperand(2); 10752 if (isContractableFMUL(N102) && 10753 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 10754 SDValue N1020 = N102.getOperand(0); 10755 SDValue N1021 = N102.getOperand(1); 10756 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10757 DAG.getNode(ISD::FNEG, SL, VT, 10758 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10759 N100)), 10760 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 10761 DAG.getNode(PreferredFusedOpcode, SL, VT, 10762 DAG.getNode(ISD::FNEG, SL, VT, 10763 DAG.getNode(ISD::FP_EXTEND, SL, 10764 VT, N1020)), 10765 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10766 N1021), 10767 N0, Flags), Flags); 10768 } 10769 } 10770 } 10771 10772 return SDValue(); 10773 } 10774 10775 /// Try to perform FMA combining on a given FMUL node based on the distributive 10776 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 10777 /// subtraction instead of addition). 10778 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 10779 SDValue N0 = N->getOperand(0); 10780 SDValue N1 = N->getOperand(1); 10781 EVT VT = N->getValueType(0); 10782 SDLoc SL(N); 10783 const SDNodeFlags Flags = N->getFlags(); 10784 10785 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 10786 10787 const TargetOptions &Options = DAG.getTarget().Options; 10788 10789 // The transforms below are incorrect when x == 0 and y == inf, because the 10790 // intermediate multiplication produces a nan. 10791 if (!Options.NoInfsFPMath) 10792 return SDValue(); 10793 10794 // Floating-point multiply-add without intermediate rounding. 10795 bool HasFMA = 10796 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 10797 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10798 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10799 10800 // Floating-point multiply-add with intermediate rounding. This can result 10801 // in a less precise result due to the changed rounding order. 10802 bool HasFMAD = Options.UnsafeFPMath && 10803 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10804 10805 // No valid opcode, do not combine. 10806 if (!HasFMAD && !HasFMA) 10807 return SDValue(); 10808 10809 // Always prefer FMAD to FMA for precision. 10810 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10811 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10812 10813 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y) 10814 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y)) 10815 auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10816 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 10817 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) { 10818 if (C->isExactlyValue(+1.0)) 10819 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10820 Y, Flags); 10821 if (C->isExactlyValue(-1.0)) 10822 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10823 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10824 } 10825 } 10826 return SDValue(); 10827 }; 10828 10829 if (SDValue FMA = FuseFADD(N0, N1, Flags)) 10830 return FMA; 10831 if (SDValue FMA = FuseFADD(N1, N0, Flags)) 10832 return FMA; 10833 10834 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y) 10835 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y)) 10836 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y)) 10837 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y) 10838 auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 10839 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 10840 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) { 10841 if (C0->isExactlyValue(+1.0)) 10842 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10843 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10844 Y, Flags); 10845 if (C0->isExactlyValue(-1.0)) 10846 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10847 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 10848 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10849 } 10850 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) { 10851 if (C1->isExactlyValue(+1.0)) 10852 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10853 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 10854 if (C1->isExactlyValue(-1.0)) 10855 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 10856 Y, Flags); 10857 } 10858 } 10859 return SDValue(); 10860 }; 10861 10862 if (SDValue FMA = FuseFSUB(N0, N1, Flags)) 10863 return FMA; 10864 if (SDValue FMA = FuseFSUB(N1, N0, Flags)) 10865 return FMA; 10866 10867 return SDValue(); 10868 } 10869 10870 SDValue DAGCombiner::visitFADD(SDNode *N) { 10871 SDValue N0 = N->getOperand(0); 10872 SDValue N1 = N->getOperand(1); 10873 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 10874 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 10875 EVT VT = N->getValueType(0); 10876 SDLoc DL(N); 10877 const TargetOptions &Options = DAG.getTarget().Options; 10878 const SDNodeFlags Flags = N->getFlags(); 10879 10880 // fold vector ops 10881 if (VT.isVector()) 10882 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10883 return FoldedVOp; 10884 10885 // fold (fadd c1, c2) -> c1 + c2 10886 if (N0CFP && N1CFP) 10887 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 10888 10889 // canonicalize constant to RHS 10890 if (N0CFP && !N1CFP) 10891 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 10892 10893 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) 10894 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true); 10895 if (N1C && N1C->isZero()) 10896 if (N1C->isNegative() || Options.UnsafeFPMath || Flags.hasNoSignedZeros()) 10897 return N0; 10898 10899 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10900 return NewSel; 10901 10902 // fold (fadd A, (fneg B)) -> (fsub A, B) 10903 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10904 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 10905 return DAG.getNode(ISD::FSUB, DL, VT, N0, 10906 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 10907 10908 // fold (fadd (fneg A), B) -> (fsub B, A) 10909 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 10910 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 10911 return DAG.getNode(ISD::FSUB, DL, VT, N1, 10912 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 10913 10914 auto isFMulNegTwo = [](SDValue FMul) { 10915 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL) 10916 return false; 10917 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true); 10918 return C && C->isExactlyValue(-2.0); 10919 }; 10920 10921 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B) 10922 if (isFMulNegTwo(N0)) { 10923 SDValue B = N0.getOperand(0); 10924 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags); 10925 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add, Flags); 10926 } 10927 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B) 10928 if (isFMulNegTwo(N1)) { 10929 SDValue B = N1.getOperand(0); 10930 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags); 10931 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add, Flags); 10932 } 10933 10934 // No FP constant should be created after legalization as Instruction 10935 // Selection pass has a hard time dealing with FP constants. 10936 bool AllowNewConst = (Level < AfterLegalizeDAG); 10937 10938 // If 'unsafe math' or nnan is enabled, fold lots of things. 10939 if ((Options.UnsafeFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 10940 // If allowed, fold (fadd (fneg x), x) -> 0.0 10941 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 10942 return DAG.getConstantFP(0.0, DL, VT); 10943 10944 // If allowed, fold (fadd x, (fneg x)) -> 0.0 10945 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 10946 return DAG.getConstantFP(0.0, DL, VT); 10947 } 10948 10949 // If 'unsafe math' or reassoc and nsz, fold lots of things. 10950 // TODO: break out portions of the transformations below for which Unsafe is 10951 // considered and which do not require both nsz and reassoc 10952 if ((Options.UnsafeFPMath || 10953 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 10954 AllowNewConst) { 10955 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 10956 if (N1CFP && N0.getOpcode() == ISD::FADD && 10957 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10958 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags); 10959 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags); 10960 } 10961 10962 // We can fold chains of FADD's of the same value into multiplications. 10963 // This transform is not safe in general because we are reducing the number 10964 // of rounding steps. 10965 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 10966 if (N0.getOpcode() == ISD::FMUL) { 10967 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 10968 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 10969 10970 // (fadd (fmul x, c), x) -> (fmul x, c+1) 10971 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 10972 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10973 DAG.getConstantFP(1.0, DL, VT), Flags); 10974 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 10975 } 10976 10977 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 10978 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 10979 N1.getOperand(0) == N1.getOperand(1) && 10980 N0.getOperand(0) == N1.getOperand(0)) { 10981 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 10982 DAG.getConstantFP(2.0, DL, VT), Flags); 10983 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 10984 } 10985 } 10986 10987 if (N1.getOpcode() == ISD::FMUL) { 10988 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 10989 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 10990 10991 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 10992 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 10993 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 10994 DAG.getConstantFP(1.0, DL, VT), Flags); 10995 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 10996 } 10997 10998 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 10999 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 11000 N0.getOperand(0) == N0.getOperand(1) && 11001 N1.getOperand(0) == N0.getOperand(0)) { 11002 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 11003 DAG.getConstantFP(2.0, DL, VT), Flags); 11004 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 11005 } 11006 } 11007 11008 if (N0.getOpcode() == ISD::FADD) { 11009 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 11010 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 11011 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 11012 (N0.getOperand(0) == N1)) { 11013 return DAG.getNode(ISD::FMUL, DL, VT, 11014 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 11015 } 11016 } 11017 11018 if (N1.getOpcode() == ISD::FADD) { 11019 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 11020 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 11021 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 11022 N1.getOperand(0) == N0) { 11023 return DAG.getNode(ISD::FMUL, DL, VT, 11024 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 11025 } 11026 } 11027 11028 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 11029 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 11030 N0.getOperand(0) == N0.getOperand(1) && 11031 N1.getOperand(0) == N1.getOperand(1) && 11032 N0.getOperand(0) == N1.getOperand(0)) { 11033 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 11034 DAG.getConstantFP(4.0, DL, VT), Flags); 11035 } 11036 } 11037 } // enable-unsafe-fp-math 11038 11039 // FADD -> FMA combines: 11040 if (SDValue Fused = visitFADDForFMACombine(N)) { 11041 AddToWorklist(Fused.getNode()); 11042 return Fused; 11043 } 11044 return SDValue(); 11045 } 11046 11047 SDValue DAGCombiner::visitFSUB(SDNode *N) { 11048 SDValue N0 = N->getOperand(0); 11049 SDValue N1 = N->getOperand(1); 11050 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 11051 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 11052 EVT VT = N->getValueType(0); 11053 SDLoc DL(N); 11054 const TargetOptions &Options = DAG.getTarget().Options; 11055 const SDNodeFlags Flags = N->getFlags(); 11056 11057 // fold vector ops 11058 if (VT.isVector()) 11059 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11060 return FoldedVOp; 11061 11062 // fold (fsub c1, c2) -> c1-c2 11063 if (N0CFP && N1CFP) 11064 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 11065 11066 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11067 return NewSel; 11068 11069 // (fsub A, 0) -> A 11070 if (N1CFP && N1CFP->isZero()) { 11071 if (!N1CFP->isNegative() || Options.UnsafeFPMath || 11072 Flags.hasNoSignedZeros()) { 11073 return N0; 11074 } 11075 } 11076 11077 if (N0 == N1) { 11078 // (fsub x, x) -> 0.0 11079 if (Options.UnsafeFPMath || Flags.hasNoNaNs()) 11080 return DAG.getConstantFP(0.0f, DL, VT); 11081 } 11082 11083 // (fsub -0.0, N1) -> -N1 11084 if (N0CFP && N0CFP->isZero()) { 11085 if (N0CFP->isNegative() || 11086 (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) { 11087 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 11088 return GetNegatedExpression(N1, DAG, LegalOperations); 11089 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11090 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 11091 } 11092 } 11093 11094 if ((Options.UnsafeFPMath || 11095 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) 11096 && N1.getOpcode() == ISD::FADD) { 11097 // X - (X + Y) -> -Y 11098 if (N0 == N1->getOperand(0)) 11099 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1), Flags); 11100 // X - (Y + X) -> -Y 11101 if (N0 == N1->getOperand(1)) 11102 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0), Flags); 11103 } 11104 11105 // fold (fsub A, (fneg B)) -> (fadd A, B) 11106 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 11107 return DAG.getNode(ISD::FADD, DL, VT, N0, 11108 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 11109 11110 // FSUB -> FMA combines: 11111 if (SDValue Fused = visitFSUBForFMACombine(N)) { 11112 AddToWorklist(Fused.getNode()); 11113 return Fused; 11114 } 11115 11116 return SDValue(); 11117 } 11118 11119 SDValue DAGCombiner::visitFMUL(SDNode *N) { 11120 SDValue N0 = N->getOperand(0); 11121 SDValue N1 = N->getOperand(1); 11122 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 11123 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 11124 EVT VT = N->getValueType(0); 11125 SDLoc DL(N); 11126 const TargetOptions &Options = DAG.getTarget().Options; 11127 const SDNodeFlags Flags = N->getFlags(); 11128 11129 // fold vector ops 11130 if (VT.isVector()) { 11131 // This just handles C1 * C2 for vectors. Other vector folds are below. 11132 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11133 return FoldedVOp; 11134 } 11135 11136 // fold (fmul c1, c2) -> c1*c2 11137 if (N0CFP && N1CFP) 11138 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 11139 11140 // canonicalize constant to RHS 11141 if (isConstantFPBuildVectorOrConstantFP(N0) && 11142 !isConstantFPBuildVectorOrConstantFP(N1)) 11143 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 11144 11145 // fold (fmul A, 1.0) -> A 11146 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11147 return N0; 11148 11149 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11150 return NewSel; 11151 11152 if (Options.UnsafeFPMath || 11153 (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) { 11154 // fold (fmul A, 0) -> 0 11155 if (N1CFP && N1CFP->isZero()) 11156 return N1; 11157 } 11158 11159 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 11160 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 11161 if (isConstantFPBuildVectorOrConstantFP(N1) && 11162 N0.getOpcode() == ISD::FMUL) { 11163 SDValue N00 = N0.getOperand(0); 11164 SDValue N01 = N0.getOperand(1); 11165 // Avoid an infinite loop by making sure that N00 is not a constant 11166 // (the inner multiply has not been constant folded yet). 11167 if (isConstantFPBuildVectorOrConstantFP(N01) && 11168 !isConstantFPBuildVectorOrConstantFP(N00)) { 11169 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 11170 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 11171 } 11172 } 11173 11174 // Match a special-case: we convert X * 2.0 into fadd. 11175 // fmul (fadd X, X), C -> fmul X, 2.0 * C 11176 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 11177 N0.getOperand(0) == N0.getOperand(1)) { 11178 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 11179 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 11180 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 11181 } 11182 } 11183 11184 // fold (fmul X, 2.0) -> (fadd X, X) 11185 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 11186 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 11187 11188 // fold (fmul X, -1.0) -> (fneg X) 11189 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 11190 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11191 return DAG.getNode(ISD::FNEG, DL, VT, N0); 11192 11193 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 11194 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11195 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11196 // Both can be negated for free, check to see if at least one is cheaper 11197 // negated. 11198 if (LHSNeg == 2 || RHSNeg == 2) 11199 return DAG.getNode(ISD::FMUL, DL, VT, 11200 GetNegatedExpression(N0, DAG, LegalOperations), 11201 GetNegatedExpression(N1, DAG, LegalOperations), 11202 Flags); 11203 } 11204 } 11205 11206 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 11207 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 11208 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 11209 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 11210 TLI.isOperationLegal(ISD::FABS, VT)) { 11211 SDValue Select = N0, X = N1; 11212 if (Select.getOpcode() != ISD::SELECT) 11213 std::swap(Select, X); 11214 11215 SDValue Cond = Select.getOperand(0); 11216 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 11217 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 11218 11219 if (TrueOpnd && FalseOpnd && 11220 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 11221 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 11222 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 11223 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 11224 switch (CC) { 11225 default: break; 11226 case ISD::SETOLT: 11227 case ISD::SETULT: 11228 case ISD::SETOLE: 11229 case ISD::SETULE: 11230 case ISD::SETLT: 11231 case ISD::SETLE: 11232 std::swap(TrueOpnd, FalseOpnd); 11233 LLVM_FALLTHROUGH; 11234 case ISD::SETOGT: 11235 case ISD::SETUGT: 11236 case ISD::SETOGE: 11237 case ISD::SETUGE: 11238 case ISD::SETGT: 11239 case ISD::SETGE: 11240 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 11241 TLI.isOperationLegal(ISD::FNEG, VT)) 11242 return DAG.getNode(ISD::FNEG, DL, VT, 11243 DAG.getNode(ISD::FABS, DL, VT, X)); 11244 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 11245 return DAG.getNode(ISD::FABS, DL, VT, X); 11246 11247 break; 11248 } 11249 } 11250 } 11251 11252 // FMUL -> FMA combines: 11253 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 11254 AddToWorklist(Fused.getNode()); 11255 return Fused; 11256 } 11257 11258 return SDValue(); 11259 } 11260 11261 SDValue DAGCombiner::visitFMA(SDNode *N) { 11262 SDValue N0 = N->getOperand(0); 11263 SDValue N1 = N->getOperand(1); 11264 SDValue N2 = N->getOperand(2); 11265 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11266 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11267 EVT VT = N->getValueType(0); 11268 SDLoc DL(N); 11269 const TargetOptions &Options = DAG.getTarget().Options; 11270 11271 // FMA nodes have flags that propagate to the created nodes. 11272 const SDNodeFlags Flags = N->getFlags(); 11273 bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N); 11274 11275 // Constant fold FMA. 11276 if (isa<ConstantFPSDNode>(N0) && 11277 isa<ConstantFPSDNode>(N1) && 11278 isa<ConstantFPSDNode>(N2)) { 11279 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 11280 } 11281 11282 if (UnsafeFPMath) { 11283 if (N0CFP && N0CFP->isZero()) 11284 return N2; 11285 if (N1CFP && N1CFP->isZero()) 11286 return N2; 11287 } 11288 // TODO: The FMA node should have flags that propagate to these nodes. 11289 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11290 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 11291 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11292 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 11293 11294 // Canonicalize (fma c, x, y) -> (fma x, c, y) 11295 if (isConstantFPBuildVectorOrConstantFP(N0) && 11296 !isConstantFPBuildVectorOrConstantFP(N1)) 11297 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 11298 11299 if (UnsafeFPMath) { 11300 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 11301 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 11302 isConstantFPBuildVectorOrConstantFP(N1) && 11303 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 11304 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11305 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 11306 Flags), Flags); 11307 } 11308 11309 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 11310 if (N0.getOpcode() == ISD::FMUL && 11311 isConstantFPBuildVectorOrConstantFP(N1) && 11312 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 11313 return DAG.getNode(ISD::FMA, DL, VT, 11314 N0.getOperand(0), 11315 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 11316 Flags), 11317 N2); 11318 } 11319 } 11320 11321 // (fma x, 1, y) -> (fadd x, y) 11322 // (fma x, -1, y) -> (fadd (fneg x), y) 11323 if (N1CFP) { 11324 if (N1CFP->isExactlyValue(1.0)) 11325 // TODO: The FMA node should have flags that propagate to this node. 11326 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 11327 11328 if (N1CFP->isExactlyValue(-1.0) && 11329 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 11330 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 11331 AddToWorklist(RHSNeg.getNode()); 11332 // TODO: The FMA node should have flags that propagate to this node. 11333 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 11334 } 11335 11336 // fma (fneg x), K, y -> fma x -K, y 11337 if (N0.getOpcode() == ISD::FNEG && 11338 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 11339 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 11340 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 11341 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 11342 } 11343 } 11344 11345 if (UnsafeFPMath) { 11346 // (fma x, c, x) -> (fmul x, (c+1)) 11347 if (N1CFP && N0 == N2) { 11348 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11349 DAG.getNode(ISD::FADD, DL, VT, N1, 11350 DAG.getConstantFP(1.0, DL, VT), Flags), 11351 Flags); 11352 } 11353 11354 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 11355 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 11356 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11357 DAG.getNode(ISD::FADD, DL, VT, N1, 11358 DAG.getConstantFP(-1.0, DL, VT), Flags), 11359 Flags); 11360 } 11361 } 11362 11363 return SDValue(); 11364 } 11365 11366 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11367 // reciprocal. 11368 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 11369 // Notice that this is not always beneficial. One reason is different targets 11370 // may have different costs for FDIV and FMUL, so sometimes the cost of two 11371 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 11372 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 11373 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 11374 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 11375 const SDNodeFlags Flags = N->getFlags(); 11376 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 11377 return SDValue(); 11378 11379 // Skip if current node is a reciprocal. 11380 SDValue N0 = N->getOperand(0); 11381 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11382 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11383 return SDValue(); 11384 11385 // Exit early if the target does not want this transform or if there can't 11386 // possibly be enough uses of the divisor to make the transform worthwhile. 11387 SDValue N1 = N->getOperand(1); 11388 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 11389 if (!MinUses || N1->use_size() < MinUses) 11390 return SDValue(); 11391 11392 // Find all FDIV users of the same divisor. 11393 // Use a set because duplicates may be present in the user list. 11394 SetVector<SDNode *> Users; 11395 for (auto *U : N1->uses()) { 11396 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 11397 // This division is eligible for optimization only if global unsafe math 11398 // is enabled or if this division allows reciprocal formation. 11399 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 11400 Users.insert(U); 11401 } 11402 } 11403 11404 // Now that we have the actual number of divisor uses, make sure it meets 11405 // the minimum threshold specified by the target. 11406 if (Users.size() < MinUses) 11407 return SDValue(); 11408 11409 EVT VT = N->getValueType(0); 11410 SDLoc DL(N); 11411 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 11412 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 11413 11414 // Dividend / Divisor -> Dividend * Reciprocal 11415 for (auto *U : Users) { 11416 SDValue Dividend = U->getOperand(0); 11417 if (Dividend != FPOne) { 11418 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 11419 Reciprocal, Flags); 11420 CombineTo(U, NewNode); 11421 } else if (U != Reciprocal.getNode()) { 11422 // In the absence of fast-math-flags, this user node is always the 11423 // same node as Reciprocal, but with FMF they may be different nodes. 11424 CombineTo(U, Reciprocal); 11425 } 11426 } 11427 return SDValue(N, 0); // N was replaced. 11428 } 11429 11430 SDValue DAGCombiner::visitFDIV(SDNode *N) { 11431 SDValue N0 = N->getOperand(0); 11432 SDValue N1 = N->getOperand(1); 11433 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11434 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11435 EVT VT = N->getValueType(0); 11436 SDLoc DL(N); 11437 const TargetOptions &Options = DAG.getTarget().Options; 11438 SDNodeFlags Flags = N->getFlags(); 11439 11440 // fold vector ops 11441 if (VT.isVector()) 11442 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11443 return FoldedVOp; 11444 11445 // fold (fdiv c1, c2) -> c1/c2 11446 if (N0CFP && N1CFP) 11447 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 11448 11449 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11450 return NewSel; 11451 11452 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 11453 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 11454 if (N1CFP) { 11455 // Compute the reciprocal 1.0 / c2. 11456 const APFloat &N1APF = N1CFP->getValueAPF(); 11457 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 11458 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 11459 // Only do the transform if the reciprocal is a legal fp immediate that 11460 // isn't too nasty (eg NaN, denormal, ...). 11461 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 11462 (!LegalOperations || 11463 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 11464 // backend)... we should handle this gracefully after Legalize. 11465 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 11466 TLI.isOperationLegal(ISD::ConstantFP, VT) || 11467 TLI.isFPImmLegal(Recip, VT))) 11468 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11469 DAG.getConstantFP(Recip, DL, VT), Flags); 11470 } 11471 11472 // If this FDIV is part of a reciprocal square root, it may be folded 11473 // into a target-specific square root estimate instruction. 11474 if (N1.getOpcode() == ISD::FSQRT) { 11475 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 11476 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11477 } 11478 } else if (N1.getOpcode() == ISD::FP_EXTEND && 11479 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11480 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11481 Flags)) { 11482 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 11483 AddToWorklist(RV.getNode()); 11484 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11485 } 11486 } else if (N1.getOpcode() == ISD::FP_ROUND && 11487 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11488 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 11489 Flags)) { 11490 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 11491 AddToWorklist(RV.getNode()); 11492 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11493 } 11494 } else if (N1.getOpcode() == ISD::FMUL) { 11495 // Look through an FMUL. Even though this won't remove the FDIV directly, 11496 // it's still worthwhile to get rid of the FSQRT if possible. 11497 SDValue SqrtOp; 11498 SDValue OtherOp; 11499 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11500 SqrtOp = N1.getOperand(0); 11501 OtherOp = N1.getOperand(1); 11502 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 11503 SqrtOp = N1.getOperand(1); 11504 OtherOp = N1.getOperand(0); 11505 } 11506 if (SqrtOp.getNode()) { 11507 // We found a FSQRT, so try to make this fold: 11508 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 11509 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 11510 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 11511 AddToWorklist(RV.getNode()); 11512 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11513 } 11514 } 11515 } 11516 11517 // Fold into a reciprocal estimate and multiply instead of a real divide. 11518 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 11519 AddToWorklist(RV.getNode()); 11520 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 11521 } 11522 } 11523 11524 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 11525 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 11526 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 11527 // Both can be negated for free, check to see if at least one is cheaper 11528 // negated. 11529 if (LHSNeg == 2 || RHSNeg == 2) 11530 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 11531 GetNegatedExpression(N0, DAG, LegalOperations), 11532 GetNegatedExpression(N1, DAG, LegalOperations), 11533 Flags); 11534 } 11535 } 11536 11537 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 11538 return CombineRepeatedDivisors; 11539 11540 return SDValue(); 11541 } 11542 11543 SDValue DAGCombiner::visitFREM(SDNode *N) { 11544 SDValue N0 = N->getOperand(0); 11545 SDValue N1 = N->getOperand(1); 11546 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11547 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11548 EVT VT = N->getValueType(0); 11549 11550 // fold (frem c1, c2) -> fmod(c1,c2) 11551 if (N0CFP && N1CFP) 11552 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 11553 11554 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11555 return NewSel; 11556 11557 return SDValue(); 11558 } 11559 11560 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 11561 SDNodeFlags Flags = N->getFlags(); 11562 if (!DAG.getTarget().Options.UnsafeFPMath && 11563 !Flags.hasApproximateFuncs()) 11564 return SDValue(); 11565 11566 SDValue N0 = N->getOperand(0); 11567 if (TLI.isFsqrtCheap(N0, DAG)) 11568 return SDValue(); 11569 11570 // FSQRT nodes have flags that propagate to the created nodes. 11571 return buildSqrtEstimate(N0, Flags); 11572 } 11573 11574 /// copysign(x, fp_extend(y)) -> copysign(x, y) 11575 /// copysign(x, fp_round(y)) -> copysign(x, y) 11576 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 11577 SDValue N1 = N->getOperand(1); 11578 if ((N1.getOpcode() == ISD::FP_EXTEND || 11579 N1.getOpcode() == ISD::FP_ROUND)) { 11580 // Do not optimize out type conversion of f128 type yet. 11581 // For some targets like x86_64, configuration is changed to keep one f128 11582 // value in one SSE register, but instruction selection cannot handle 11583 // FCOPYSIGN on SSE registers yet. 11584 EVT N1VT = N1->getValueType(0); 11585 EVT N1Op0VT = N1->getOperand(0).getValueType(); 11586 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 11587 } 11588 return false; 11589 } 11590 11591 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 11592 SDValue N0 = N->getOperand(0); 11593 SDValue N1 = N->getOperand(1); 11594 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 11595 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 11596 EVT VT = N->getValueType(0); 11597 11598 if (N0CFP && N1CFP) // Constant fold 11599 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 11600 11601 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) { 11602 const APFloat &V = N1C->getValueAPF(); 11603 // copysign(x, c1) -> fabs(x) iff ispos(c1) 11604 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 11605 if (!V.isNegative()) { 11606 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 11607 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11608 } else { 11609 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11610 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 11611 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 11612 } 11613 } 11614 11615 // copysign(fabs(x), y) -> copysign(x, y) 11616 // copysign(fneg(x), y) -> copysign(x, y) 11617 // copysign(copysign(x,z), y) -> copysign(x, y) 11618 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 11619 N0.getOpcode() == ISD::FCOPYSIGN) 11620 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 11621 11622 // copysign(x, abs(y)) -> abs(x) 11623 if (N1.getOpcode() == ISD::FABS) 11624 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 11625 11626 // copysign(x, copysign(y,z)) -> copysign(x, z) 11627 if (N1.getOpcode() == ISD::FCOPYSIGN) 11628 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 11629 11630 // copysign(x, fp_extend(y)) -> copysign(x, y) 11631 // copysign(x, fp_round(y)) -> copysign(x, y) 11632 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 11633 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 11634 11635 return SDValue(); 11636 } 11637 11638 SDValue DAGCombiner::visitFPOW(SDNode *N) { 11639 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1)); 11640 if (!ExponentC) 11641 return SDValue(); 11642 11643 // Try to convert x ** (1/3) into cube root. 11644 // TODO: Handle the various flavors of long double. 11645 // TODO: Since we're approximating, we don't need an exact 1/3 exponent. 11646 // Some range near 1/3 should be fine. 11647 EVT VT = N->getValueType(0); 11648 if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) || 11649 (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) { 11650 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0. 11651 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf. 11652 // pow(-val, 1/3) = nan; cbrt(-val) = -num. 11653 // For regular numbers, rounding may cause the results to differ. 11654 // Therefore, we require { nsz ninf nnan afn } for this transform. 11655 // TODO: We could select out the special cases if we don't have nsz/ninf. 11656 SDNodeFlags Flags = N->getFlags(); 11657 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() || 11658 !Flags.hasApproximateFuncs()) 11659 return SDValue(); 11660 11661 // Do not create a cbrt() libcall if the target does not have it, and do not 11662 // turn a pow that has lowering support into a cbrt() libcall. 11663 if (!DAG.getLibInfo().has(LibFunc_cbrt) || 11664 (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) && 11665 DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT))) 11666 return SDValue(); 11667 11668 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0), Flags); 11669 } 11670 11671 // Try to convert x ** (1/4) into square roots. 11672 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case. 11673 // TODO: This could be extended (using a target hook) to handle smaller 11674 // power-of-2 fractional exponents. 11675 if (ExponentC->getValueAPF().isExactlyValue(0.25)) { 11676 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0. 11677 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN. 11678 // For regular numbers, rounding may cause the results to differ. 11679 // Therefore, we require { nsz ninf afn } for this transform. 11680 // TODO: We could select out the special cases if we don't have nsz/ninf. 11681 SDNodeFlags Flags = N->getFlags(); 11682 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || 11683 !Flags.hasApproximateFuncs()) 11684 return SDValue(); 11685 11686 // Don't double the number of libcalls. We are trying to inline fast code. 11687 if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT)) 11688 return SDValue(); 11689 11690 // Assume that libcalls are the smallest code. 11691 // TODO: This restriction should probably be lifted for vectors. 11692 if (DAG.getMachineFunction().getFunction().optForSize()) 11693 return SDValue(); 11694 11695 // pow(X, 0.25) --> sqrt(sqrt(X)) 11696 SDLoc DL(N); 11697 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0), Flags); 11698 return DAG.getNode(ISD::FSQRT, DL, VT, Sqrt, Flags); 11699 } 11700 11701 return SDValue(); 11702 } 11703 11704 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 11705 const TargetLowering &TLI) { 11706 // This optimization is guarded by a function attribute because it may produce 11707 // unexpected results. Ie, programs may be relying on the platform-specific 11708 // undefined behavior when the float-to-int conversion overflows. 11709 const Function &F = DAG.getMachineFunction().getFunction(); 11710 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 11711 if (StrictOverflow.getValueAsString().equals("false")) 11712 return SDValue(); 11713 11714 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 11715 // replacing casts with a libcall. We also must be allowed to ignore -0.0 11716 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 11717 // conversions would return +0.0. 11718 // FIXME: We should be able to use node-level FMF here. 11719 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 11720 EVT VT = N->getValueType(0); 11721 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 11722 !DAG.getTarget().Options.NoSignedZerosFPMath) 11723 return SDValue(); 11724 11725 // fptosi/fptoui round towards zero, so converting from FP to integer and 11726 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 11727 SDValue N0 = N->getOperand(0); 11728 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 11729 N0.getOperand(0).getValueType() == VT) 11730 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11731 11732 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 11733 N0.getOperand(0).getValueType() == VT) 11734 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 11735 11736 return SDValue(); 11737 } 11738 11739 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 11740 SDValue N0 = N->getOperand(0); 11741 EVT VT = N->getValueType(0); 11742 EVT OpVT = N0.getValueType(); 11743 11744 // fold (sint_to_fp c1) -> c1fp 11745 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11746 // ...but only if the target supports immediate floating-point values 11747 (!LegalOperations || 11748 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11749 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11750 11751 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 11752 // but UINT_TO_FP is legal on this target, try to convert. 11753 if (!hasOperation(ISD::SINT_TO_FP, OpVT) && 11754 hasOperation(ISD::UINT_TO_FP, OpVT)) { 11755 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 11756 if (DAG.SignBitIsZero(N0)) 11757 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11758 } 11759 11760 // The next optimizations are desirable only if SELECT_CC can be lowered. 11761 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11762 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11763 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 11764 !VT.isVector() && 11765 (!LegalOperations || 11766 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11767 SDLoc DL(N); 11768 SDValue Ops[] = 11769 { N0.getOperand(0), N0.getOperand(1), 11770 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11771 N0.getOperand(2) }; 11772 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11773 } 11774 11775 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 11776 // (select_cc x, y, 1.0, 0.0,, cc) 11777 if (N0.getOpcode() == ISD::ZERO_EXTEND && 11778 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 11779 (!LegalOperations || 11780 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11781 SDLoc DL(N); 11782 SDValue Ops[] = 11783 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 11784 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11785 N0.getOperand(0).getOperand(2) }; 11786 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11787 } 11788 } 11789 11790 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11791 return FTrunc; 11792 11793 return SDValue(); 11794 } 11795 11796 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 11797 SDValue N0 = N->getOperand(0); 11798 EVT VT = N->getValueType(0); 11799 EVT OpVT = N0.getValueType(); 11800 11801 // fold (uint_to_fp c1) -> c1fp 11802 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 11803 // ...but only if the target supports immediate floating-point values 11804 (!LegalOperations || 11805 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 11806 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 11807 11808 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 11809 // but SINT_TO_FP is legal on this target, try to convert. 11810 if (!hasOperation(ISD::UINT_TO_FP, OpVT) && 11811 hasOperation(ISD::SINT_TO_FP, OpVT)) { 11812 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 11813 if (DAG.SignBitIsZero(N0)) 11814 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 11815 } 11816 11817 // The next optimizations are desirable only if SELECT_CC can be lowered. 11818 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 11819 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 11820 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 11821 (!LegalOperations || 11822 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 11823 SDLoc DL(N); 11824 SDValue Ops[] = 11825 { N0.getOperand(0), N0.getOperand(1), 11826 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 11827 N0.getOperand(2) }; 11828 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 11829 } 11830 } 11831 11832 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 11833 return FTrunc; 11834 11835 return SDValue(); 11836 } 11837 11838 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 11839 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 11840 SDValue N0 = N->getOperand(0); 11841 EVT VT = N->getValueType(0); 11842 11843 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 11844 return SDValue(); 11845 11846 SDValue Src = N0.getOperand(0); 11847 EVT SrcVT = Src.getValueType(); 11848 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 11849 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 11850 11851 // We can safely assume the conversion won't overflow the output range, 11852 // because (for example) (uint8_t)18293.f is undefined behavior. 11853 11854 // Since we can assume the conversion won't overflow, our decision as to 11855 // whether the input will fit in the float should depend on the minimum 11856 // of the input range and output range. 11857 11858 // This means this is also safe for a signed input and unsigned output, since 11859 // a negative input would lead to undefined behavior. 11860 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 11861 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 11862 unsigned ActualSize = std::min(InputSize, OutputSize); 11863 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 11864 11865 // We can only fold away the float conversion if the input range can be 11866 // represented exactly in the float range. 11867 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 11868 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 11869 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 11870 : ISD::ZERO_EXTEND; 11871 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 11872 } 11873 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 11874 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 11875 return DAG.getBitcast(VT, Src); 11876 } 11877 return SDValue(); 11878 } 11879 11880 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 11881 SDValue N0 = N->getOperand(0); 11882 EVT VT = N->getValueType(0); 11883 11884 // fold (fp_to_sint c1fp) -> c1 11885 if (isConstantFPBuildVectorOrConstantFP(N0)) 11886 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 11887 11888 return FoldIntToFPToInt(N, DAG); 11889 } 11890 11891 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 11892 SDValue N0 = N->getOperand(0); 11893 EVT VT = N->getValueType(0); 11894 11895 // fold (fp_to_uint c1fp) -> c1 11896 if (isConstantFPBuildVectorOrConstantFP(N0)) 11897 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 11898 11899 return FoldIntToFPToInt(N, DAG); 11900 } 11901 11902 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 11903 SDValue N0 = N->getOperand(0); 11904 SDValue N1 = N->getOperand(1); 11905 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11906 EVT VT = N->getValueType(0); 11907 11908 // fold (fp_round c1fp) -> c1fp 11909 if (N0CFP) 11910 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 11911 11912 // fold (fp_round (fp_extend x)) -> x 11913 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 11914 return N0.getOperand(0); 11915 11916 // fold (fp_round (fp_round x)) -> (fp_round x) 11917 if (N0.getOpcode() == ISD::FP_ROUND) { 11918 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 11919 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 11920 11921 // Skip this folding if it results in an fp_round from f80 to f16. 11922 // 11923 // f80 to f16 always generates an expensive (and as yet, unimplemented) 11924 // libcall to __truncxfhf2 instead of selecting native f16 conversion 11925 // instructions from f32 or f64. Moreover, the first (value-preserving) 11926 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 11927 // x86. 11928 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 11929 return SDValue(); 11930 11931 // If the first fp_round isn't a value preserving truncation, it might 11932 // introduce a tie in the second fp_round, that wouldn't occur in the 11933 // single-step fp_round we want to fold to. 11934 // In other words, double rounding isn't the same as rounding. 11935 // Also, this is a value preserving truncation iff both fp_round's are. 11936 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 11937 SDLoc DL(N); 11938 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 11939 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 11940 } 11941 } 11942 11943 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 11944 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 11945 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 11946 N0.getOperand(0), N1); 11947 AddToWorklist(Tmp.getNode()); 11948 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 11949 Tmp, N0.getOperand(1)); 11950 } 11951 11952 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11953 return NewVSel; 11954 11955 return SDValue(); 11956 } 11957 11958 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 11959 SDValue N0 = N->getOperand(0); 11960 EVT VT = N->getValueType(0); 11961 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 11962 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11963 11964 // fold (fp_round_inreg c1fp) -> c1fp 11965 if (N0CFP && isTypeLegal(EVT)) { 11966 SDLoc DL(N); 11967 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 11968 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 11969 } 11970 11971 return SDValue(); 11972 } 11973 11974 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 11975 SDValue N0 = N->getOperand(0); 11976 EVT VT = N->getValueType(0); 11977 11978 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 11979 if (N->hasOneUse() && 11980 N->use_begin()->getOpcode() == ISD::FP_ROUND) 11981 return SDValue(); 11982 11983 // fold (fp_extend c1fp) -> c1fp 11984 if (isConstantFPBuildVectorOrConstantFP(N0)) 11985 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 11986 11987 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 11988 if (N0.getOpcode() == ISD::FP16_TO_FP && 11989 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 11990 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 11991 11992 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 11993 // value of X. 11994 if (N0.getOpcode() == ISD::FP_ROUND 11995 && N0.getConstantOperandVal(1) == 1) { 11996 SDValue In = N0.getOperand(0); 11997 if (In.getValueType() == VT) return In; 11998 if (VT.bitsLT(In.getValueType())) 11999 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 12000 In, N0.getOperand(1)); 12001 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 12002 } 12003 12004 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 12005 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12006 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 12007 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12008 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 12009 LN0->getChain(), 12010 LN0->getBasePtr(), N0.getValueType(), 12011 LN0->getMemOperand()); 12012 CombineTo(N, ExtLoad); 12013 CombineTo(N0.getNode(), 12014 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 12015 N0.getValueType(), ExtLoad, 12016 DAG.getIntPtrConstant(1, SDLoc(N0))), 12017 ExtLoad.getValue(1)); 12018 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12019 } 12020 12021 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 12022 return NewVSel; 12023 12024 return SDValue(); 12025 } 12026 12027 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 12028 SDValue N0 = N->getOperand(0); 12029 EVT VT = N->getValueType(0); 12030 12031 // fold (fceil c1) -> fceil(c1) 12032 if (isConstantFPBuildVectorOrConstantFP(N0)) 12033 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 12034 12035 return SDValue(); 12036 } 12037 12038 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 12039 SDValue N0 = N->getOperand(0); 12040 EVT VT = N->getValueType(0); 12041 12042 // fold (ftrunc c1) -> ftrunc(c1) 12043 if (isConstantFPBuildVectorOrConstantFP(N0)) 12044 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 12045 12046 // fold ftrunc (known rounded int x) -> x 12047 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 12048 // likely to be generated to extract integer from a rounded floating value. 12049 switch (N0.getOpcode()) { 12050 default: break; 12051 case ISD::FRINT: 12052 case ISD::FTRUNC: 12053 case ISD::FNEARBYINT: 12054 case ISD::FFLOOR: 12055 case ISD::FCEIL: 12056 return N0; 12057 } 12058 12059 return SDValue(); 12060 } 12061 12062 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 12063 SDValue N0 = N->getOperand(0); 12064 EVT VT = N->getValueType(0); 12065 12066 // fold (ffloor c1) -> ffloor(c1) 12067 if (isConstantFPBuildVectorOrConstantFP(N0)) 12068 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 12069 12070 return SDValue(); 12071 } 12072 12073 // FIXME: FNEG and FABS have a lot in common; refactor. 12074 SDValue DAGCombiner::visitFNEG(SDNode *N) { 12075 SDValue N0 = N->getOperand(0); 12076 EVT VT = N->getValueType(0); 12077 12078 // Constant fold FNEG. 12079 if (isConstantFPBuildVectorOrConstantFP(N0)) 12080 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 12081 12082 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 12083 &DAG.getTarget().Options)) 12084 return GetNegatedExpression(N0, DAG, LegalOperations); 12085 12086 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 12087 // constant pool values. 12088 if (!TLI.isFNegFree(VT) && 12089 N0.getOpcode() == ISD::BITCAST && 12090 N0.getNode()->hasOneUse()) { 12091 SDValue Int = N0.getOperand(0); 12092 EVT IntVT = Int.getValueType(); 12093 if (IntVT.isInteger() && !IntVT.isVector()) { 12094 APInt SignMask; 12095 if (N0.getValueType().isVector()) { 12096 // For a vector, get a mask such as 0x80... per scalar element 12097 // and splat it. 12098 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 12099 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 12100 } else { 12101 // For a scalar, just generate 0x80... 12102 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 12103 } 12104 SDLoc DL0(N0); 12105 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 12106 DAG.getConstant(SignMask, DL0, IntVT)); 12107 AddToWorklist(Int.getNode()); 12108 return DAG.getBitcast(VT, Int); 12109 } 12110 } 12111 12112 // (fneg (fmul c, x)) -> (fmul -c, x) 12113 if (N0.getOpcode() == ISD::FMUL && 12114 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 12115 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 12116 if (CFP1) { 12117 APFloat CVal = CFP1->getValueAPF(); 12118 CVal.changeSign(); 12119 if (Level >= AfterLegalizeDAG && 12120 (TLI.isFPImmLegal(CVal, VT) || 12121 TLI.isOperationLegal(ISD::ConstantFP, VT))) 12122 return DAG.getNode( 12123 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 12124 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 12125 N0->getFlags()); 12126 } 12127 } 12128 12129 return SDValue(); 12130 } 12131 12132 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, 12133 APFloat (*Op)(const APFloat &, const APFloat &)) { 12134 SDValue N0 = N->getOperand(0); 12135 SDValue N1 = N->getOperand(1); 12136 EVT VT = N->getValueType(0); 12137 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 12138 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 12139 12140 if (N0CFP && N1CFP) { 12141 const APFloat &C0 = N0CFP->getValueAPF(); 12142 const APFloat &C1 = N1CFP->getValueAPF(); 12143 return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT); 12144 } 12145 12146 // Canonicalize to constant on RHS. 12147 if (isConstantFPBuildVectorOrConstantFP(N0) && 12148 !isConstantFPBuildVectorOrConstantFP(N1)) 12149 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 12150 12151 return SDValue(); 12152 } 12153 12154 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 12155 return visitFMinMax(DAG, N, minnum); 12156 } 12157 12158 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 12159 return visitFMinMax(DAG, N, maxnum); 12160 } 12161 12162 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) { 12163 return visitFMinMax(DAG, N, minimum); 12164 } 12165 12166 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) { 12167 return visitFMinMax(DAG, N, maximum); 12168 } 12169 12170 SDValue DAGCombiner::visitFABS(SDNode *N) { 12171 SDValue N0 = N->getOperand(0); 12172 EVT VT = N->getValueType(0); 12173 12174 // fold (fabs c1) -> fabs(c1) 12175 if (isConstantFPBuildVectorOrConstantFP(N0)) 12176 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 12177 12178 // fold (fabs (fabs x)) -> (fabs x) 12179 if (N0.getOpcode() == ISD::FABS) 12180 return N->getOperand(0); 12181 12182 // fold (fabs (fneg x)) -> (fabs x) 12183 // fold (fabs (fcopysign x, y)) -> (fabs x) 12184 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 12185 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 12186 12187 // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads. 12188 if (!TLI.isFAbsFree(VT) && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) { 12189 SDValue Int = N0.getOperand(0); 12190 EVT IntVT = Int.getValueType(); 12191 if (IntVT.isInteger() && !IntVT.isVector()) { 12192 APInt SignMask; 12193 if (N0.getValueType().isVector()) { 12194 // For a vector, get a mask such as 0x7f... per scalar element 12195 // and splat it. 12196 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 12197 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 12198 } else { 12199 // For a scalar, just generate 0x7f... 12200 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 12201 } 12202 SDLoc DL(N0); 12203 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 12204 DAG.getConstant(SignMask, DL, IntVT)); 12205 AddToWorklist(Int.getNode()); 12206 return DAG.getBitcast(N->getValueType(0), Int); 12207 } 12208 } 12209 12210 return SDValue(); 12211 } 12212 12213 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 12214 SDValue Chain = N->getOperand(0); 12215 SDValue N1 = N->getOperand(1); 12216 SDValue N2 = N->getOperand(2); 12217 12218 // If N is a constant we could fold this into a fallthrough or unconditional 12219 // branch. However that doesn't happen very often in normal code, because 12220 // Instcombine/SimplifyCFG should have handled the available opportunities. 12221 // If we did this folding here, it would be necessary to update the 12222 // MachineBasicBlock CFG, which is awkward. 12223 12224 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 12225 // on the target. 12226 if (N1.getOpcode() == ISD::SETCC && 12227 TLI.isOperationLegalOrCustom(ISD::BR_CC, 12228 N1.getOperand(0).getValueType())) { 12229 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12230 Chain, N1.getOperand(2), 12231 N1.getOperand(0), N1.getOperand(1), N2); 12232 } 12233 12234 if (N1.hasOneUse()) { 12235 if (SDValue NewN1 = rebuildSetCC(N1)) 12236 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2); 12237 } 12238 12239 return SDValue(); 12240 } 12241 12242 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 12243 if (N.getOpcode() == ISD::SRL || 12244 (N.getOpcode() == ISD::TRUNCATE && 12245 (N.getOperand(0).hasOneUse() && 12246 N.getOperand(0).getOpcode() == ISD::SRL))) { 12247 // Look pass the truncate. 12248 if (N.getOpcode() == ISD::TRUNCATE) 12249 N = N.getOperand(0); 12250 12251 // Match this pattern so that we can generate simpler code: 12252 // 12253 // %a = ... 12254 // %b = and i32 %a, 2 12255 // %c = srl i32 %b, 1 12256 // brcond i32 %c ... 12257 // 12258 // into 12259 // 12260 // %a = ... 12261 // %b = and i32 %a, 2 12262 // %c = setcc eq %b, 0 12263 // brcond %c ... 12264 // 12265 // This applies only when the AND constant value has one bit set and the 12266 // SRL constant is equal to the log2 of the AND constant. The back-end is 12267 // smart enough to convert the result into a TEST/JMP sequence. 12268 SDValue Op0 = N.getOperand(0); 12269 SDValue Op1 = N.getOperand(1); 12270 12271 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 12272 SDValue AndOp1 = Op0.getOperand(1); 12273 12274 if (AndOp1.getOpcode() == ISD::Constant) { 12275 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 12276 12277 if (AndConst.isPowerOf2() && 12278 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 12279 SDLoc DL(N); 12280 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 12281 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 12282 ISD::SETNE); 12283 } 12284 } 12285 } 12286 } 12287 12288 // Transform br(xor(x, y)) -> br(x != y) 12289 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 12290 if (N.getOpcode() == ISD::XOR) { 12291 // Because we may call this on a speculatively constructed 12292 // SimplifiedSetCC Node, we need to simplify this node first. 12293 // Ideally this should be folded into SimplifySetCC and not 12294 // here. For now, grab a handle to N so we don't lose it from 12295 // replacements interal to the visit. 12296 HandleSDNode XORHandle(N); 12297 while (N.getOpcode() == ISD::XOR) { 12298 SDValue Tmp = visitXOR(N.getNode()); 12299 // No simplification done. 12300 if (!Tmp.getNode()) 12301 break; 12302 // Returning N is form in-visit replacement that may invalidated 12303 // N. Grab value from Handle. 12304 if (Tmp.getNode() == N.getNode()) 12305 N = XORHandle.getValue(); 12306 else // Node simplified. Try simplifying again. 12307 N = Tmp; 12308 } 12309 12310 if (N.getOpcode() != ISD::XOR) 12311 return N; 12312 12313 SDNode *TheXor = N.getNode(); 12314 12315 SDValue Op0 = TheXor->getOperand(0); 12316 SDValue Op1 = TheXor->getOperand(1); 12317 12318 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 12319 bool Equal = false; 12320 if (isOneConstant(Op0) && Op0.hasOneUse() && 12321 Op0.getOpcode() == ISD::XOR) { 12322 TheXor = Op0.getNode(); 12323 Equal = true; 12324 } 12325 12326 EVT SetCCVT = N.getValueType(); 12327 if (LegalTypes) 12328 SetCCVT = getSetCCResultType(SetCCVT); 12329 // Replace the uses of XOR with SETCC 12330 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1, 12331 Equal ? ISD::SETEQ : ISD::SETNE); 12332 } 12333 } 12334 12335 return SDValue(); 12336 } 12337 12338 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 12339 // 12340 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 12341 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 12342 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 12343 12344 // If N is a constant we could fold this into a fallthrough or unconditional 12345 // branch. However that doesn't happen very often in normal code, because 12346 // Instcombine/SimplifyCFG should have handled the available opportunities. 12347 // If we did this folding here, it would be necessary to update the 12348 // MachineBasicBlock CFG, which is awkward. 12349 12350 // Use SimplifySetCC to simplify SETCC's. 12351 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 12352 CondLHS, CondRHS, CC->get(), SDLoc(N), 12353 false); 12354 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 12355 12356 // fold to a simpler setcc 12357 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 12358 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12359 N->getOperand(0), Simp.getOperand(2), 12360 Simp.getOperand(0), Simp.getOperand(1), 12361 N->getOperand(4)); 12362 12363 return SDValue(); 12364 } 12365 12366 /// Return true if 'Use' is a load or a store that uses N as its base pointer 12367 /// and that N may be folded in the load / store addressing mode. 12368 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 12369 SelectionDAG &DAG, 12370 const TargetLowering &TLI) { 12371 EVT VT; 12372 unsigned AS; 12373 12374 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 12375 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 12376 return false; 12377 VT = LD->getMemoryVT(); 12378 AS = LD->getAddressSpace(); 12379 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 12380 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 12381 return false; 12382 VT = ST->getMemoryVT(); 12383 AS = ST->getAddressSpace(); 12384 } else 12385 return false; 12386 12387 TargetLowering::AddrMode AM; 12388 if (N->getOpcode() == ISD::ADD) { 12389 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12390 if (Offset) 12391 // [reg +/- imm] 12392 AM.BaseOffs = Offset->getSExtValue(); 12393 else 12394 // [reg +/- reg] 12395 AM.Scale = 1; 12396 } else if (N->getOpcode() == ISD::SUB) { 12397 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12398 if (Offset) 12399 // [reg +/- imm] 12400 AM.BaseOffs = -Offset->getSExtValue(); 12401 else 12402 // [reg +/- reg] 12403 AM.Scale = 1; 12404 } else 12405 return false; 12406 12407 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 12408 VT.getTypeForEVT(*DAG.getContext()), AS); 12409 } 12410 12411 /// Try turning a load/store into a pre-indexed load/store when the base 12412 /// pointer is an add or subtract and it has other uses besides the load/store. 12413 /// After the transformation, the new indexed load/store has effectively folded 12414 /// the add/subtract in and all of its other uses are redirected to the 12415 /// new load/store. 12416 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 12417 if (Level < AfterLegalizeDAG) 12418 return false; 12419 12420 bool isLoad = true; 12421 SDValue Ptr; 12422 EVT VT; 12423 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12424 if (LD->isIndexed()) 12425 return false; 12426 VT = LD->getMemoryVT(); 12427 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 12428 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 12429 return false; 12430 Ptr = LD->getBasePtr(); 12431 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12432 if (ST->isIndexed()) 12433 return false; 12434 VT = ST->getMemoryVT(); 12435 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 12436 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 12437 return false; 12438 Ptr = ST->getBasePtr(); 12439 isLoad = false; 12440 } else { 12441 return false; 12442 } 12443 12444 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 12445 // out. There is no reason to make this a preinc/predec. 12446 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 12447 Ptr.getNode()->hasOneUse()) 12448 return false; 12449 12450 // Ask the target to do addressing mode selection. 12451 SDValue BasePtr; 12452 SDValue Offset; 12453 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12454 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 12455 return false; 12456 12457 // Backends without true r+i pre-indexed forms may need to pass a 12458 // constant base with a variable offset so that constant coercion 12459 // will work with the patterns in canonical form. 12460 bool Swapped = false; 12461 if (isa<ConstantSDNode>(BasePtr)) { 12462 std::swap(BasePtr, Offset); 12463 Swapped = true; 12464 } 12465 12466 // Don't create a indexed load / store with zero offset. 12467 if (isNullConstant(Offset)) 12468 return false; 12469 12470 // Try turning it into a pre-indexed load / store except when: 12471 // 1) The new base ptr is a frame index. 12472 // 2) If N is a store and the new base ptr is either the same as or is a 12473 // predecessor of the value being stored. 12474 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 12475 // that would create a cycle. 12476 // 4) All uses are load / store ops that use it as old base ptr. 12477 12478 // Check #1. Preinc'ing a frame index would require copying the stack pointer 12479 // (plus the implicit offset) to a register to preinc anyway. 12480 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12481 return false; 12482 12483 // Check #2. 12484 if (!isLoad) { 12485 SDValue Val = cast<StoreSDNode>(N)->getValue(); 12486 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 12487 return false; 12488 } 12489 12490 // Caches for hasPredecessorHelper. 12491 SmallPtrSet<const SDNode *, 32> Visited; 12492 SmallVector<const SDNode *, 16> Worklist; 12493 Worklist.push_back(N); 12494 12495 // If the offset is a constant, there may be other adds of constants that 12496 // can be folded with this one. We should do this to avoid having to keep 12497 // a copy of the original base pointer. 12498 SmallVector<SDNode *, 16> OtherUses; 12499 if (isa<ConstantSDNode>(Offset)) 12500 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 12501 UE = BasePtr.getNode()->use_end(); 12502 UI != UE; ++UI) { 12503 SDUse &Use = UI.getUse(); 12504 // Skip the use that is Ptr and uses of other results from BasePtr's 12505 // node (important for nodes that return multiple results). 12506 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 12507 continue; 12508 12509 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 12510 continue; 12511 12512 if (Use.getUser()->getOpcode() != ISD::ADD && 12513 Use.getUser()->getOpcode() != ISD::SUB) { 12514 OtherUses.clear(); 12515 break; 12516 } 12517 12518 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 12519 if (!isa<ConstantSDNode>(Op1)) { 12520 OtherUses.clear(); 12521 break; 12522 } 12523 12524 // FIXME: In some cases, we can be smarter about this. 12525 if (Op1.getValueType() != Offset.getValueType()) { 12526 OtherUses.clear(); 12527 break; 12528 } 12529 12530 OtherUses.push_back(Use.getUser()); 12531 } 12532 12533 if (Swapped) 12534 std::swap(BasePtr, Offset); 12535 12536 // Now check for #3 and #4. 12537 bool RealUse = false; 12538 12539 for (SDNode *Use : Ptr.getNode()->uses()) { 12540 if (Use == N) 12541 continue; 12542 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 12543 return false; 12544 12545 // If Ptr may be folded in addressing mode of other use, then it's 12546 // not profitable to do this transformation. 12547 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 12548 RealUse = true; 12549 } 12550 12551 if (!RealUse) 12552 return false; 12553 12554 SDValue Result; 12555 if (isLoad) 12556 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12557 BasePtr, Offset, AM); 12558 else 12559 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12560 BasePtr, Offset, AM); 12561 ++PreIndexedNodes; 12562 ++NodesCombined; 12563 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 12564 Result.getNode()->dump(&DAG); dbgs() << '\n'); 12565 WorklistRemover DeadNodes(*this); 12566 if (isLoad) { 12567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12568 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12569 } else { 12570 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12571 } 12572 12573 // Finally, since the node is now dead, remove it from the graph. 12574 deleteAndRecombine(N); 12575 12576 if (Swapped) 12577 std::swap(BasePtr, Offset); 12578 12579 // Replace other uses of BasePtr that can be updated to use Ptr 12580 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 12581 unsigned OffsetIdx = 1; 12582 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 12583 OffsetIdx = 0; 12584 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 12585 BasePtr.getNode() && "Expected BasePtr operand"); 12586 12587 // We need to replace ptr0 in the following expression: 12588 // x0 * offset0 + y0 * ptr0 = t0 12589 // knowing that 12590 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 12591 // 12592 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 12593 // indexed load/store and the expression that needs to be re-written. 12594 // 12595 // Therefore, we have: 12596 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 12597 12598 ConstantSDNode *CN = 12599 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 12600 int X0, X1, Y0, Y1; 12601 const APInt &Offset0 = CN->getAPIntValue(); 12602 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 12603 12604 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 12605 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 12606 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 12607 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 12608 12609 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 12610 12611 APInt CNV = Offset0; 12612 if (X0 < 0) CNV = -CNV; 12613 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 12614 else CNV = CNV - Offset1; 12615 12616 SDLoc DL(OtherUses[i]); 12617 12618 // We can now generate the new expression. 12619 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 12620 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 12621 12622 SDValue NewUse = DAG.getNode(Opcode, 12623 DL, 12624 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 12625 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 12626 deleteAndRecombine(OtherUses[i]); 12627 } 12628 12629 // Replace the uses of Ptr with uses of the updated base value. 12630 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 12631 deleteAndRecombine(Ptr.getNode()); 12632 AddToWorklist(Result.getNode()); 12633 12634 return true; 12635 } 12636 12637 /// Try to combine a load/store with a add/sub of the base pointer node into a 12638 /// post-indexed load/store. The transformation folded the add/subtract into the 12639 /// new indexed load/store effectively and all of its uses are redirected to the 12640 /// new load/store. 12641 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 12642 if (Level < AfterLegalizeDAG) 12643 return false; 12644 12645 bool isLoad = true; 12646 SDValue Ptr; 12647 EVT VT; 12648 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12649 if (LD->isIndexed()) 12650 return false; 12651 VT = LD->getMemoryVT(); 12652 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 12653 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 12654 return false; 12655 Ptr = LD->getBasePtr(); 12656 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12657 if (ST->isIndexed()) 12658 return false; 12659 VT = ST->getMemoryVT(); 12660 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 12661 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 12662 return false; 12663 Ptr = ST->getBasePtr(); 12664 isLoad = false; 12665 } else { 12666 return false; 12667 } 12668 12669 if (Ptr.getNode()->hasOneUse()) 12670 return false; 12671 12672 for (SDNode *Op : Ptr.getNode()->uses()) { 12673 if (Op == N || 12674 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 12675 continue; 12676 12677 SDValue BasePtr; 12678 SDValue Offset; 12679 ISD::MemIndexedMode AM = ISD::UNINDEXED; 12680 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 12681 // Don't create a indexed load / store with zero offset. 12682 if (isNullConstant(Offset)) 12683 continue; 12684 12685 // Try turning it into a post-indexed load / store except when 12686 // 1) All uses are load / store ops that use it as base ptr (and 12687 // it may be folded as addressing mmode). 12688 // 2) Op must be independent of N, i.e. Op is neither a predecessor 12689 // nor a successor of N. Otherwise, if Op is folded that would 12690 // create a cycle. 12691 12692 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 12693 continue; 12694 12695 // Check for #1. 12696 bool TryNext = false; 12697 for (SDNode *Use : BasePtr.getNode()->uses()) { 12698 if (Use == Ptr.getNode()) 12699 continue; 12700 12701 // If all the uses are load / store addresses, then don't do the 12702 // transformation. 12703 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 12704 bool RealUse = false; 12705 for (SDNode *UseUse : Use->uses()) { 12706 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 12707 RealUse = true; 12708 } 12709 12710 if (!RealUse) { 12711 TryNext = true; 12712 break; 12713 } 12714 } 12715 } 12716 12717 if (TryNext) 12718 continue; 12719 12720 // Check for #2. 12721 SmallPtrSet<const SDNode *, 32> Visited; 12722 SmallVector<const SDNode *, 8> Worklist; 12723 // Ptr is predecessor to both N and Op. 12724 Visited.insert(Ptr.getNode()); 12725 Worklist.push_back(N); 12726 Worklist.push_back(Op); 12727 if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) && 12728 !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) { 12729 SDValue Result = isLoad 12730 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 12731 BasePtr, Offset, AM) 12732 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 12733 BasePtr, Offset, AM); 12734 ++PostIndexedNodes; 12735 ++NodesCombined; 12736 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 12737 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 12738 dbgs() << '\n'); 12739 WorklistRemover DeadNodes(*this); 12740 if (isLoad) { 12741 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 12742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 12743 } else { 12744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 12745 } 12746 12747 // Finally, since the node is now dead, remove it from the graph. 12748 deleteAndRecombine(N); 12749 12750 // Replace the uses of Use with uses of the updated base value. 12751 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 12752 Result.getValue(isLoad ? 1 : 0)); 12753 deleteAndRecombine(Op); 12754 return true; 12755 } 12756 } 12757 } 12758 12759 return false; 12760 } 12761 12762 /// Return the base-pointer arithmetic from an indexed \p LD. 12763 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 12764 ISD::MemIndexedMode AM = LD->getAddressingMode(); 12765 assert(AM != ISD::UNINDEXED); 12766 SDValue BP = LD->getOperand(1); 12767 SDValue Inc = LD->getOperand(2); 12768 12769 // Some backends use TargetConstants for load offsets, but don't expect 12770 // TargetConstants in general ADD nodes. We can convert these constants into 12771 // regular Constants (if the constant is not opaque). 12772 assert((Inc.getOpcode() != ISD::TargetConstant || 12773 !cast<ConstantSDNode>(Inc)->isOpaque()) && 12774 "Cannot split out indexing using opaque target constants"); 12775 if (Inc.getOpcode() == ISD::TargetConstant) { 12776 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 12777 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 12778 ConstInc->getValueType(0)); 12779 } 12780 12781 unsigned Opc = 12782 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 12783 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 12784 } 12785 12786 static inline int numVectorEltsOrZero(EVT T) { 12787 return T.isVector() ? T.getVectorNumElements() : 0; 12788 } 12789 12790 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) { 12791 Val = ST->getValue(); 12792 EVT STType = Val.getValueType(); 12793 EVT STMemType = ST->getMemoryVT(); 12794 if (STType == STMemType) 12795 return true; 12796 if (isTypeLegal(STMemType)) 12797 return false; // fail. 12798 if (STType.isFloatingPoint() && STMemType.isFloatingPoint() && 12799 TLI.isOperationLegal(ISD::FTRUNC, STMemType)) { 12800 Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val); 12801 return true; 12802 } 12803 if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) && 12804 STType.isInteger() && STMemType.isInteger()) { 12805 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val); 12806 return true; 12807 } 12808 if (STType.getSizeInBits() == STMemType.getSizeInBits()) { 12809 Val = DAG.getBitcast(STMemType, Val); 12810 return true; 12811 } 12812 return false; // fail. 12813 } 12814 12815 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) { 12816 EVT LDMemType = LD->getMemoryVT(); 12817 EVT LDType = LD->getValueType(0); 12818 assert(Val.getValueType() == LDMemType && 12819 "Attempting to extend value of non-matching type"); 12820 if (LDType == LDMemType) 12821 return true; 12822 if (LDMemType.isInteger() && LDType.isInteger()) { 12823 switch (LD->getExtensionType()) { 12824 case ISD::NON_EXTLOAD: 12825 Val = DAG.getBitcast(LDType, Val); 12826 return true; 12827 case ISD::EXTLOAD: 12828 Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val); 12829 return true; 12830 case ISD::SEXTLOAD: 12831 Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val); 12832 return true; 12833 case ISD::ZEXTLOAD: 12834 Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val); 12835 return true; 12836 } 12837 } 12838 return false; 12839 } 12840 12841 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) { 12842 if (OptLevel == CodeGenOpt::None || LD->isVolatile()) 12843 return SDValue(); 12844 SDValue Chain = LD->getOperand(0); 12845 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode()); 12846 if (!ST || ST->isVolatile()) 12847 return SDValue(); 12848 12849 EVT LDType = LD->getValueType(0); 12850 EVT LDMemType = LD->getMemoryVT(); 12851 EVT STMemType = ST->getMemoryVT(); 12852 EVT STType = ST->getValue().getValueType(); 12853 12854 BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG); 12855 BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG); 12856 int64_t Offset; 12857 12858 bool STCoversLD = 12859 BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset) && (Offset >= 0) && 12860 (Offset * 8 <= LDMemType.getSizeInBits()) && 12861 (Offset * 8 + LDMemType.getSizeInBits() <= STMemType.getSizeInBits()); 12862 12863 if (!STCoversLD) 12864 return SDValue(); 12865 12866 // Normalize for Endianness. 12867 if (DAG.getDataLayout().isBigEndian()) 12868 Offset = 12869 (STMemType.getSizeInBits() - LDMemType.getSizeInBits()) / 8 - Offset; 12870 12871 // Memory as copy space (potentially masked). 12872 if (Offset == 0 && LDType == STType && STMemType == LDMemType) { 12873 // Simple case: Direct non-truncating forwarding 12874 if (LDType.getSizeInBits() == LDMemType.getSizeInBits()) 12875 return CombineTo(LD, ST->getValue(), Chain); 12876 // Can we model the truncate and extension with an and mask? 12877 if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() && 12878 !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) { 12879 // Mask to size of LDMemType 12880 auto Mask = 12881 DAG.getConstant(APInt::getLowBitsSet(STType.getSizeInBits(), 12882 STMemType.getSizeInBits()), 12883 SDLoc(ST), STType); 12884 auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask); 12885 return CombineTo(LD, Val, Chain); 12886 } 12887 } 12888 12889 // TODO: Deal with nonzero offset. 12890 if (LD->getBasePtr().isUndef() || Offset != 0) 12891 return SDValue(); 12892 // Model necessary truncations / extenstions. 12893 SDValue Val; 12894 // Truncate Value To Stored Memory Size. 12895 do { 12896 if (!getTruncatedStoreValue(ST, Val)) 12897 continue; 12898 if (!isTypeLegal(LDMemType)) 12899 continue; 12900 if (STMemType != LDMemType) { 12901 // TODO: Support vectors? This requires extract_subvector/bitcast. 12902 if (!STMemType.isVector() && !LDMemType.isVector() && 12903 STMemType.isInteger() && LDMemType.isInteger()) 12904 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val); 12905 else 12906 continue; 12907 } 12908 if (!extendLoadedValueToExtension(LD, Val)) 12909 continue; 12910 return CombineTo(LD, Val, Chain); 12911 } while (false); 12912 12913 // On failure, cleanup dead nodes we may have created. 12914 if (Val->use_empty()) 12915 deleteAndRecombine(Val.getNode()); 12916 return SDValue(); 12917 } 12918 12919 SDValue DAGCombiner::visitLOAD(SDNode *N) { 12920 LoadSDNode *LD = cast<LoadSDNode>(N); 12921 SDValue Chain = LD->getChain(); 12922 SDValue Ptr = LD->getBasePtr(); 12923 12924 // If load is not volatile and there are no uses of the loaded value (and 12925 // the updated indexed value in case of indexed loads), change uses of the 12926 // chain value into uses of the chain input (i.e. delete the dead load). 12927 if (!LD->isVolatile()) { 12928 if (N->getValueType(1) == MVT::Other) { 12929 // Unindexed loads. 12930 if (!N->hasAnyUseOfValue(0)) { 12931 // It's not safe to use the two value CombineTo variant here. e.g. 12932 // v1, chain2 = load chain1, loc 12933 // v2, chain3 = load chain2, loc 12934 // v3 = add v2, c 12935 // Now we replace use of chain2 with chain1. This makes the second load 12936 // isomorphic to the one we are deleting, and thus makes this load live. 12937 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 12938 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 12939 dbgs() << "\n"); 12940 WorklistRemover DeadNodes(*this); 12941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12942 AddUsersToWorklist(Chain.getNode()); 12943 if (N->use_empty()) 12944 deleteAndRecombine(N); 12945 12946 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12947 } 12948 } else { 12949 // Indexed loads. 12950 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 12951 12952 // If this load has an opaque TargetConstant offset, then we cannot split 12953 // the indexing into an add/sub directly (that TargetConstant may not be 12954 // valid for a different type of node, and we cannot convert an opaque 12955 // target constant into a regular constant). 12956 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 12957 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 12958 12959 if (!N->hasAnyUseOfValue(0) && 12960 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 12961 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 12962 SDValue Index; 12963 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 12964 Index = SplitIndexingFromLoad(LD); 12965 // Try to fold the base pointer arithmetic into subsequent loads and 12966 // stores. 12967 AddUsersToWorklist(N); 12968 } else 12969 Index = DAG.getUNDEF(N->getValueType(1)); 12970 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 12971 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 12972 dbgs() << " and 2 other values\n"); 12973 WorklistRemover DeadNodes(*this); 12974 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 12975 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 12976 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 12977 deleteAndRecombine(N); 12978 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12979 } 12980 } 12981 } 12982 12983 // If this load is directly stored, replace the load value with the stored 12984 // value. 12985 if (auto V = ForwardStoreValueToDirectLoad(LD)) 12986 return V; 12987 12988 // Try to infer better alignment information than the load already has. 12989 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 12990 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12991 if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) { 12992 SDValue NewLoad = DAG.getExtLoad( 12993 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 12994 LD->getPointerInfo(), LD->getMemoryVT(), Align, 12995 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12996 // NewLoad will always be N as we are only refining the alignment 12997 assert(NewLoad.getNode() == N); 12998 (void)NewLoad; 12999 } 13000 } 13001 } 13002 13003 if (LD->isUnindexed()) { 13004 // Walk up chain skipping non-aliasing memory nodes. 13005 SDValue BetterChain = FindBetterChain(N, Chain); 13006 13007 // If there is a better chain. 13008 if (Chain != BetterChain) { 13009 SDValue ReplLoad; 13010 13011 // Replace the chain to void dependency. 13012 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 13013 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 13014 BetterChain, Ptr, LD->getMemOperand()); 13015 } else { 13016 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 13017 LD->getValueType(0), 13018 BetterChain, Ptr, LD->getMemoryVT(), 13019 LD->getMemOperand()); 13020 } 13021 13022 // Create token factor to keep old chain connected. 13023 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 13024 MVT::Other, Chain, ReplLoad.getValue(1)); 13025 13026 // Replace uses with load result and token factor 13027 return CombineTo(N, ReplLoad.getValue(0), Token); 13028 } 13029 } 13030 13031 // Try transforming N to an indexed load. 13032 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13033 return SDValue(N, 0); 13034 13035 // Try to slice up N to more direct loads if the slices are mapped to 13036 // different register banks or pairing can take place. 13037 if (SliceUpLoad(N)) 13038 return SDValue(N, 0); 13039 13040 return SDValue(); 13041 } 13042 13043 namespace { 13044 13045 /// Helper structure used to slice a load in smaller loads. 13046 /// Basically a slice is obtained from the following sequence: 13047 /// Origin = load Ty1, Base 13048 /// Shift = srl Ty1 Origin, CstTy Amount 13049 /// Inst = trunc Shift to Ty2 13050 /// 13051 /// Then, it will be rewritten into: 13052 /// Slice = load SliceTy, Base + SliceOffset 13053 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 13054 /// 13055 /// SliceTy is deduced from the number of bits that are actually used to 13056 /// build Inst. 13057 struct LoadedSlice { 13058 /// Helper structure used to compute the cost of a slice. 13059 struct Cost { 13060 /// Are we optimizing for code size. 13061 bool ForCodeSize; 13062 13063 /// Various cost. 13064 unsigned Loads = 0; 13065 unsigned Truncates = 0; 13066 unsigned CrossRegisterBanksCopies = 0; 13067 unsigned ZExts = 0; 13068 unsigned Shift = 0; 13069 13070 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 13071 13072 /// Get the cost of one isolated slice. 13073 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 13074 : ForCodeSize(ForCodeSize), Loads(1) { 13075 EVT TruncType = LS.Inst->getValueType(0); 13076 EVT LoadedType = LS.getLoadedType(); 13077 if (TruncType != LoadedType && 13078 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 13079 ZExts = 1; 13080 } 13081 13082 /// Account for slicing gain in the current cost. 13083 /// Slicing provide a few gains like removing a shift or a 13084 /// truncate. This method allows to grow the cost of the original 13085 /// load with the gain from this slice. 13086 void addSliceGain(const LoadedSlice &LS) { 13087 // Each slice saves a truncate. 13088 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 13089 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 13090 LS.Inst->getValueType(0))) 13091 ++Truncates; 13092 // If there is a shift amount, this slice gets rid of it. 13093 if (LS.Shift) 13094 ++Shift; 13095 // If this slice can merge a cross register bank copy, account for it. 13096 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 13097 ++CrossRegisterBanksCopies; 13098 } 13099 13100 Cost &operator+=(const Cost &RHS) { 13101 Loads += RHS.Loads; 13102 Truncates += RHS.Truncates; 13103 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 13104 ZExts += RHS.ZExts; 13105 Shift += RHS.Shift; 13106 return *this; 13107 } 13108 13109 bool operator==(const Cost &RHS) const { 13110 return Loads == RHS.Loads && Truncates == RHS.Truncates && 13111 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 13112 ZExts == RHS.ZExts && Shift == RHS.Shift; 13113 } 13114 13115 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 13116 13117 bool operator<(const Cost &RHS) const { 13118 // Assume cross register banks copies are as expensive as loads. 13119 // FIXME: Do we want some more target hooks? 13120 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 13121 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 13122 // Unless we are optimizing for code size, consider the 13123 // expensive operation first. 13124 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 13125 return ExpensiveOpsLHS < ExpensiveOpsRHS; 13126 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 13127 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 13128 } 13129 13130 bool operator>(const Cost &RHS) const { return RHS < *this; } 13131 13132 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 13133 13134 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 13135 }; 13136 13137 // The last instruction that represent the slice. This should be a 13138 // truncate instruction. 13139 SDNode *Inst; 13140 13141 // The original load instruction. 13142 LoadSDNode *Origin; 13143 13144 // The right shift amount in bits from the original load. 13145 unsigned Shift; 13146 13147 // The DAG from which Origin came from. 13148 // This is used to get some contextual information about legal types, etc. 13149 SelectionDAG *DAG; 13150 13151 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 13152 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 13153 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 13154 13155 /// Get the bits used in a chunk of bits \p BitWidth large. 13156 /// \return Result is \p BitWidth and has used bits set to 1 and 13157 /// not used bits set to 0. 13158 APInt getUsedBits() const { 13159 // Reproduce the trunc(lshr) sequence: 13160 // - Start from the truncated value. 13161 // - Zero extend to the desired bit width. 13162 // - Shift left. 13163 assert(Origin && "No original load to compare against."); 13164 unsigned BitWidth = Origin->getValueSizeInBits(0); 13165 assert(Inst && "This slice is not bound to an instruction"); 13166 assert(Inst->getValueSizeInBits(0) <= BitWidth && 13167 "Extracted slice is bigger than the whole type!"); 13168 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 13169 UsedBits.setAllBits(); 13170 UsedBits = UsedBits.zext(BitWidth); 13171 UsedBits <<= Shift; 13172 return UsedBits; 13173 } 13174 13175 /// Get the size of the slice to be loaded in bytes. 13176 unsigned getLoadedSize() const { 13177 unsigned SliceSize = getUsedBits().countPopulation(); 13178 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 13179 return SliceSize / 8; 13180 } 13181 13182 /// Get the type that will be loaded for this slice. 13183 /// Note: This may not be the final type for the slice. 13184 EVT getLoadedType() const { 13185 assert(DAG && "Missing context"); 13186 LLVMContext &Ctxt = *DAG->getContext(); 13187 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 13188 } 13189 13190 /// Get the alignment of the load used for this slice. 13191 unsigned getAlignment() const { 13192 unsigned Alignment = Origin->getAlignment(); 13193 unsigned Offset = getOffsetFromBase(); 13194 if (Offset != 0) 13195 Alignment = MinAlign(Alignment, Alignment + Offset); 13196 return Alignment; 13197 } 13198 13199 /// Check if this slice can be rewritten with legal operations. 13200 bool isLegal() const { 13201 // An invalid slice is not legal. 13202 if (!Origin || !Inst || !DAG) 13203 return false; 13204 13205 // Offsets are for indexed load only, we do not handle that. 13206 if (!Origin->getOffset().isUndef()) 13207 return false; 13208 13209 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 13210 13211 // Check that the type is legal. 13212 EVT SliceType = getLoadedType(); 13213 if (!TLI.isTypeLegal(SliceType)) 13214 return false; 13215 13216 // Check that the load is legal for this type. 13217 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 13218 return false; 13219 13220 // Check that the offset can be computed. 13221 // 1. Check its type. 13222 EVT PtrType = Origin->getBasePtr().getValueType(); 13223 if (PtrType == MVT::Untyped || PtrType.isExtended()) 13224 return false; 13225 13226 // 2. Check that it fits in the immediate. 13227 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 13228 return false; 13229 13230 // 3. Check that the computation is legal. 13231 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 13232 return false; 13233 13234 // Check that the zext is legal if it needs one. 13235 EVT TruncateType = Inst->getValueType(0); 13236 if (TruncateType != SliceType && 13237 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 13238 return false; 13239 13240 return true; 13241 } 13242 13243 /// Get the offset in bytes of this slice in the original chunk of 13244 /// bits. 13245 /// \pre DAG != nullptr. 13246 uint64_t getOffsetFromBase() const { 13247 assert(DAG && "Missing context."); 13248 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 13249 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 13250 uint64_t Offset = Shift / 8; 13251 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 13252 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 13253 "The size of the original loaded type is not a multiple of a" 13254 " byte."); 13255 // If Offset is bigger than TySizeInBytes, it means we are loading all 13256 // zeros. This should have been optimized before in the process. 13257 assert(TySizeInBytes > Offset && 13258 "Invalid shift amount for given loaded size"); 13259 if (IsBigEndian) 13260 Offset = TySizeInBytes - Offset - getLoadedSize(); 13261 return Offset; 13262 } 13263 13264 /// Generate the sequence of instructions to load the slice 13265 /// represented by this object and redirect the uses of this slice to 13266 /// this new sequence of instructions. 13267 /// \pre this->Inst && this->Origin are valid Instructions and this 13268 /// object passed the legal check: LoadedSlice::isLegal returned true. 13269 /// \return The last instruction of the sequence used to load the slice. 13270 SDValue loadSlice() const { 13271 assert(Inst && Origin && "Unable to replace a non-existing slice."); 13272 const SDValue &OldBaseAddr = Origin->getBasePtr(); 13273 SDValue BaseAddr = OldBaseAddr; 13274 // Get the offset in that chunk of bytes w.r.t. the endianness. 13275 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 13276 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 13277 if (Offset) { 13278 // BaseAddr = BaseAddr + Offset. 13279 EVT ArithType = BaseAddr.getValueType(); 13280 SDLoc DL(Origin); 13281 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 13282 DAG->getConstant(Offset, DL, ArithType)); 13283 } 13284 13285 // Create the type of the loaded slice according to its size. 13286 EVT SliceType = getLoadedType(); 13287 13288 // Create the load for the slice. 13289 SDValue LastInst = 13290 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 13291 Origin->getPointerInfo().getWithOffset(Offset), 13292 getAlignment(), Origin->getMemOperand()->getFlags()); 13293 // If the final type is not the same as the loaded type, this means that 13294 // we have to pad with zero. Create a zero extend for that. 13295 EVT FinalType = Inst->getValueType(0); 13296 if (SliceType != FinalType) 13297 LastInst = 13298 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 13299 return LastInst; 13300 } 13301 13302 /// Check if this slice can be merged with an expensive cross register 13303 /// bank copy. E.g., 13304 /// i = load i32 13305 /// f = bitcast i32 i to float 13306 bool canMergeExpensiveCrossRegisterBankCopy() const { 13307 if (!Inst || !Inst->hasOneUse()) 13308 return false; 13309 SDNode *Use = *Inst->use_begin(); 13310 if (Use->getOpcode() != ISD::BITCAST) 13311 return false; 13312 assert(DAG && "Missing context"); 13313 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 13314 EVT ResVT = Use->getValueType(0); 13315 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 13316 const TargetRegisterClass *ArgRC = 13317 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 13318 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 13319 return false; 13320 13321 // At this point, we know that we perform a cross-register-bank copy. 13322 // Check if it is expensive. 13323 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 13324 // Assume bitcasts are cheap, unless both register classes do not 13325 // explicitly share a common sub class. 13326 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 13327 return false; 13328 13329 // Check if it will be merged with the load. 13330 // 1. Check the alignment constraint. 13331 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 13332 ResVT.getTypeForEVT(*DAG->getContext())); 13333 13334 if (RequiredAlignment > getAlignment()) 13335 return false; 13336 13337 // 2. Check that the load is a legal operation for that type. 13338 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 13339 return false; 13340 13341 // 3. Check that we do not have a zext in the way. 13342 if (Inst->getValueType(0) != getLoadedType()) 13343 return false; 13344 13345 return true; 13346 } 13347 }; 13348 13349 } // end anonymous namespace 13350 13351 /// Check that all bits set in \p UsedBits form a dense region, i.e., 13352 /// \p UsedBits looks like 0..0 1..1 0..0. 13353 static bool areUsedBitsDense(const APInt &UsedBits) { 13354 // If all the bits are one, this is dense! 13355 if (UsedBits.isAllOnesValue()) 13356 return true; 13357 13358 // Get rid of the unused bits on the right. 13359 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 13360 // Get rid of the unused bits on the left. 13361 if (NarrowedUsedBits.countLeadingZeros()) 13362 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 13363 // Check that the chunk of bits is completely used. 13364 return NarrowedUsedBits.isAllOnesValue(); 13365 } 13366 13367 /// Check whether or not \p First and \p Second are next to each other 13368 /// in memory. This means that there is no hole between the bits loaded 13369 /// by \p First and the bits loaded by \p Second. 13370 static bool areSlicesNextToEachOther(const LoadedSlice &First, 13371 const LoadedSlice &Second) { 13372 assert(First.Origin == Second.Origin && First.Origin && 13373 "Unable to match different memory origins."); 13374 APInt UsedBits = First.getUsedBits(); 13375 assert((UsedBits & Second.getUsedBits()) == 0 && 13376 "Slices are not supposed to overlap."); 13377 UsedBits |= Second.getUsedBits(); 13378 return areUsedBitsDense(UsedBits); 13379 } 13380 13381 /// Adjust the \p GlobalLSCost according to the target 13382 /// paring capabilities and the layout of the slices. 13383 /// \pre \p GlobalLSCost should account for at least as many loads as 13384 /// there is in the slices in \p LoadedSlices. 13385 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13386 LoadedSlice::Cost &GlobalLSCost) { 13387 unsigned NumberOfSlices = LoadedSlices.size(); 13388 // If there is less than 2 elements, no pairing is possible. 13389 if (NumberOfSlices < 2) 13390 return; 13391 13392 // Sort the slices so that elements that are likely to be next to each 13393 // other in memory are next to each other in the list. 13394 llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 13395 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 13396 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 13397 }); 13398 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 13399 // First (resp. Second) is the first (resp. Second) potentially candidate 13400 // to be placed in a paired load. 13401 const LoadedSlice *First = nullptr; 13402 const LoadedSlice *Second = nullptr; 13403 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 13404 // Set the beginning of the pair. 13405 First = Second) { 13406 Second = &LoadedSlices[CurrSlice]; 13407 13408 // If First is NULL, it means we start a new pair. 13409 // Get to the next slice. 13410 if (!First) 13411 continue; 13412 13413 EVT LoadedType = First->getLoadedType(); 13414 13415 // If the types of the slices are different, we cannot pair them. 13416 if (LoadedType != Second->getLoadedType()) 13417 continue; 13418 13419 // Check if the target supplies paired loads for this type. 13420 unsigned RequiredAlignment = 0; 13421 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 13422 // move to the next pair, this type is hopeless. 13423 Second = nullptr; 13424 continue; 13425 } 13426 // Check if we meet the alignment requirement. 13427 if (RequiredAlignment > First->getAlignment()) 13428 continue; 13429 13430 // Check that both loads are next to each other in memory. 13431 if (!areSlicesNextToEachOther(*First, *Second)) 13432 continue; 13433 13434 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 13435 --GlobalLSCost.Loads; 13436 // Move to the next pair. 13437 Second = nullptr; 13438 } 13439 } 13440 13441 /// Check the profitability of all involved LoadedSlice. 13442 /// Currently, it is considered profitable if there is exactly two 13443 /// involved slices (1) which are (2) next to each other in memory, and 13444 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 13445 /// 13446 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 13447 /// the elements themselves. 13448 /// 13449 /// FIXME: When the cost model will be mature enough, we can relax 13450 /// constraints (1) and (2). 13451 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13452 const APInt &UsedBits, bool ForCodeSize) { 13453 unsigned NumberOfSlices = LoadedSlices.size(); 13454 if (StressLoadSlicing) 13455 return NumberOfSlices > 1; 13456 13457 // Check (1). 13458 if (NumberOfSlices != 2) 13459 return false; 13460 13461 // Check (2). 13462 if (!areUsedBitsDense(UsedBits)) 13463 return false; 13464 13465 // Check (3). 13466 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 13467 // The original code has one big load. 13468 OrigCost.Loads = 1; 13469 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 13470 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 13471 // Accumulate the cost of all the slices. 13472 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 13473 GlobalSlicingCost += SliceCost; 13474 13475 // Account as cost in the original configuration the gain obtained 13476 // with the current slices. 13477 OrigCost.addSliceGain(LS); 13478 } 13479 13480 // If the target supports paired load, adjust the cost accordingly. 13481 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 13482 return OrigCost > GlobalSlicingCost; 13483 } 13484 13485 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 13486 /// operations, split it in the various pieces being extracted. 13487 /// 13488 /// This sort of thing is introduced by SROA. 13489 /// This slicing takes care not to insert overlapping loads. 13490 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 13491 bool DAGCombiner::SliceUpLoad(SDNode *N) { 13492 if (Level < AfterLegalizeDAG) 13493 return false; 13494 13495 LoadSDNode *LD = cast<LoadSDNode>(N); 13496 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 13497 !LD->getValueType(0).isInteger()) 13498 return false; 13499 13500 // Keep track of already used bits to detect overlapping values. 13501 // In that case, we will just abort the transformation. 13502 APInt UsedBits(LD->getValueSizeInBits(0), 0); 13503 13504 SmallVector<LoadedSlice, 4> LoadedSlices; 13505 13506 // Check if this load is used as several smaller chunks of bits. 13507 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 13508 // of computation for each trunc. 13509 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 13510 UI != UIEnd; ++UI) { 13511 // Skip the uses of the chain. 13512 if (UI.getUse().getResNo() != 0) 13513 continue; 13514 13515 SDNode *User = *UI; 13516 unsigned Shift = 0; 13517 13518 // Check if this is a trunc(lshr). 13519 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 13520 isa<ConstantSDNode>(User->getOperand(1))) { 13521 Shift = User->getConstantOperandVal(1); 13522 User = *User->use_begin(); 13523 } 13524 13525 // At this point, User is a Truncate, iff we encountered, trunc or 13526 // trunc(lshr). 13527 if (User->getOpcode() != ISD::TRUNCATE) 13528 return false; 13529 13530 // The width of the type must be a power of 2 and greater than 8-bits. 13531 // Otherwise the load cannot be represented in LLVM IR. 13532 // Moreover, if we shifted with a non-8-bits multiple, the slice 13533 // will be across several bytes. We do not support that. 13534 unsigned Width = User->getValueSizeInBits(0); 13535 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 13536 return false; 13537 13538 // Build the slice for this chain of computations. 13539 LoadedSlice LS(User, LD, Shift, &DAG); 13540 APInt CurrentUsedBits = LS.getUsedBits(); 13541 13542 // Check if this slice overlaps with another. 13543 if ((CurrentUsedBits & UsedBits) != 0) 13544 return false; 13545 // Update the bits used globally. 13546 UsedBits |= CurrentUsedBits; 13547 13548 // Check if the new slice would be legal. 13549 if (!LS.isLegal()) 13550 return false; 13551 13552 // Record the slice. 13553 LoadedSlices.push_back(LS); 13554 } 13555 13556 // Abort slicing if it does not seem to be profitable. 13557 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 13558 return false; 13559 13560 ++SlicedLoads; 13561 13562 // Rewrite each chain to use an independent load. 13563 // By construction, each chain can be represented by a unique load. 13564 13565 // Prepare the argument for the new token factor for all the slices. 13566 SmallVector<SDValue, 8> ArgChains; 13567 for (SmallVectorImpl<LoadedSlice>::const_iterator 13568 LSIt = LoadedSlices.begin(), 13569 LSItEnd = LoadedSlices.end(); 13570 LSIt != LSItEnd; ++LSIt) { 13571 SDValue SliceInst = LSIt->loadSlice(); 13572 CombineTo(LSIt->Inst, SliceInst, true); 13573 if (SliceInst.getOpcode() != ISD::LOAD) 13574 SliceInst = SliceInst.getOperand(0); 13575 assert(SliceInst->getOpcode() == ISD::LOAD && 13576 "It takes more than a zext to get to the loaded slice!!"); 13577 ArgChains.push_back(SliceInst.getValue(1)); 13578 } 13579 13580 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 13581 ArgChains); 13582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 13583 AddToWorklist(Chain.getNode()); 13584 return true; 13585 } 13586 13587 /// Check to see if V is (and load (ptr), imm), where the load is having 13588 /// specific bytes cleared out. If so, return the byte size being masked out 13589 /// and the shift amount. 13590 static std::pair<unsigned, unsigned> 13591 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 13592 std::pair<unsigned, unsigned> Result(0, 0); 13593 13594 // Check for the structure we're looking for. 13595 if (V->getOpcode() != ISD::AND || 13596 !isa<ConstantSDNode>(V->getOperand(1)) || 13597 !ISD::isNormalLoad(V->getOperand(0).getNode())) 13598 return Result; 13599 13600 // Check the chain and pointer. 13601 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 13602 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 13603 13604 // This only handles simple types. 13605 if (V.getValueType() != MVT::i16 && 13606 V.getValueType() != MVT::i32 && 13607 V.getValueType() != MVT::i64) 13608 return Result; 13609 13610 // Check the constant mask. Invert it so that the bits being masked out are 13611 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 13612 // follow the sign bit for uniformity. 13613 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 13614 unsigned NotMaskLZ = countLeadingZeros(NotMask); 13615 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 13616 unsigned NotMaskTZ = countTrailingZeros(NotMask); 13617 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 13618 if (NotMaskLZ == 64) return Result; // All zero mask. 13619 13620 // See if we have a continuous run of bits. If so, we have 0*1+0* 13621 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 13622 return Result; 13623 13624 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 13625 if (V.getValueType() != MVT::i64 && NotMaskLZ) 13626 NotMaskLZ -= 64-V.getValueSizeInBits(); 13627 13628 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 13629 switch (MaskedBytes) { 13630 case 1: 13631 case 2: 13632 case 4: break; 13633 default: return Result; // All one mask, or 5-byte mask. 13634 } 13635 13636 // Verify that the first bit starts at a multiple of mask so that the access 13637 // is aligned the same as the access width. 13638 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 13639 13640 // For narrowing to be valid, it must be the case that the load the 13641 // immediately preceeding memory operation before the store. 13642 if (LD == Chain.getNode()) 13643 ; // ok. 13644 else if (Chain->getOpcode() == ISD::TokenFactor && 13645 SDValue(LD, 1).hasOneUse()) { 13646 // LD has only 1 chain use so they are no indirect dependencies. 13647 bool isOk = false; 13648 for (const SDValue &ChainOp : Chain->op_values()) 13649 if (ChainOp.getNode() == LD) { 13650 isOk = true; 13651 break; 13652 } 13653 if (!isOk) 13654 return Result; 13655 } else 13656 return Result; // Fail. 13657 13658 Result.first = MaskedBytes; 13659 Result.second = NotMaskTZ/8; 13660 return Result; 13661 } 13662 13663 /// Check to see if IVal is something that provides a value as specified by 13664 /// MaskInfo. If so, replace the specified store with a narrower store of 13665 /// truncated IVal. 13666 static SDNode * 13667 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 13668 SDValue IVal, StoreSDNode *St, 13669 DAGCombiner *DC) { 13670 unsigned NumBytes = MaskInfo.first; 13671 unsigned ByteShift = MaskInfo.second; 13672 SelectionDAG &DAG = DC->getDAG(); 13673 13674 // Check to see if IVal is all zeros in the part being masked in by the 'or' 13675 // that uses this. If not, this is not a replacement. 13676 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 13677 ByteShift*8, (ByteShift+NumBytes)*8); 13678 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 13679 13680 // Check that it is legal on the target to do this. It is legal if the new 13681 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 13682 // legalization. 13683 MVT VT = MVT::getIntegerVT(NumBytes*8); 13684 if (!DC->isTypeLegal(VT)) 13685 return nullptr; 13686 13687 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 13688 // shifted by ByteShift and truncated down to NumBytes. 13689 if (ByteShift) { 13690 SDLoc DL(IVal); 13691 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 13692 DAG.getConstant(ByteShift*8, DL, 13693 DC->getShiftAmountTy(IVal.getValueType()))); 13694 } 13695 13696 // Figure out the offset for the store and the alignment of the access. 13697 unsigned StOffset; 13698 unsigned NewAlign = St->getAlignment(); 13699 13700 if (DAG.getDataLayout().isLittleEndian()) 13701 StOffset = ByteShift; 13702 else 13703 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 13704 13705 SDValue Ptr = St->getBasePtr(); 13706 if (StOffset) { 13707 SDLoc DL(IVal); 13708 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 13709 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 13710 NewAlign = MinAlign(NewAlign, StOffset); 13711 } 13712 13713 // Truncate down to the new size. 13714 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 13715 13716 ++OpsNarrowed; 13717 return DAG 13718 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 13719 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 13720 .getNode(); 13721 } 13722 13723 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 13724 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 13725 /// narrowing the load and store if it would end up being a win for performance 13726 /// or code size. 13727 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 13728 StoreSDNode *ST = cast<StoreSDNode>(N); 13729 if (ST->isVolatile()) 13730 return SDValue(); 13731 13732 SDValue Chain = ST->getChain(); 13733 SDValue Value = ST->getValue(); 13734 SDValue Ptr = ST->getBasePtr(); 13735 EVT VT = Value.getValueType(); 13736 13737 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 13738 return SDValue(); 13739 13740 unsigned Opc = Value.getOpcode(); 13741 13742 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 13743 // is a byte mask indicating a consecutive number of bytes, check to see if 13744 // Y is known to provide just those bytes. If so, we try to replace the 13745 // load + replace + store sequence with a single (narrower) store, which makes 13746 // the load dead. 13747 if (Opc == ISD::OR) { 13748 std::pair<unsigned, unsigned> MaskedLoad; 13749 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 13750 if (MaskedLoad.first) 13751 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13752 Value.getOperand(1), ST,this)) 13753 return SDValue(NewST, 0); 13754 13755 // Or is commutative, so try swapping X and Y. 13756 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 13757 if (MaskedLoad.first) 13758 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 13759 Value.getOperand(0), ST,this)) 13760 return SDValue(NewST, 0); 13761 } 13762 13763 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 13764 Value.getOperand(1).getOpcode() != ISD::Constant) 13765 return SDValue(); 13766 13767 SDValue N0 = Value.getOperand(0); 13768 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 13769 Chain == SDValue(N0.getNode(), 1)) { 13770 LoadSDNode *LD = cast<LoadSDNode>(N0); 13771 if (LD->getBasePtr() != Ptr || 13772 LD->getPointerInfo().getAddrSpace() != 13773 ST->getPointerInfo().getAddrSpace()) 13774 return SDValue(); 13775 13776 // Find the type to narrow it the load / op / store to. 13777 SDValue N1 = Value.getOperand(1); 13778 unsigned BitWidth = N1.getValueSizeInBits(); 13779 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 13780 if (Opc == ISD::AND) 13781 Imm ^= APInt::getAllOnesValue(BitWidth); 13782 if (Imm == 0 || Imm.isAllOnesValue()) 13783 return SDValue(); 13784 unsigned ShAmt = Imm.countTrailingZeros(); 13785 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 13786 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 13787 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13788 // The narrowing should be profitable, the load/store operation should be 13789 // legal (or custom) and the store size should be equal to the NewVT width. 13790 while (NewBW < BitWidth && 13791 (NewVT.getStoreSizeInBits() != NewBW || 13792 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 13793 !TLI.isNarrowingProfitable(VT, NewVT))) { 13794 NewBW = NextPowerOf2(NewBW); 13795 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 13796 } 13797 if (NewBW >= BitWidth) 13798 return SDValue(); 13799 13800 // If the lsb changed does not start at the type bitwidth boundary, 13801 // start at the previous one. 13802 if (ShAmt % NewBW) 13803 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 13804 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 13805 std::min(BitWidth, ShAmt + NewBW)); 13806 if ((Imm & Mask) == Imm) { 13807 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 13808 if (Opc == ISD::AND) 13809 NewImm ^= APInt::getAllOnesValue(NewBW); 13810 uint64_t PtrOff = ShAmt / 8; 13811 // For big endian targets, we need to adjust the offset to the pointer to 13812 // load the correct bytes. 13813 if (DAG.getDataLayout().isBigEndian()) 13814 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 13815 13816 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 13817 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 13818 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 13819 return SDValue(); 13820 13821 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 13822 Ptr.getValueType(), Ptr, 13823 DAG.getConstant(PtrOff, SDLoc(LD), 13824 Ptr.getValueType())); 13825 SDValue NewLD = 13826 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 13827 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 13828 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 13829 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 13830 DAG.getConstant(NewImm, SDLoc(Value), 13831 NewVT)); 13832 SDValue NewST = 13833 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 13834 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 13835 13836 AddToWorklist(NewPtr.getNode()); 13837 AddToWorklist(NewLD.getNode()); 13838 AddToWorklist(NewVal.getNode()); 13839 WorklistRemover DeadNodes(*this); 13840 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 13841 ++OpsNarrowed; 13842 return NewST; 13843 } 13844 } 13845 13846 return SDValue(); 13847 } 13848 13849 /// For a given floating point load / store pair, if the load value isn't used 13850 /// by any other operations, then consider transforming the pair to integer 13851 /// load / store operations if the target deems the transformation profitable. 13852 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 13853 StoreSDNode *ST = cast<StoreSDNode>(N); 13854 SDValue Chain = ST->getChain(); 13855 SDValue Value = ST->getValue(); 13856 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 13857 Value.hasOneUse() && 13858 Chain == SDValue(Value.getNode(), 1)) { 13859 LoadSDNode *LD = cast<LoadSDNode>(Value); 13860 EVT VT = LD->getMemoryVT(); 13861 if (!VT.isFloatingPoint() || 13862 VT != ST->getMemoryVT() || 13863 LD->isNonTemporal() || 13864 ST->isNonTemporal() || 13865 LD->getPointerInfo().getAddrSpace() != 0 || 13866 ST->getPointerInfo().getAddrSpace() != 0) 13867 return SDValue(); 13868 13869 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 13870 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 13871 !TLI.isOperationLegal(ISD::STORE, IntVT) || 13872 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 13873 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 13874 return SDValue(); 13875 13876 unsigned LDAlign = LD->getAlignment(); 13877 unsigned STAlign = ST->getAlignment(); 13878 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 13879 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 13880 if (LDAlign < ABIAlign || STAlign < ABIAlign) 13881 return SDValue(); 13882 13883 SDValue NewLD = 13884 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 13885 LD->getPointerInfo(), LDAlign); 13886 13887 SDValue NewST = 13888 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 13889 ST->getPointerInfo(), STAlign); 13890 13891 AddToWorklist(NewLD.getNode()); 13892 AddToWorklist(NewST.getNode()); 13893 WorklistRemover DeadNodes(*this); 13894 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 13895 ++LdStFP2Int; 13896 return NewST; 13897 } 13898 13899 return SDValue(); 13900 } 13901 13902 // This is a helper function for visitMUL to check the profitability 13903 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 13904 // MulNode is the original multiply, AddNode is (add x, c1), 13905 // and ConstNode is c2. 13906 // 13907 // If the (add x, c1) has multiple uses, we could increase 13908 // the number of adds if we make this transformation. 13909 // It would only be worth doing this if we can remove a 13910 // multiply in the process. Check for that here. 13911 // To illustrate: 13912 // (A + c1) * c3 13913 // (A + c2) * c3 13914 // We're checking for cases where we have common "c3 * A" expressions. 13915 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 13916 SDValue &AddNode, 13917 SDValue &ConstNode) { 13918 APInt Val; 13919 13920 // If the add only has one use, this would be OK to do. 13921 if (AddNode.getNode()->hasOneUse()) 13922 return true; 13923 13924 // Walk all the users of the constant with which we're multiplying. 13925 for (SDNode *Use : ConstNode->uses()) { 13926 if (Use == MulNode) // This use is the one we're on right now. Skip it. 13927 continue; 13928 13929 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 13930 SDNode *OtherOp; 13931 SDNode *MulVar = AddNode.getOperand(0).getNode(); 13932 13933 // OtherOp is what we're multiplying against the constant. 13934 if (Use->getOperand(0) == ConstNode) 13935 OtherOp = Use->getOperand(1).getNode(); 13936 else 13937 OtherOp = Use->getOperand(0).getNode(); 13938 13939 // Check to see if multiply is with the same operand of our "add". 13940 // 13941 // ConstNode = CONST 13942 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 13943 // ... 13944 // AddNode = (A + c1) <-- MulVar is A. 13945 // = AddNode * ConstNode <-- current visiting instruction. 13946 // 13947 // If we make this transformation, we will have a common 13948 // multiply (ConstNode * A) that we can save. 13949 if (OtherOp == MulVar) 13950 return true; 13951 13952 // Now check to see if a future expansion will give us a common 13953 // multiply. 13954 // 13955 // ConstNode = CONST 13956 // AddNode = (A + c1) 13957 // ... = AddNode * ConstNode <-- current visiting instruction. 13958 // ... 13959 // OtherOp = (A + c2) 13960 // Use = OtherOp * ConstNode <-- visiting Use. 13961 // 13962 // If we make this transformation, we will have a common 13963 // multiply (CONST * A) after we also do the same transformation 13964 // to the "t2" instruction. 13965 if (OtherOp->getOpcode() == ISD::ADD && 13966 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 13967 OtherOp->getOperand(0).getNode() == MulVar) 13968 return true; 13969 } 13970 } 13971 13972 // Didn't find a case where this would be profitable. 13973 return false; 13974 } 13975 13976 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 13977 unsigned NumStores) { 13978 SmallVector<SDValue, 8> Chains; 13979 SmallPtrSet<const SDNode *, 8> Visited; 13980 SDLoc StoreDL(StoreNodes[0].MemNode); 13981 13982 for (unsigned i = 0; i < NumStores; ++i) { 13983 Visited.insert(StoreNodes[i].MemNode); 13984 } 13985 13986 // don't include nodes that are children 13987 for (unsigned i = 0; i < NumStores; ++i) { 13988 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 13989 Chains.push_back(StoreNodes[i].MemNode->getChain()); 13990 } 13991 13992 assert(Chains.size() > 0 && "Chain should have generated a chain"); 13993 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 13994 } 13995 13996 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 13997 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 13998 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 13999 // Make sure we have something to merge. 14000 if (NumStores < 2) 14001 return false; 14002 14003 // The latest Node in the DAG. 14004 SDLoc DL(StoreNodes[0].MemNode); 14005 14006 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 14007 unsigned SizeInBits = NumStores * ElementSizeBits; 14008 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14009 14010 EVT StoreTy; 14011 if (UseVector) { 14012 unsigned Elts = NumStores * NumMemElts; 14013 // Get the type for the merged vector store. 14014 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 14015 } else 14016 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 14017 14018 SDValue StoredVal; 14019 if (UseVector) { 14020 if (IsConstantSrc) { 14021 SmallVector<SDValue, 8> BuildVector; 14022 for (unsigned I = 0; I != NumStores; ++I) { 14023 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 14024 SDValue Val = St->getValue(); 14025 // If constant is of the wrong type, convert it now. 14026 if (MemVT != Val.getValueType()) { 14027 Val = peekThroughBitcasts(Val); 14028 // Deal with constants of wrong size. 14029 if (ElementSizeBits != Val.getValueSizeInBits()) { 14030 EVT IntMemVT = 14031 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 14032 if (isa<ConstantFPSDNode>(Val)) { 14033 // Not clear how to truncate FP values. 14034 return false; 14035 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 14036 Val = DAG.getConstant(C->getAPIntValue() 14037 .zextOrTrunc(Val.getValueSizeInBits()) 14038 .zextOrTrunc(ElementSizeBits), 14039 SDLoc(C), IntMemVT); 14040 } 14041 // Make sure correctly size type is the correct type. 14042 Val = DAG.getBitcast(MemVT, Val); 14043 } 14044 BuildVector.push_back(Val); 14045 } 14046 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 14047 : ISD::BUILD_VECTOR, 14048 DL, StoreTy, BuildVector); 14049 } else { 14050 SmallVector<SDValue, 8> Ops; 14051 for (unsigned i = 0; i < NumStores; ++i) { 14052 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 14053 SDValue Val = peekThroughBitcasts(St->getValue()); 14054 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 14055 // type MemVT. If the underlying value is not the correct 14056 // type, but it is an extraction of an appropriate vector we 14057 // can recast Val to be of the correct type. This may require 14058 // converting between EXTRACT_VECTOR_ELT and 14059 // EXTRACT_SUBVECTOR. 14060 if ((MemVT != Val.getValueType()) && 14061 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14062 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 14063 EVT MemVTScalarTy = MemVT.getScalarType(); 14064 // We may need to add a bitcast here to get types to line up. 14065 if (MemVTScalarTy != Val.getValueType().getScalarType()) { 14066 Val = DAG.getBitcast(MemVT, Val); 14067 } else { 14068 unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR 14069 : ISD::EXTRACT_VECTOR_ELT; 14070 SDValue Vec = Val.getOperand(0); 14071 SDValue Idx = Val.getOperand(1); 14072 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); 14073 } 14074 } 14075 Ops.push_back(Val); 14076 } 14077 14078 // Build the extracted vector elements back into a vector. 14079 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 14080 : ISD::BUILD_VECTOR, 14081 DL, StoreTy, Ops); 14082 } 14083 } else { 14084 // We should always use a vector store when merging extracted vector 14085 // elements, so this path implies a store of constants. 14086 assert(IsConstantSrc && "Merged vector elements should use vector store"); 14087 14088 APInt StoreInt(SizeInBits, 0); 14089 14090 // Construct a single integer constant which is made of the smaller 14091 // constant inputs. 14092 bool IsLE = DAG.getDataLayout().isLittleEndian(); 14093 for (unsigned i = 0; i < NumStores; ++i) { 14094 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 14095 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 14096 14097 SDValue Val = St->getValue(); 14098 Val = peekThroughBitcasts(Val); 14099 StoreInt <<= ElementSizeBits; 14100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 14101 StoreInt |= C->getAPIntValue() 14102 .zextOrTrunc(ElementSizeBits) 14103 .zextOrTrunc(SizeInBits); 14104 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 14105 StoreInt |= C->getValueAPF() 14106 .bitcastToAPInt() 14107 .zextOrTrunc(ElementSizeBits) 14108 .zextOrTrunc(SizeInBits); 14109 // If fp truncation is necessary give up for now. 14110 if (MemVT.getSizeInBits() != ElementSizeBits) 14111 return false; 14112 } else { 14113 llvm_unreachable("Invalid constant element type"); 14114 } 14115 } 14116 14117 // Create the new Load and Store operations. 14118 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 14119 } 14120 14121 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14122 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 14123 14124 // make sure we use trunc store if it's necessary to be legal. 14125 SDValue NewStore; 14126 if (!UseTrunc) { 14127 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 14128 FirstInChain->getPointerInfo(), 14129 FirstInChain->getAlignment()); 14130 } else { // Must be realized as a trunc store 14131 EVT LegalizedStoredValTy = 14132 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 14133 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 14134 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 14135 SDValue ExtendedStoreVal = 14136 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 14137 LegalizedStoredValTy); 14138 NewStore = DAG.getTruncStore( 14139 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 14140 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 14141 FirstInChain->getAlignment(), 14142 FirstInChain->getMemOperand()->getFlags()); 14143 } 14144 14145 // Replace all merged stores with the new store. 14146 for (unsigned i = 0; i < NumStores; ++i) 14147 CombineTo(StoreNodes[i].MemNode, NewStore); 14148 14149 AddToWorklist(NewChain.getNode()); 14150 return true; 14151 } 14152 14153 void DAGCombiner::getStoreMergeCandidates( 14154 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 14155 SDNode *&RootNode) { 14156 // This holds the base pointer, index, and the offset in bytes from the base 14157 // pointer. 14158 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 14159 EVT MemVT = St->getMemoryVT(); 14160 14161 SDValue Val = peekThroughBitcasts(St->getValue()); 14162 // We must have a base and an offset. 14163 if (!BasePtr.getBase().getNode()) 14164 return; 14165 14166 // Do not handle stores to undef base pointers. 14167 if (BasePtr.getBase().isUndef()) 14168 return; 14169 14170 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 14171 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14172 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14173 bool IsLoadSrc = isa<LoadSDNode>(Val); 14174 BaseIndexOffset LBasePtr; 14175 // Match on loadbaseptr if relevant. 14176 EVT LoadVT; 14177 if (IsLoadSrc) { 14178 auto *Ld = cast<LoadSDNode>(Val); 14179 LBasePtr = BaseIndexOffset::match(Ld, DAG); 14180 LoadVT = Ld->getMemoryVT(); 14181 // Load and store should be the same type. 14182 if (MemVT != LoadVT) 14183 return; 14184 // Loads must only have one use. 14185 if (!Ld->hasNUsesOfValue(1, 0)) 14186 return; 14187 // The memory operands must not be volatile. 14188 if (Ld->isVolatile() || Ld->isIndexed()) 14189 return; 14190 } 14191 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 14192 int64_t &Offset) -> bool { 14193 if (Other->isVolatile() || Other->isIndexed()) 14194 return false; 14195 SDValue Val = peekThroughBitcasts(Other->getValue()); 14196 // Allow merging constants of different types as integers. 14197 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 14198 : Other->getMemoryVT() != MemVT; 14199 if (IsLoadSrc) { 14200 if (NoTypeMatch) 14201 return false; 14202 // The Load's Base Ptr must also match 14203 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 14204 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 14205 if (LoadVT != OtherLd->getMemoryVT()) 14206 return false; 14207 // Loads must only have one use. 14208 if (!OtherLd->hasNUsesOfValue(1, 0)) 14209 return false; 14210 // The memory operands must not be volatile. 14211 if (OtherLd->isVolatile() || OtherLd->isIndexed()) 14212 return false; 14213 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 14214 return false; 14215 } else 14216 return false; 14217 } 14218 if (IsConstantSrc) { 14219 if (NoTypeMatch) 14220 return false; 14221 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 14222 return false; 14223 } 14224 if (IsExtractVecSrc) { 14225 // Do not merge truncated stores here. 14226 if (Other->isTruncatingStore()) 14227 return false; 14228 if (!MemVT.bitsEq(Val.getValueType())) 14229 return false; 14230 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 14231 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14232 return false; 14233 } 14234 Ptr = BaseIndexOffset::match(Other, DAG); 14235 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 14236 }; 14237 14238 // We looking for a root node which is an ancestor to all mergable 14239 // stores. We search up through a load, to our root and then down 14240 // through all children. For instance we will find Store{1,2,3} if 14241 // St is Store1, Store2. or Store3 where the root is not a load 14242 // which always true for nonvolatile ops. TODO: Expand 14243 // the search to find all valid candidates through multiple layers of loads. 14244 // 14245 // Root 14246 // |-------|-------| 14247 // Load Load Store3 14248 // | | 14249 // Store1 Store2 14250 // 14251 // FIXME: We should be able to climb and 14252 // descend TokenFactors to find candidates as well. 14253 14254 RootNode = St->getChain().getNode(); 14255 14256 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 14257 RootNode = Ldn->getChain().getNode(); 14258 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14259 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 14260 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 14261 if (I2.getOperandNo() == 0) 14262 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 14263 BaseIndexOffset Ptr; 14264 int64_t PtrDiff; 14265 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14266 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14267 } 14268 } else 14269 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14270 if (I.getOperandNo() == 0) 14271 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 14272 BaseIndexOffset Ptr; 14273 int64_t PtrDiff; 14274 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14275 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14276 } 14277 } 14278 14279 // We need to check that merging these stores does not cause a loop in 14280 // the DAG. Any store candidate may depend on another candidate 14281 // indirectly through its operand (we already consider dependencies 14282 // through the chain). Check in parallel by searching up from 14283 // non-chain operands of candidates. 14284 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 14285 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 14286 SDNode *RootNode) { 14287 // FIXME: We should be able to truncate a full search of 14288 // predecessors by doing a BFS and keeping tabs the originating 14289 // stores from which worklist nodes come from in a similar way to 14290 // TokenFactor simplfication. 14291 14292 SmallPtrSet<const SDNode *, 32> Visited; 14293 SmallVector<const SDNode *, 8> Worklist; 14294 14295 // RootNode is a predecessor to all candidates so we need not search 14296 // past it. Add RootNode (peeking through TokenFactors). Do not count 14297 // these towards size check. 14298 14299 Worklist.push_back(RootNode); 14300 while (!Worklist.empty()) { 14301 auto N = Worklist.pop_back_val(); 14302 if (!Visited.insert(N).second) 14303 continue; // Already present in Visited. 14304 if (N->getOpcode() == ISD::TokenFactor) { 14305 for (SDValue Op : N->ops()) 14306 Worklist.push_back(Op.getNode()); 14307 } 14308 } 14309 14310 // Don't count pruning nodes towards max. 14311 unsigned int Max = 1024 + Visited.size(); 14312 // Search Ops of store candidates. 14313 for (unsigned i = 0; i < NumStores; ++i) { 14314 SDNode *N = StoreNodes[i].MemNode; 14315 // Of the 4 Store Operands: 14316 // * Chain (Op 0) -> We have already considered these 14317 // in candidate selection and can be 14318 // safely ignored 14319 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 14320 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant, 14321 // but aren't necessarily fromt the same base node, so 14322 // cycles possible (e.g. via indexed store). 14323 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for 14324 // non-indexed stores). Not constant on all targets (e.g. ARM) 14325 // and so can participate in a cycle. 14326 for (unsigned j = 1; j < N->getNumOperands(); ++j) 14327 Worklist.push_back(N->getOperand(j).getNode()); 14328 } 14329 // Search through DAG. We can stop early if we find a store node. 14330 for (unsigned i = 0; i < NumStores; ++i) 14331 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 14332 Max)) 14333 return false; 14334 return true; 14335 } 14336 14337 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 14338 if (OptLevel == CodeGenOpt::None) 14339 return false; 14340 14341 EVT MemVT = St->getMemoryVT(); 14342 int64_t ElementSizeBytes = MemVT.getStoreSize(); 14343 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14344 14345 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 14346 return false; 14347 14348 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 14349 Attribute::NoImplicitFloat); 14350 14351 // This function cannot currently deal with non-byte-sized memory sizes. 14352 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 14353 return false; 14354 14355 if (!MemVT.isSimple()) 14356 return false; 14357 14358 // Perform an early exit check. Do not bother looking at stored values that 14359 // are not constants, loads, or extracted vector elements. 14360 SDValue StoredVal = peekThroughBitcasts(St->getValue()); 14361 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 14362 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 14363 isa<ConstantFPSDNode>(StoredVal); 14364 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14365 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14366 14367 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 14368 return false; 14369 14370 SmallVector<MemOpLink, 8> StoreNodes; 14371 SDNode *RootNode; 14372 // Find potential store merge candidates by searching through chain sub-DAG 14373 getStoreMergeCandidates(St, StoreNodes, RootNode); 14374 14375 // Check if there is anything to merge. 14376 if (StoreNodes.size() < 2) 14377 return false; 14378 14379 // Sort the memory operands according to their distance from the 14380 // base pointer. 14381 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) { 14382 return LHS.OffsetFromBase < RHS.OffsetFromBase; 14383 }); 14384 14385 // Store Merge attempts to merge the lowest stores. This generally 14386 // works out as if successful, as the remaining stores are checked 14387 // after the first collection of stores is merged. However, in the 14388 // case that a non-mergeable store is found first, e.g., {p[-2], 14389 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 14390 // mergeable cases. To prevent this, we prune such stores from the 14391 // front of StoreNodes here. 14392 14393 bool RV = false; 14394 while (StoreNodes.size() > 1) { 14395 unsigned StartIdx = 0; 14396 while ((StartIdx + 1 < StoreNodes.size()) && 14397 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 14398 StoreNodes[StartIdx + 1].OffsetFromBase) 14399 ++StartIdx; 14400 14401 // Bail if we don't have enough candidates to merge. 14402 if (StartIdx + 1 >= StoreNodes.size()) 14403 return RV; 14404 14405 if (StartIdx) 14406 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 14407 14408 // Scan the memory operations on the chain and find the first 14409 // non-consecutive store memory address. 14410 unsigned NumConsecutiveStores = 1; 14411 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 14412 // Check that the addresses are consecutive starting from the second 14413 // element in the list of stores. 14414 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 14415 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 14416 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14417 break; 14418 NumConsecutiveStores = i + 1; 14419 } 14420 14421 if (NumConsecutiveStores < 2) { 14422 StoreNodes.erase(StoreNodes.begin(), 14423 StoreNodes.begin() + NumConsecutiveStores); 14424 continue; 14425 } 14426 14427 // The node with the lowest store address. 14428 LLVMContext &Context = *DAG.getContext(); 14429 const DataLayout &DL = DAG.getDataLayout(); 14430 14431 // Store the constants into memory as one consecutive store. 14432 if (IsConstantSrc) { 14433 while (NumConsecutiveStores >= 2) { 14434 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14435 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14436 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14437 unsigned LastLegalType = 1; 14438 unsigned LastLegalVectorType = 1; 14439 bool LastIntegerTrunc = false; 14440 bool NonZero = false; 14441 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 14442 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14443 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 14444 SDValue StoredVal = ST->getValue(); 14445 bool IsElementZero = false; 14446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 14447 IsElementZero = C->isNullValue(); 14448 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 14449 IsElementZero = C->getConstantFPValue()->isNullValue(); 14450 if (IsElementZero) { 14451 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 14452 FirstZeroAfterNonZero = i; 14453 } 14454 NonZero |= !IsElementZero; 14455 14456 // Find a legal type for the constant store. 14457 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14458 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14459 bool IsFast = false; 14460 14461 // Break early when size is too large to be legal. 14462 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14463 break; 14464 14465 if (TLI.isTypeLegal(StoreTy) && 14466 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14467 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14468 FirstStoreAlign, &IsFast) && 14469 IsFast) { 14470 LastIntegerTrunc = false; 14471 LastLegalType = i + 1; 14472 // Or check whether a truncstore is legal. 14473 } else if (TLI.getTypeAction(Context, StoreTy) == 14474 TargetLowering::TypePromoteInteger) { 14475 EVT LegalizedStoredValTy = 14476 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 14477 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14478 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14479 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14480 FirstStoreAlign, &IsFast) && 14481 IsFast) { 14482 LastIntegerTrunc = true; 14483 LastLegalType = i + 1; 14484 } 14485 } 14486 14487 // We only use vectors if the constant is known to be zero or the 14488 // target allows it and the function is not marked with the 14489 // noimplicitfloat attribute. 14490 if ((!NonZero || 14491 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 14492 !NoVectors) { 14493 // Find a legal type for the vector store. 14494 unsigned Elts = (i + 1) * NumMemElts; 14495 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14496 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 14497 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14498 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14499 FirstStoreAlign, &IsFast) && 14500 IsFast) 14501 LastLegalVectorType = i + 1; 14502 } 14503 } 14504 14505 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 14506 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 14507 14508 // Check if we found a legal integer type that creates a meaningful 14509 // merge. 14510 if (NumElem < 2) { 14511 // We know that candidate stores are in order and of correct 14512 // shape. While there is no mergeable sequence from the 14513 // beginning one may start later in the sequence. The only 14514 // reason a merge of size N could have failed where another of 14515 // the same size would not have, is if the alignment has 14516 // improved or we've dropped a non-zero value. Drop as many 14517 // candidates as we can here. 14518 unsigned NumSkip = 1; 14519 while ( 14520 (NumSkip < NumConsecutiveStores) && 14521 (NumSkip < FirstZeroAfterNonZero) && 14522 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14523 NumSkip++; 14524 14525 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14526 NumConsecutiveStores -= NumSkip; 14527 continue; 14528 } 14529 14530 // Check that we can merge these candidates without causing a cycle. 14531 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14532 RootNode)) { 14533 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14534 NumConsecutiveStores -= NumElem; 14535 continue; 14536 } 14537 14538 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true, 14539 UseVector, LastIntegerTrunc); 14540 14541 // Remove merged stores for next iteration. 14542 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14543 NumConsecutiveStores -= NumElem; 14544 } 14545 continue; 14546 } 14547 14548 // When extracting multiple vector elements, try to store them 14549 // in one vector store rather than a sequence of scalar stores. 14550 if (IsExtractVecSrc) { 14551 // Loop on Consecutive Stores on success. 14552 while (NumConsecutiveStores >= 2) { 14553 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14554 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14555 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14556 unsigned NumStoresToMerge = 1; 14557 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14558 // Find a legal type for the vector store. 14559 unsigned Elts = (i + 1) * NumMemElts; 14560 EVT Ty = 14561 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 14562 bool IsFast; 14563 14564 // Break early when size is too large to be legal. 14565 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 14566 break; 14567 14568 if (TLI.isTypeLegal(Ty) && 14569 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 14570 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 14571 FirstStoreAlign, &IsFast) && 14572 IsFast) 14573 NumStoresToMerge = i + 1; 14574 } 14575 14576 // Check if we found a legal integer type creating a meaningful 14577 // merge. 14578 if (NumStoresToMerge < 2) { 14579 // We know that candidate stores are in order and of correct 14580 // shape. While there is no mergeable sequence from the 14581 // beginning one may start later in the sequence. The only 14582 // reason a merge of size N could have failed where another of 14583 // the same size would not have, is if the alignment has 14584 // improved. Drop as many candidates as we can here. 14585 unsigned NumSkip = 1; 14586 while ( 14587 (NumSkip < NumConsecutiveStores) && 14588 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14589 NumSkip++; 14590 14591 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14592 NumConsecutiveStores -= NumSkip; 14593 continue; 14594 } 14595 14596 // Check that we can merge these candidates without causing a cycle. 14597 if (!checkMergeStoreCandidatesForDependencies( 14598 StoreNodes, NumStoresToMerge, RootNode)) { 14599 StoreNodes.erase(StoreNodes.begin(), 14600 StoreNodes.begin() + NumStoresToMerge); 14601 NumConsecutiveStores -= NumStoresToMerge; 14602 continue; 14603 } 14604 14605 RV |= MergeStoresOfConstantsOrVecElts( 14606 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 14607 14608 StoreNodes.erase(StoreNodes.begin(), 14609 StoreNodes.begin() + NumStoresToMerge); 14610 NumConsecutiveStores -= NumStoresToMerge; 14611 } 14612 continue; 14613 } 14614 14615 // Below we handle the case of multiple consecutive stores that 14616 // come from multiple consecutive loads. We merge them into a single 14617 // wide load and a single wide store. 14618 14619 // Look for load nodes which are used by the stored values. 14620 SmallVector<MemOpLink, 8> LoadNodes; 14621 14622 // Find acceptable loads. Loads need to have the same chain (token factor), 14623 // must not be zext, volatile, indexed, and they must be consecutive. 14624 BaseIndexOffset LdBasePtr; 14625 14626 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 14627 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 14628 SDValue Val = peekThroughBitcasts(St->getValue()); 14629 LoadSDNode *Ld = cast<LoadSDNode>(Val); 14630 14631 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 14632 // If this is not the first ptr that we check. 14633 int64_t LdOffset = 0; 14634 if (LdBasePtr.getBase().getNode()) { 14635 // The base ptr must be the same. 14636 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 14637 break; 14638 } else { 14639 // Check that all other base pointers are the same as this one. 14640 LdBasePtr = LdPtr; 14641 } 14642 14643 // We found a potential memory operand to merge. 14644 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 14645 } 14646 14647 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 14648 // If we have load/store pair instructions and we only have two values, 14649 // don't bother merging. 14650 unsigned RequiredAlignment; 14651 if (LoadNodes.size() == 2 && 14652 TLI.hasPairedLoad(MemVT, RequiredAlignment) && 14653 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 14654 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 14655 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 14656 break; 14657 } 14658 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14659 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 14660 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 14661 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 14662 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 14663 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 14664 14665 // Scan the memory operations on the chain and find the first 14666 // non-consecutive load memory address. These variables hold the index in 14667 // the store node array. 14668 14669 unsigned LastConsecutiveLoad = 1; 14670 14671 // This variable refers to the size and not index in the array. 14672 unsigned LastLegalVectorType = 1; 14673 unsigned LastLegalIntegerType = 1; 14674 bool isDereferenceable = true; 14675 bool DoIntegerTruncate = false; 14676 StartAddress = LoadNodes[0].OffsetFromBase; 14677 SDValue FirstChain = FirstLoad->getChain(); 14678 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 14679 // All loads must share the same chain. 14680 if (LoadNodes[i].MemNode->getChain() != FirstChain) 14681 break; 14682 14683 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 14684 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14685 break; 14686 LastConsecutiveLoad = i; 14687 14688 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 14689 isDereferenceable = false; 14690 14691 // Find a legal type for the vector store. 14692 unsigned Elts = (i + 1) * NumMemElts; 14693 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14694 14695 // Break early when size is too large to be legal. 14696 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 14697 break; 14698 14699 bool IsFastSt, IsFastLd; 14700 if (TLI.isTypeLegal(StoreTy) && 14701 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14702 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14703 FirstStoreAlign, &IsFastSt) && 14704 IsFastSt && 14705 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14706 FirstLoadAlign, &IsFastLd) && 14707 IsFastLd) { 14708 LastLegalVectorType = i + 1; 14709 } 14710 14711 // Find a legal type for the integer store. 14712 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 14713 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 14714 if (TLI.isTypeLegal(StoreTy) && 14715 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 14716 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14717 FirstStoreAlign, &IsFastSt) && 14718 IsFastSt && 14719 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14720 FirstLoadAlign, &IsFastLd) && 14721 IsFastLd) { 14722 LastLegalIntegerType = i + 1; 14723 DoIntegerTruncate = false; 14724 // Or check whether a truncstore and extload is legal. 14725 } else if (TLI.getTypeAction(Context, StoreTy) == 14726 TargetLowering::TypePromoteInteger) { 14727 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 14728 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 14729 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 14730 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, 14731 StoreTy) && 14732 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, 14733 StoreTy) && 14734 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 14735 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 14736 FirstStoreAlign, &IsFastSt) && 14737 IsFastSt && 14738 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 14739 FirstLoadAlign, &IsFastLd) && 14740 IsFastLd) { 14741 LastLegalIntegerType = i + 1; 14742 DoIntegerTruncate = true; 14743 } 14744 } 14745 } 14746 14747 // Only use vector types if the vector type is larger than the integer 14748 // type. If they are the same, use integers. 14749 bool UseVectorTy = 14750 LastLegalVectorType > LastLegalIntegerType && !NoVectors; 14751 unsigned LastLegalType = 14752 std::max(LastLegalVectorType, LastLegalIntegerType); 14753 14754 // We add +1 here because the LastXXX variables refer to location while 14755 // the NumElem refers to array/index size. 14756 unsigned NumElem = 14757 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 14758 NumElem = std::min(LastLegalType, NumElem); 14759 14760 if (NumElem < 2) { 14761 // We know that candidate stores are in order and of correct 14762 // shape. While there is no mergeable sequence from the 14763 // beginning one may start later in the sequence. The only 14764 // reason a merge of size N could have failed where another of 14765 // the same size would not have is if the alignment or either 14766 // the load or store has improved. Drop as many candidates as we 14767 // can here. 14768 unsigned NumSkip = 1; 14769 while ((NumSkip < LoadNodes.size()) && 14770 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 14771 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 14772 NumSkip++; 14773 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 14774 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 14775 NumConsecutiveStores -= NumSkip; 14776 continue; 14777 } 14778 14779 // Check that we can merge these candidates without causing a cycle. 14780 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 14781 RootNode)) { 14782 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14783 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14784 NumConsecutiveStores -= NumElem; 14785 continue; 14786 } 14787 14788 // Find if it is better to use vectors or integers to load and store 14789 // to memory. 14790 EVT JointMemOpVT; 14791 if (UseVectorTy) { 14792 // Find a legal type for the vector store. 14793 unsigned Elts = NumElem * NumMemElts; 14794 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 14795 } else { 14796 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 14797 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 14798 } 14799 14800 SDLoc LoadDL(LoadNodes[0].MemNode); 14801 SDLoc StoreDL(StoreNodes[0].MemNode); 14802 14803 // The merged loads are required to have the same incoming chain, so 14804 // using the first's chain is acceptable. 14805 14806 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 14807 AddToWorklist(NewStoreChain.getNode()); 14808 14809 MachineMemOperand::Flags MMOFlags = 14810 isDereferenceable ? MachineMemOperand::MODereferenceable 14811 : MachineMemOperand::MONone; 14812 14813 SDValue NewLoad, NewStore; 14814 if (UseVectorTy || !DoIntegerTruncate) { 14815 NewLoad = 14816 DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 14817 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 14818 FirstLoadAlign, MMOFlags); 14819 NewStore = DAG.getStore( 14820 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 14821 FirstInChain->getPointerInfo(), FirstStoreAlign); 14822 } else { // This must be the truncstore/extload case 14823 EVT ExtendedTy = 14824 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 14825 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 14826 FirstLoad->getChain(), FirstLoad->getBasePtr(), 14827 FirstLoad->getPointerInfo(), JointMemOpVT, 14828 FirstLoadAlign, MMOFlags); 14829 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 14830 FirstInChain->getBasePtr(), 14831 FirstInChain->getPointerInfo(), 14832 JointMemOpVT, FirstInChain->getAlignment(), 14833 FirstInChain->getMemOperand()->getFlags()); 14834 } 14835 14836 // Transfer chain users from old loads to the new load. 14837 for (unsigned i = 0; i < NumElem; ++i) { 14838 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 14839 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 14840 SDValue(NewLoad.getNode(), 1)); 14841 } 14842 14843 // Replace the all stores with the new store. Recursively remove 14844 // corresponding value if its no longer used. 14845 for (unsigned i = 0; i < NumElem; ++i) { 14846 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 14847 CombineTo(StoreNodes[i].MemNode, NewStore); 14848 if (Val.getNode()->use_empty()) 14849 recursivelyDeleteUnusedNodes(Val.getNode()); 14850 } 14851 14852 RV = true; 14853 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 14854 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 14855 NumConsecutiveStores -= NumElem; 14856 } 14857 } 14858 return RV; 14859 } 14860 14861 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 14862 SDLoc SL(ST); 14863 SDValue ReplStore; 14864 14865 // Replace the chain to avoid dependency. 14866 if (ST->isTruncatingStore()) { 14867 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 14868 ST->getBasePtr(), ST->getMemoryVT(), 14869 ST->getMemOperand()); 14870 } else { 14871 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 14872 ST->getMemOperand()); 14873 } 14874 14875 // Create token to keep both nodes around. 14876 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 14877 MVT::Other, ST->getChain(), ReplStore); 14878 14879 // Make sure the new and old chains are cleaned up. 14880 AddToWorklist(Token.getNode()); 14881 14882 // Don't add users to work list. 14883 return CombineTo(ST, Token, false); 14884 } 14885 14886 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 14887 SDValue Value = ST->getValue(); 14888 if (Value.getOpcode() == ISD::TargetConstantFP) 14889 return SDValue(); 14890 14891 SDLoc DL(ST); 14892 14893 SDValue Chain = ST->getChain(); 14894 SDValue Ptr = ST->getBasePtr(); 14895 14896 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 14897 14898 // NOTE: If the original store is volatile, this transform must not increase 14899 // the number of stores. For example, on x86-32 an f64 can be stored in one 14900 // processor operation but an i64 (which is not legal) requires two. So the 14901 // transform should not be done in this case. 14902 14903 SDValue Tmp; 14904 switch (CFP->getSimpleValueType(0).SimpleTy) { 14905 default: 14906 llvm_unreachable("Unknown FP type"); 14907 case MVT::f16: // We don't do this for these yet. 14908 case MVT::f80: 14909 case MVT::f128: 14910 case MVT::ppcf128: 14911 return SDValue(); 14912 case MVT::f32: 14913 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 14914 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14915 ; 14916 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 14917 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 14918 MVT::i32); 14919 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 14920 } 14921 14922 return SDValue(); 14923 case MVT::f64: 14924 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 14925 !ST->isVolatile()) || 14926 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 14927 ; 14928 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 14929 getZExtValue(), SDLoc(CFP), MVT::i64); 14930 return DAG.getStore(Chain, DL, Tmp, 14931 Ptr, ST->getMemOperand()); 14932 } 14933 14934 if (!ST->isVolatile() && 14935 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 14936 // Many FP stores are not made apparent until after legalize, e.g. for 14937 // argument passing. Since this is so common, custom legalize the 14938 // 64-bit integer store into two 32-bit stores. 14939 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 14940 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 14941 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 14942 if (DAG.getDataLayout().isBigEndian()) 14943 std::swap(Lo, Hi); 14944 14945 unsigned Alignment = ST->getAlignment(); 14946 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 14947 AAMDNodes AAInfo = ST->getAAInfo(); 14948 14949 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 14950 ST->getAlignment(), MMOFlags, AAInfo); 14951 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 14952 DAG.getConstant(4, DL, Ptr.getValueType())); 14953 Alignment = MinAlign(Alignment, 4U); 14954 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 14955 ST->getPointerInfo().getWithOffset(4), 14956 Alignment, MMOFlags, AAInfo); 14957 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 14958 St0, St1); 14959 } 14960 14961 return SDValue(); 14962 } 14963 } 14964 14965 SDValue DAGCombiner::visitSTORE(SDNode *N) { 14966 StoreSDNode *ST = cast<StoreSDNode>(N); 14967 SDValue Chain = ST->getChain(); 14968 SDValue Value = ST->getValue(); 14969 SDValue Ptr = ST->getBasePtr(); 14970 14971 // If this is a store of a bit convert, store the input value if the 14972 // resultant store does not need a higher alignment than the original. 14973 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 14974 ST->isUnindexed()) { 14975 EVT SVT = Value.getOperand(0).getValueType(); 14976 // If the store is volatile, we only want to change the store type if the 14977 // resulting store is legal. Otherwise we might increase the number of 14978 // memory accesses. We don't care if the original type was legal or not 14979 // as we assume software couldn't rely on the number of accesses of an 14980 // illegal type. 14981 if (((!LegalOperations && !ST->isVolatile()) || 14982 TLI.isOperationLegal(ISD::STORE, SVT)) && 14983 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 14984 unsigned OrigAlign = ST->getAlignment(); 14985 bool Fast = false; 14986 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 14987 ST->getAddressSpace(), OrigAlign, &Fast) && 14988 Fast) { 14989 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 14990 ST->getPointerInfo(), OrigAlign, 14991 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 14992 } 14993 } 14994 } 14995 14996 // Turn 'store undef, Ptr' -> nothing. 14997 if (Value.isUndef() && ST->isUnindexed()) 14998 return Chain; 14999 15000 // Try to infer better alignment information than the store already has. 15001 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 15002 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 15003 if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) { 15004 SDValue NewStore = 15005 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 15006 ST->getMemoryVT(), Align, 15007 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 15008 // NewStore will always be N as we are only refining the alignment 15009 assert(NewStore.getNode() == N); 15010 (void)NewStore; 15011 } 15012 } 15013 } 15014 15015 // Try transforming a pair floating point load / store ops to integer 15016 // load / store ops. 15017 if (SDValue NewST = TransformFPLoadStorePair(N)) 15018 return NewST; 15019 15020 if (ST->isUnindexed()) { 15021 // Walk up chain skipping non-aliasing memory nodes, on this store and any 15022 // adjacent stores. 15023 if (findBetterNeighborChains(ST)) { 15024 // replaceStoreChain uses CombineTo, which handled all of the worklist 15025 // manipulation. Return the original node to not do anything else. 15026 return SDValue(ST, 0); 15027 } 15028 Chain = ST->getChain(); 15029 } 15030 15031 // FIXME: is there such a thing as a truncating indexed store? 15032 if (ST->isTruncatingStore() && ST->isUnindexed() && 15033 Value.getValueType().isInteger() && 15034 (!isa<ConstantSDNode>(Value) || 15035 !cast<ConstantSDNode>(Value)->isOpaque())) { 15036 // See if we can simplify the input to this truncstore with knowledge that 15037 // only the low bits are being used. For example: 15038 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 15039 SDValue Shorter = DAG.GetDemandedBits( 15040 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 15041 ST->getMemoryVT().getScalarSizeInBits())); 15042 AddToWorklist(Value.getNode()); 15043 if (Shorter.getNode()) 15044 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 15045 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 15046 15047 // Otherwise, see if we can simplify the operation with 15048 // SimplifyDemandedBits, which only works if the value has a single use. 15049 if (SimplifyDemandedBits( 15050 Value, 15051 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 15052 ST->getMemoryVT().getScalarSizeInBits()))) { 15053 // Re-visit the store if anything changed and the store hasn't been merged 15054 // with another node (N is deleted) SimplifyDemandedBits will add Value's 15055 // node back to the worklist if necessary, but we also need to re-visit 15056 // the Store node itself. 15057 if (N->getOpcode() != ISD::DELETED_NODE) 15058 AddToWorklist(N); 15059 return SDValue(N, 0); 15060 } 15061 } 15062 15063 // If this is a load followed by a store to the same location, then the store 15064 // is dead/noop. 15065 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 15066 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 15067 ST->isUnindexed() && !ST->isVolatile() && 15068 // There can't be any side effects between the load and store, such as 15069 // a call or store. 15070 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 15071 // The store is dead, remove it. 15072 return Chain; 15073 } 15074 } 15075 15076 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 15077 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 15078 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 15079 ST->getMemoryVT() == ST1->getMemoryVT()) { 15080 // If this is a store followed by a store with the same value to the same 15081 // location, then the store is dead/noop. 15082 if (ST1->getValue() == Value) { 15083 // The store is dead, remove it. 15084 return Chain; 15085 } 15086 15087 // If this is a store who's preceeding store to the same location 15088 // and no one other node is chained to that store we can effectively 15089 // drop the store. Do not remove stores to undef as they may be used as 15090 // data sinks. 15091 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 15092 !ST1->getBasePtr().isUndef()) { 15093 // ST1 is fully overwritten and can be elided. Combine with it's chain 15094 // value. 15095 CombineTo(ST1, ST1->getChain()); 15096 return SDValue(); 15097 } 15098 } 15099 } 15100 15101 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 15102 // truncating store. We can do this even if this is already a truncstore. 15103 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 15104 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 15105 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 15106 ST->getMemoryVT())) { 15107 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 15108 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 15109 } 15110 15111 // Always perform this optimization before types are legal. If the target 15112 // prefers, also try this after legalization to catch stores that were created 15113 // by intrinsics or other nodes. 15114 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 15115 while (true) { 15116 // There can be multiple store sequences on the same chain. 15117 // Keep trying to merge store sequences until we are unable to do so 15118 // or until we merge the last store on the chain. 15119 bool Changed = MergeConsecutiveStores(ST); 15120 if (!Changed) break; 15121 // Return N as merge only uses CombineTo and no worklist clean 15122 // up is necessary. 15123 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 15124 return SDValue(N, 0); 15125 } 15126 } 15127 15128 // Try transforming N to an indexed store. 15129 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 15130 return SDValue(N, 0); 15131 15132 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 15133 // 15134 // Make sure to do this only after attempting to merge stores in order to 15135 // avoid changing the types of some subset of stores due to visit order, 15136 // preventing their merging. 15137 if (isa<ConstantFPSDNode>(ST->getValue())) { 15138 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 15139 return NewSt; 15140 } 15141 15142 if (SDValue NewSt = splitMergedValStore(ST)) 15143 return NewSt; 15144 15145 return ReduceLoadOpStoreWidth(N); 15146 } 15147 15148 /// For the instruction sequence of store below, F and I values 15149 /// are bundled together as an i64 value before being stored into memory. 15150 /// Sometimes it is more efficent to generate separate stores for F and I, 15151 /// which can remove the bitwise instructions or sink them to colder places. 15152 /// 15153 /// (store (or (zext (bitcast F to i32) to i64), 15154 /// (shl (zext I to i64), 32)), addr) --> 15155 /// (store F, addr) and (store I, addr+4) 15156 /// 15157 /// Similarly, splitting for other merged store can also be beneficial, like: 15158 /// For pair of {i32, i32}, i64 store --> two i32 stores. 15159 /// For pair of {i32, i16}, i64 store --> two i32 stores. 15160 /// For pair of {i16, i16}, i32 store --> two i16 stores. 15161 /// For pair of {i16, i8}, i32 store --> two i16 stores. 15162 /// For pair of {i8, i8}, i16 store --> two i8 stores. 15163 /// 15164 /// We allow each target to determine specifically which kind of splitting is 15165 /// supported. 15166 /// 15167 /// The store patterns are commonly seen from the simple code snippet below 15168 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 15169 /// void goo(const std::pair<int, float> &); 15170 /// hoo() { 15171 /// ... 15172 /// goo(std::make_pair(tmp, ftmp)); 15173 /// ... 15174 /// } 15175 /// 15176 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 15177 if (OptLevel == CodeGenOpt::None) 15178 return SDValue(); 15179 15180 SDValue Val = ST->getValue(); 15181 SDLoc DL(ST); 15182 15183 // Match OR operand. 15184 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 15185 return SDValue(); 15186 15187 // Match SHL operand and get Lower and Higher parts of Val. 15188 SDValue Op1 = Val.getOperand(0); 15189 SDValue Op2 = Val.getOperand(1); 15190 SDValue Lo, Hi; 15191 if (Op1.getOpcode() != ISD::SHL) { 15192 std::swap(Op1, Op2); 15193 if (Op1.getOpcode() != ISD::SHL) 15194 return SDValue(); 15195 } 15196 Lo = Op2; 15197 Hi = Op1.getOperand(0); 15198 if (!Op1.hasOneUse()) 15199 return SDValue(); 15200 15201 // Match shift amount to HalfValBitSize. 15202 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 15203 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 15204 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 15205 return SDValue(); 15206 15207 // Lo and Hi are zero-extended from int with size less equal than 32 15208 // to i64. 15209 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 15210 !Lo.getOperand(0).getValueType().isScalarInteger() || 15211 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 15212 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 15213 !Hi.getOperand(0).getValueType().isScalarInteger() || 15214 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 15215 return SDValue(); 15216 15217 // Use the EVT of low and high parts before bitcast as the input 15218 // of target query. 15219 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 15220 ? Lo.getOperand(0).getValueType() 15221 : Lo.getValueType(); 15222 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 15223 ? Hi.getOperand(0).getValueType() 15224 : Hi.getValueType(); 15225 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 15226 return SDValue(); 15227 15228 // Start to split store. 15229 unsigned Alignment = ST->getAlignment(); 15230 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 15231 AAMDNodes AAInfo = ST->getAAInfo(); 15232 15233 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 15234 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 15235 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 15236 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 15237 15238 SDValue Chain = ST->getChain(); 15239 SDValue Ptr = ST->getBasePtr(); 15240 // Lower value store. 15241 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 15242 ST->getAlignment(), MMOFlags, AAInfo); 15243 Ptr = 15244 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 15245 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 15246 // Higher value store. 15247 SDValue St1 = 15248 DAG.getStore(St0, DL, Hi, Ptr, 15249 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 15250 Alignment / 2, MMOFlags, AAInfo); 15251 return St1; 15252 } 15253 15254 /// Convert a disguised subvector insertion into a shuffle: 15255 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 15256 /// bitcast(shuffle (bitcast V), (extended X), Mask) 15257 /// Note: We do not use an insert_subvector node because that requires a legal 15258 /// subvector type. 15259 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 15260 SDValue InsertVal = N->getOperand(1); 15261 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 15262 !InsertVal.getOperand(0).getValueType().isVector()) 15263 return SDValue(); 15264 15265 SDValue SubVec = InsertVal.getOperand(0); 15266 SDValue DestVec = N->getOperand(0); 15267 EVT SubVecVT = SubVec.getValueType(); 15268 EVT VT = DestVec.getValueType(); 15269 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 15270 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 15271 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 15272 15273 // Step 1: Create a shuffle mask that implements this insert operation. The 15274 // vector that we are inserting into will be operand 0 of the shuffle, so 15275 // those elements are just 'i'. The inserted subvector is in the first 15276 // positions of operand 1 of the shuffle. Example: 15277 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 15278 SmallVector<int, 16> Mask(NumMaskVals); 15279 for (unsigned i = 0; i != NumMaskVals; ++i) { 15280 if (i / NumSrcElts == InsIndex) 15281 Mask[i] = (i % NumSrcElts) + NumMaskVals; 15282 else 15283 Mask[i] = i; 15284 } 15285 15286 // Bail out if the target can not handle the shuffle we want to create. 15287 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 15288 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 15289 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 15290 return SDValue(); 15291 15292 // Step 2: Create a wide vector from the inserted source vector by appending 15293 // undefined elements. This is the same size as our destination vector. 15294 SDLoc DL(N); 15295 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 15296 ConcatOps[0] = SubVec; 15297 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 15298 15299 // Step 3: Shuffle in the padded subvector. 15300 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 15301 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 15302 AddToWorklist(PaddedSubV.getNode()); 15303 AddToWorklist(DestVecBC.getNode()); 15304 AddToWorklist(Shuf.getNode()); 15305 return DAG.getBitcast(VT, Shuf); 15306 } 15307 15308 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 15309 SDValue InVec = N->getOperand(0); 15310 SDValue InVal = N->getOperand(1); 15311 SDValue EltNo = N->getOperand(2); 15312 SDLoc DL(N); 15313 15314 // If the inserted element is an UNDEF, just use the input vector. 15315 if (InVal.isUndef()) 15316 return InVec; 15317 15318 EVT VT = InVec.getValueType(); 15319 15320 // Remove redundant insertions: 15321 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 15322 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15323 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 15324 return InVec; 15325 15326 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 15327 if (!IndexC) { 15328 // If this is variable insert to undef vector, it might be better to splat: 15329 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > 15330 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { 15331 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal); 15332 return DAG.getBuildVector(VT, DL, Ops); 15333 } 15334 return SDValue(); 15335 } 15336 15337 // We must know which element is being inserted for folds below here. 15338 unsigned Elt = IndexC->getZExtValue(); 15339 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 15340 return Shuf; 15341 15342 // Canonicalize insert_vector_elt dag nodes. 15343 // Example: 15344 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 15345 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 15346 // 15347 // Do this only if the child insert_vector node has one use; also 15348 // do this only if indices are both constants and Idx1 < Idx0. 15349 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 15350 && isa<ConstantSDNode>(InVec.getOperand(2))) { 15351 unsigned OtherElt = InVec.getConstantOperandVal(2); 15352 if (Elt < OtherElt) { 15353 // Swap nodes. 15354 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 15355 InVec.getOperand(0), InVal, EltNo); 15356 AddToWorklist(NewOp.getNode()); 15357 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 15358 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 15359 } 15360 } 15361 15362 // If we can't generate a legal BUILD_VECTOR, exit 15363 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 15364 return SDValue(); 15365 15366 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 15367 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 15368 // vector elements. 15369 SmallVector<SDValue, 8> Ops; 15370 // Do not combine these two vectors if the output vector will not replace 15371 // the input vector. 15372 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 15373 Ops.append(InVec.getNode()->op_begin(), 15374 InVec.getNode()->op_end()); 15375 } else if (InVec.isUndef()) { 15376 unsigned NElts = VT.getVectorNumElements(); 15377 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 15378 } else { 15379 return SDValue(); 15380 } 15381 15382 // Insert the element 15383 if (Elt < Ops.size()) { 15384 // All the operands of BUILD_VECTOR must have the same type; 15385 // we enforce that here. 15386 EVT OpVT = Ops[0].getValueType(); 15387 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 15388 } 15389 15390 // Return the new vector 15391 return DAG.getBuildVector(VT, DL, Ops); 15392 } 15393 15394 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 15395 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 15396 assert(!OriginalLoad->isVolatile()); 15397 15398 EVT ResultVT = EVE->getValueType(0); 15399 EVT VecEltVT = InVecVT.getVectorElementType(); 15400 unsigned Align = OriginalLoad->getAlignment(); 15401 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 15402 VecEltVT.getTypeForEVT(*DAG.getContext())); 15403 15404 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 15405 return SDValue(); 15406 15407 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 15408 ISD::NON_EXTLOAD : ISD::EXTLOAD; 15409 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 15410 return SDValue(); 15411 15412 Align = NewAlign; 15413 15414 SDValue NewPtr = OriginalLoad->getBasePtr(); 15415 SDValue Offset; 15416 EVT PtrType = NewPtr.getValueType(); 15417 MachinePointerInfo MPI; 15418 SDLoc DL(EVE); 15419 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 15420 int Elt = ConstEltNo->getZExtValue(); 15421 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 15422 Offset = DAG.getConstant(PtrOff, DL, PtrType); 15423 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 15424 } else { 15425 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 15426 Offset = DAG.getNode( 15427 ISD::MUL, DL, PtrType, Offset, 15428 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 15429 MPI = OriginalLoad->getPointerInfo(); 15430 } 15431 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 15432 15433 // The replacement we need to do here is a little tricky: we need to 15434 // replace an extractelement of a load with a load. 15435 // Use ReplaceAllUsesOfValuesWith to do the replacement. 15436 // Note that this replacement assumes that the extractvalue is the only 15437 // use of the load; that's okay because we don't want to perform this 15438 // transformation in other cases anyway. 15439 SDValue Load; 15440 SDValue Chain; 15441 if (ResultVT.bitsGT(VecEltVT)) { 15442 // If the result type of vextract is wider than the load, then issue an 15443 // extending load instead. 15444 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 15445 VecEltVT) 15446 ? ISD::ZEXTLOAD 15447 : ISD::EXTLOAD; 15448 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 15449 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 15450 Align, OriginalLoad->getMemOperand()->getFlags(), 15451 OriginalLoad->getAAInfo()); 15452 Chain = Load.getValue(1); 15453 } else { 15454 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 15455 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 15456 OriginalLoad->getAAInfo()); 15457 Chain = Load.getValue(1); 15458 if (ResultVT.bitsLT(VecEltVT)) 15459 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 15460 else 15461 Load = DAG.getBitcast(ResultVT, Load); 15462 } 15463 WorklistRemover DeadNodes(*this); 15464 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 15465 SDValue To[] = { Load, Chain }; 15466 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 15467 // Since we're explicitly calling ReplaceAllUses, add the new node to the 15468 // worklist explicitly as well. 15469 AddToWorklist(Load.getNode()); 15470 AddUsersToWorklist(Load.getNode()); // Add users too 15471 // Make sure to revisit this node to clean it up; it will usually be dead. 15472 AddToWorklist(EVE); 15473 ++OpsNarrowed; 15474 return SDValue(EVE, 0); 15475 } 15476 15477 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 15478 SDValue InVec = N->getOperand(0); 15479 EVT VT = InVec.getValueType(); 15480 EVT NVT = N->getValueType(0); 15481 if (InVec.isUndef()) 15482 return DAG.getUNDEF(NVT); 15483 15484 // (vextract (scalar_to_vector val, 0) -> val 15485 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15486 // Check if the result type doesn't match the inserted element type. A 15487 // SCALAR_TO_VECTOR may truncate the inserted element and the 15488 // EXTRACT_VECTOR_ELT may widen the extracted vector. 15489 SDValue InOp = InVec.getOperand(0); 15490 if (InOp.getValueType() != NVT) { 15491 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15492 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 15493 } 15494 return InOp; 15495 } 15496 15497 SDValue EltNo = N->getOperand(1); 15498 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 15499 15500 // extract_vector_elt of out-of-bounds element -> UNDEF 15501 if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements())) 15502 return DAG.getUNDEF(NVT); 15503 15504 // extract_vector_elt (build_vector x, y), 1 -> y 15505 if (ConstEltNo && 15506 InVec.getOpcode() == ISD::BUILD_VECTOR && 15507 TLI.isTypeLegal(VT) && 15508 (InVec.hasOneUse() || 15509 TLI.aggressivelyPreferBuildVectorSources(VT))) { 15510 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 15511 EVT InEltVT = Elt.getValueType(); 15512 15513 // Sometimes build_vector's scalar input types do not match result type. 15514 if (NVT == InEltVT) 15515 return Elt; 15516 15517 // TODO: It may be useful to truncate if free if the build_vector implicitly 15518 // converts. 15519 } 15520 15521 // TODO: These transforms should not require the 'hasOneUse' restriction, but 15522 // there are regressions on multiple targets without it. We can end up with a 15523 // mess of scalar and vector code if we reduce only part of the DAG to scalar. 15524 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && VT.isInteger() && 15525 InVec.hasOneUse()) { 15526 // The vector index of the LSBs of the source depend on the endian-ness. 15527 bool IsLE = DAG.getDataLayout().isLittleEndian(); 15528 unsigned ExtractIndex = ConstEltNo->getZExtValue(); 15529 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x) 15530 unsigned BCTruncElt = IsLE ? 0 : VT.getVectorNumElements() - 1; 15531 SDValue BCSrc = InVec.getOperand(0); 15532 if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger()) 15533 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 15534 15535 if (LegalTypes && BCSrc.getValueType().isInteger() && 15536 BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15537 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt --> 15538 // trunc i64 X to i32 15539 SDValue X = BCSrc.getOperand(0); 15540 assert(X.getValueType().isScalarInteger() && NVT.isScalarInteger() && 15541 "Extract element and scalar to vector can't change element type " 15542 "from FP to integer."); 15543 unsigned XBitWidth = X.getValueSizeInBits(); 15544 unsigned VecEltBitWidth = VT.getScalarSizeInBits(); 15545 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1; 15546 15547 // An extract element return value type can be wider than its vector 15548 // operand element type. In that case, the high bits are undefined, so 15549 // it's possible that we may need to extend rather than truncate. 15550 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) { 15551 assert(XBitWidth % VecEltBitWidth == 0 && 15552 "Scalar bitwidth must be a multiple of vector element bitwidth"); 15553 return DAG.getAnyExtOrTrunc(X, SDLoc(N), NVT); 15554 } 15555 } 15556 } 15557 15558 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 15559 // 15560 // This only really matters if the index is non-constant since other combines 15561 // on the constant elements already work. 15562 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 15563 EltNo == InVec.getOperand(2)) { 15564 SDValue Elt = InVec.getOperand(1); 15565 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 15566 } 15567 15568 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 15569 // We only perform this optimization before the op legalization phase because 15570 // we may introduce new vector instructions which are not backed by TD 15571 // patterns. For example on AVX, extracting elements from a wide vector 15572 // without using extract_subvector. However, if we can find an underlying 15573 // scalar value, then we can always use that. 15574 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 15575 int NumElem = VT.getVectorNumElements(); 15576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 15577 // Find the new index to extract from. 15578 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 15579 15580 // Extracting an undef index is undef. 15581 if (OrigElt == -1) 15582 return DAG.getUNDEF(NVT); 15583 15584 // Select the right vector half to extract from. 15585 SDValue SVInVec; 15586 if (OrigElt < NumElem) { 15587 SVInVec = InVec->getOperand(0); 15588 } else { 15589 SVInVec = InVec->getOperand(1); 15590 OrigElt -= NumElem; 15591 } 15592 15593 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 15594 SDValue InOp = SVInVec.getOperand(OrigElt); 15595 if (InOp.getValueType() != NVT) { 15596 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 15597 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 15598 } 15599 15600 return InOp; 15601 } 15602 15603 // FIXME: We should handle recursing on other vector shuffles and 15604 // scalar_to_vector here as well. 15605 15606 if (!LegalOperations || 15607 // FIXME: Should really be just isOperationLegalOrCustom. 15608 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 15609 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 15610 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15611 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 15612 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 15613 } 15614 } 15615 15616 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 15617 // simplify it based on the (valid) extraction indices. 15618 if (llvm::all_of(InVec->uses(), [&](SDNode *Use) { 15619 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15620 Use->getOperand(0) == InVec && 15621 isa<ConstantSDNode>(Use->getOperand(1)); 15622 })) { 15623 APInt DemandedElts = APInt::getNullValue(VT.getVectorNumElements()); 15624 for (SDNode *Use : InVec->uses()) { 15625 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 15626 if (CstElt->getAPIntValue().ult(VT.getVectorNumElements())) 15627 DemandedElts.setBit(CstElt->getZExtValue()); 15628 } 15629 if (SimplifyDemandedVectorElts(InVec, DemandedElts, true)) 15630 return SDValue(N, 0); 15631 } 15632 15633 bool BCNumEltsChanged = false; 15634 EVT ExtVT = VT.getVectorElementType(); 15635 EVT LVT = ExtVT; 15636 15637 // If the result of load has to be truncated, then it's not necessarily 15638 // profitable. 15639 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 15640 return SDValue(); 15641 15642 if (InVec.getOpcode() == ISD::BITCAST) { 15643 // Don't duplicate a load with other uses. 15644 if (!InVec.hasOneUse()) 15645 return SDValue(); 15646 15647 EVT BCVT = InVec.getOperand(0).getValueType(); 15648 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 15649 return SDValue(); 15650 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 15651 BCNumEltsChanged = true; 15652 InVec = InVec.getOperand(0); 15653 ExtVT = BCVT.getVectorElementType(); 15654 } 15655 15656 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 15657 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 15658 ISD::isNormalLoad(InVec.getNode()) && 15659 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 15660 SDValue Index = N->getOperand(1); 15661 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 15662 if (!OrigLoad->isVolatile()) { 15663 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 15664 OrigLoad); 15665 } 15666 } 15667 } 15668 15669 // Perform only after legalization to ensure build_vector / vector_shuffle 15670 // optimizations have already been done. 15671 if (!LegalOperations) return SDValue(); 15672 15673 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 15674 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 15675 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 15676 15677 if (ConstEltNo) { 15678 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 15679 15680 LoadSDNode *LN0 = nullptr; 15681 const ShuffleVectorSDNode *SVN = nullptr; 15682 if (ISD::isNormalLoad(InVec.getNode())) { 15683 LN0 = cast<LoadSDNode>(InVec); 15684 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 15685 InVec.getOperand(0).getValueType() == ExtVT && 15686 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 15687 // Don't duplicate a load with other uses. 15688 if (!InVec.hasOneUse()) 15689 return SDValue(); 15690 15691 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 15692 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 15693 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 15694 // => 15695 // (load $addr+1*size) 15696 15697 // Don't duplicate a load with other uses. 15698 if (!InVec.hasOneUse()) 15699 return SDValue(); 15700 15701 // If the bit convert changed the number of elements, it is unsafe 15702 // to examine the mask. 15703 if (BCNumEltsChanged) 15704 return SDValue(); 15705 15706 // Select the input vector, guarding against out of range extract vector. 15707 unsigned NumElems = VT.getVectorNumElements(); 15708 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 15709 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 15710 15711 if (InVec.getOpcode() == ISD::BITCAST) { 15712 // Don't duplicate a load with other uses. 15713 if (!InVec.hasOneUse()) 15714 return SDValue(); 15715 15716 InVec = InVec.getOperand(0); 15717 } 15718 if (ISD::isNormalLoad(InVec.getNode())) { 15719 LN0 = cast<LoadSDNode>(InVec); 15720 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 15721 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 15722 } 15723 } 15724 15725 // Make sure we found a non-volatile load and the extractelement is 15726 // the only use. 15727 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 15728 return SDValue(); 15729 15730 // If Idx was -1 above, Elt is going to be -1, so just return undef. 15731 if (Elt == -1) 15732 return DAG.getUNDEF(LVT); 15733 15734 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 15735 } 15736 15737 return SDValue(); 15738 } 15739 15740 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 15741 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 15742 // We perform this optimization post type-legalization because 15743 // the type-legalizer often scalarizes integer-promoted vectors. 15744 // Performing this optimization before may create bit-casts which 15745 // will be type-legalized to complex code sequences. 15746 // We perform this optimization only before the operation legalizer because we 15747 // may introduce illegal operations. 15748 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 15749 return SDValue(); 15750 15751 unsigned NumInScalars = N->getNumOperands(); 15752 SDLoc DL(N); 15753 EVT VT = N->getValueType(0); 15754 15755 // Check to see if this is a BUILD_VECTOR of a bunch of values 15756 // which come from any_extend or zero_extend nodes. If so, we can create 15757 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 15758 // optimizations. We do not handle sign-extend because we can't fill the sign 15759 // using shuffles. 15760 EVT SourceType = MVT::Other; 15761 bool AllAnyExt = true; 15762 15763 for (unsigned i = 0; i != NumInScalars; ++i) { 15764 SDValue In = N->getOperand(i); 15765 // Ignore undef inputs. 15766 if (In.isUndef()) continue; 15767 15768 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 15769 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 15770 15771 // Abort if the element is not an extension. 15772 if (!ZeroExt && !AnyExt) { 15773 SourceType = MVT::Other; 15774 break; 15775 } 15776 15777 // The input is a ZeroExt or AnyExt. Check the original type. 15778 EVT InTy = In.getOperand(0).getValueType(); 15779 15780 // Check that all of the widened source types are the same. 15781 if (SourceType == MVT::Other) 15782 // First time. 15783 SourceType = InTy; 15784 else if (InTy != SourceType) { 15785 // Multiple income types. Abort. 15786 SourceType = MVT::Other; 15787 break; 15788 } 15789 15790 // Check if all of the extends are ANY_EXTENDs. 15791 AllAnyExt &= AnyExt; 15792 } 15793 15794 // In order to have valid types, all of the inputs must be extended from the 15795 // same source type and all of the inputs must be any or zero extend. 15796 // Scalar sizes must be a power of two. 15797 EVT OutScalarTy = VT.getScalarType(); 15798 bool ValidTypes = SourceType != MVT::Other && 15799 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 15800 isPowerOf2_32(SourceType.getSizeInBits()); 15801 15802 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 15803 // turn into a single shuffle instruction. 15804 if (!ValidTypes) 15805 return SDValue(); 15806 15807 bool isLE = DAG.getDataLayout().isLittleEndian(); 15808 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 15809 assert(ElemRatio > 1 && "Invalid element size ratio"); 15810 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 15811 DAG.getConstant(0, DL, SourceType); 15812 15813 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 15814 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 15815 15816 // Populate the new build_vector 15817 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15818 SDValue Cast = N->getOperand(i); 15819 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 15820 Cast.getOpcode() == ISD::ZERO_EXTEND || 15821 Cast.isUndef()) && "Invalid cast opcode"); 15822 SDValue In; 15823 if (Cast.isUndef()) 15824 In = DAG.getUNDEF(SourceType); 15825 else 15826 In = Cast->getOperand(0); 15827 unsigned Index = isLE ? (i * ElemRatio) : 15828 (i * ElemRatio + (ElemRatio - 1)); 15829 15830 assert(Index < Ops.size() && "Invalid index"); 15831 Ops[Index] = In; 15832 } 15833 15834 // The type of the new BUILD_VECTOR node. 15835 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 15836 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 15837 "Invalid vector size"); 15838 // Check if the new vector type is legal. 15839 if (!isTypeLegal(VecVT) || 15840 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 15841 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 15842 return SDValue(); 15843 15844 // Make the new BUILD_VECTOR. 15845 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 15846 15847 // The new BUILD_VECTOR node has the potential to be further optimized. 15848 AddToWorklist(BV.getNode()); 15849 // Bitcast to the desired type. 15850 return DAG.getBitcast(VT, BV); 15851 } 15852 15853 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 15854 EVT VT = N->getValueType(0); 15855 15856 unsigned NumInScalars = N->getNumOperands(); 15857 SDLoc DL(N); 15858 15859 EVT SrcVT = MVT::Other; 15860 unsigned Opcode = ISD::DELETED_NODE; 15861 unsigned NumDefs = 0; 15862 15863 for (unsigned i = 0; i != NumInScalars; ++i) { 15864 SDValue In = N->getOperand(i); 15865 unsigned Opc = In.getOpcode(); 15866 15867 if (Opc == ISD::UNDEF) 15868 continue; 15869 15870 // If all scalar values are floats and converted from integers. 15871 if (Opcode == ISD::DELETED_NODE && 15872 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 15873 Opcode = Opc; 15874 } 15875 15876 if (Opc != Opcode) 15877 return SDValue(); 15878 15879 EVT InVT = In.getOperand(0).getValueType(); 15880 15881 // If all scalar values are typed differently, bail out. It's chosen to 15882 // simplify BUILD_VECTOR of integer types. 15883 if (SrcVT == MVT::Other) 15884 SrcVT = InVT; 15885 if (SrcVT != InVT) 15886 return SDValue(); 15887 NumDefs++; 15888 } 15889 15890 // If the vector has just one element defined, it's not worth to fold it into 15891 // a vectorized one. 15892 if (NumDefs < 2) 15893 return SDValue(); 15894 15895 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 15896 && "Should only handle conversion from integer to float."); 15897 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 15898 15899 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 15900 15901 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 15902 return SDValue(); 15903 15904 // Just because the floating-point vector type is legal does not necessarily 15905 // mean that the corresponding integer vector type is. 15906 if (!isTypeLegal(NVT)) 15907 return SDValue(); 15908 15909 SmallVector<SDValue, 8> Opnds; 15910 for (unsigned i = 0; i != NumInScalars; ++i) { 15911 SDValue In = N->getOperand(i); 15912 15913 if (In.isUndef()) 15914 Opnds.push_back(DAG.getUNDEF(SrcVT)); 15915 else 15916 Opnds.push_back(In.getOperand(0)); 15917 } 15918 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 15919 AddToWorklist(BV.getNode()); 15920 15921 return DAG.getNode(Opcode, DL, VT, BV); 15922 } 15923 15924 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 15925 ArrayRef<int> VectorMask, 15926 SDValue VecIn1, SDValue VecIn2, 15927 unsigned LeftIdx) { 15928 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 15929 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 15930 15931 EVT VT = N->getValueType(0); 15932 EVT InVT1 = VecIn1.getValueType(); 15933 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 15934 15935 unsigned Vec2Offset = 0; 15936 unsigned NumElems = VT.getVectorNumElements(); 15937 unsigned ShuffleNumElems = NumElems; 15938 15939 // In case both the input vectors are extracted from same base 15940 // vector we do not need extra addend (Vec2Offset) while 15941 // computing shuffle mask. 15942 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15943 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 15944 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 15945 Vec2Offset = InVT1.getVectorNumElements(); 15946 15947 // We can't generate a shuffle node with mismatched input and output types. 15948 // Try to make the types match the type of the output. 15949 if (InVT1 != VT || InVT2 != VT) { 15950 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 15951 // If the output vector length is a multiple of both input lengths, 15952 // we can concatenate them and pad the rest with undefs. 15953 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 15954 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 15955 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 15956 ConcatOps[0] = VecIn1; 15957 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 15958 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 15959 VecIn2 = SDValue(); 15960 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 15961 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 15962 return SDValue(); 15963 15964 if (!VecIn2.getNode()) { 15965 // If we only have one input vector, and it's twice the size of the 15966 // output, split it in two. 15967 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 15968 DAG.getConstant(NumElems, DL, IdxTy)); 15969 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 15970 // Since we now have shorter input vectors, adjust the offset of the 15971 // second vector's start. 15972 Vec2Offset = NumElems; 15973 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 15974 // VecIn1 is wider than the output, and we have another, possibly 15975 // smaller input. Pad the smaller input with undefs, shuffle at the 15976 // input vector width, and extract the output. 15977 // The shuffle type is different than VT, so check legality again. 15978 if (LegalOperations && 15979 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 15980 return SDValue(); 15981 15982 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 15983 // lower it back into a BUILD_VECTOR. So if the inserted type is 15984 // illegal, don't even try. 15985 if (InVT1 != InVT2) { 15986 if (!TLI.isTypeLegal(InVT2)) 15987 return SDValue(); 15988 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 15989 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 15990 } 15991 ShuffleNumElems = NumElems * 2; 15992 } else { 15993 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 15994 // than VecIn1. We can't handle this for now - this case will disappear 15995 // when we start sorting the vectors by type. 15996 return SDValue(); 15997 } 15998 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 15999 InVT1.getSizeInBits() == VT.getSizeInBits()) { 16000 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 16001 ConcatOps[0] = VecIn2; 16002 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 16003 } else { 16004 // TODO: Support cases where the length mismatch isn't exactly by a 16005 // factor of 2. 16006 // TODO: Move this check upwards, so that if we have bad type 16007 // mismatches, we don't create any DAG nodes. 16008 return SDValue(); 16009 } 16010 } 16011 16012 // Initialize mask to undef. 16013 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 16014 16015 // Only need to run up to the number of elements actually used, not the 16016 // total number of elements in the shuffle - if we are shuffling a wider 16017 // vector, the high lanes should be set to undef. 16018 for (unsigned i = 0; i != NumElems; ++i) { 16019 if (VectorMask[i] <= 0) 16020 continue; 16021 16022 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 16023 if (VectorMask[i] == (int)LeftIdx) { 16024 Mask[i] = ExtIndex; 16025 } else if (VectorMask[i] == (int)LeftIdx + 1) { 16026 Mask[i] = Vec2Offset + ExtIndex; 16027 } 16028 } 16029 16030 // The type the input vectors may have changed above. 16031 InVT1 = VecIn1.getValueType(); 16032 16033 // If we already have a VecIn2, it should have the same type as VecIn1. 16034 // If we don't, get an undef/zero vector of the appropriate type. 16035 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 16036 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 16037 16038 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 16039 if (ShuffleNumElems > NumElems) 16040 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 16041 16042 return Shuffle; 16043 } 16044 16045 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 16046 // operations. If the types of the vectors we're extracting from allow it, 16047 // turn this into a vector_shuffle node. 16048 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 16049 SDLoc DL(N); 16050 EVT VT = N->getValueType(0); 16051 16052 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 16053 if (!isTypeLegal(VT)) 16054 return SDValue(); 16055 16056 // May only combine to shuffle after legalize if shuffle is legal. 16057 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 16058 return SDValue(); 16059 16060 bool UsesZeroVector = false; 16061 unsigned NumElems = N->getNumOperands(); 16062 16063 // Record, for each element of the newly built vector, which input vector 16064 // that element comes from. -1 stands for undef, 0 for the zero vector, 16065 // and positive values for the input vectors. 16066 // VectorMask maps each element to its vector number, and VecIn maps vector 16067 // numbers to their initial SDValues. 16068 16069 SmallVector<int, 8> VectorMask(NumElems, -1); 16070 SmallVector<SDValue, 8> VecIn; 16071 VecIn.push_back(SDValue()); 16072 16073 for (unsigned i = 0; i != NumElems; ++i) { 16074 SDValue Op = N->getOperand(i); 16075 16076 if (Op.isUndef()) 16077 continue; 16078 16079 // See if we can use a blend with a zero vector. 16080 // TODO: Should we generalize this to a blend with an arbitrary constant 16081 // vector? 16082 if (isNullConstant(Op) || isNullFPConstant(Op)) { 16083 UsesZeroVector = true; 16084 VectorMask[i] = 0; 16085 continue; 16086 } 16087 16088 // Not an undef or zero. If the input is something other than an 16089 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 16090 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 16091 !isa<ConstantSDNode>(Op.getOperand(1))) 16092 return SDValue(); 16093 SDValue ExtractedFromVec = Op.getOperand(0); 16094 16095 APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue(); 16096 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 16097 return SDValue(); 16098 16099 // All inputs must have the same element type as the output. 16100 if (VT.getVectorElementType() != 16101 ExtractedFromVec.getValueType().getVectorElementType()) 16102 return SDValue(); 16103 16104 // Have we seen this input vector before? 16105 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 16106 // a map back from SDValues to numbers isn't worth it. 16107 unsigned Idx = std::distance( 16108 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 16109 if (Idx == VecIn.size()) 16110 VecIn.push_back(ExtractedFromVec); 16111 16112 VectorMask[i] = Idx; 16113 } 16114 16115 // If we didn't find at least one input vector, bail out. 16116 if (VecIn.size() < 2) 16117 return SDValue(); 16118 16119 // If all the Operands of BUILD_VECTOR extract from same 16120 // vector, then split the vector efficiently based on the maximum 16121 // vector access index and adjust the VectorMask and 16122 // VecIn accordingly. 16123 if (VecIn.size() == 2) { 16124 unsigned MaxIndex = 0; 16125 unsigned NearestPow2 = 0; 16126 SDValue Vec = VecIn.back(); 16127 EVT InVT = Vec.getValueType(); 16128 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16129 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 16130 16131 for (unsigned i = 0; i < NumElems; i++) { 16132 if (VectorMask[i] <= 0) 16133 continue; 16134 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 16135 IndexVec[i] = Index; 16136 MaxIndex = std::max(MaxIndex, Index); 16137 } 16138 16139 NearestPow2 = PowerOf2Ceil(MaxIndex); 16140 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 16141 NumElems * 2 < NearestPow2) { 16142 unsigned SplitSize = NearestPow2 / 2; 16143 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 16144 InVT.getVectorElementType(), SplitSize); 16145 if (TLI.isTypeLegal(SplitVT)) { 16146 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 16147 DAG.getConstant(SplitSize, DL, IdxTy)); 16148 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 16149 DAG.getConstant(0, DL, IdxTy)); 16150 VecIn.pop_back(); 16151 VecIn.push_back(VecIn1); 16152 VecIn.push_back(VecIn2); 16153 16154 for (unsigned i = 0; i < NumElems; i++) { 16155 if (VectorMask[i] <= 0) 16156 continue; 16157 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 16158 } 16159 } 16160 } 16161 } 16162 16163 // TODO: We want to sort the vectors by descending length, so that adjacent 16164 // pairs have similar length, and the longer vector is always first in the 16165 // pair. 16166 16167 // TODO: Should this fire if some of the input vectors has illegal type (like 16168 // it does now), or should we let legalization run its course first? 16169 16170 // Shuffle phase: 16171 // Take pairs of vectors, and shuffle them so that the result has elements 16172 // from these vectors in the correct places. 16173 // For example, given: 16174 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 16175 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 16176 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 16177 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 16178 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 16179 // We will generate: 16180 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 16181 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 16182 SmallVector<SDValue, 4> Shuffles; 16183 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 16184 unsigned LeftIdx = 2 * In + 1; 16185 SDValue VecLeft = VecIn[LeftIdx]; 16186 SDValue VecRight = 16187 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 16188 16189 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 16190 VecRight, LeftIdx)) 16191 Shuffles.push_back(Shuffle); 16192 else 16193 return SDValue(); 16194 } 16195 16196 // If we need the zero vector as an "ingredient" in the blend tree, add it 16197 // to the list of shuffles. 16198 if (UsesZeroVector) 16199 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 16200 : DAG.getConstantFP(0.0, DL, VT)); 16201 16202 // If we only have one shuffle, we're done. 16203 if (Shuffles.size() == 1) 16204 return Shuffles[0]; 16205 16206 // Update the vector mask to point to the post-shuffle vectors. 16207 for (int &Vec : VectorMask) 16208 if (Vec == 0) 16209 Vec = Shuffles.size() - 1; 16210 else 16211 Vec = (Vec - 1) / 2; 16212 16213 // More than one shuffle. Generate a binary tree of blends, e.g. if from 16214 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 16215 // generate: 16216 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 16217 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 16218 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 16219 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 16220 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 16221 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 16222 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 16223 16224 // Make sure the initial size of the shuffle list is even. 16225 if (Shuffles.size() % 2) 16226 Shuffles.push_back(DAG.getUNDEF(VT)); 16227 16228 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 16229 if (CurSize % 2) { 16230 Shuffles[CurSize] = DAG.getUNDEF(VT); 16231 CurSize++; 16232 } 16233 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 16234 int Left = 2 * In; 16235 int Right = 2 * In + 1; 16236 SmallVector<int, 8> Mask(NumElems, -1); 16237 for (unsigned i = 0; i != NumElems; ++i) { 16238 if (VectorMask[i] == Left) { 16239 Mask[i] = i; 16240 VectorMask[i] = In; 16241 } else if (VectorMask[i] == Right) { 16242 Mask[i] = i + NumElems; 16243 VectorMask[i] = In; 16244 } 16245 } 16246 16247 Shuffles[In] = 16248 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 16249 } 16250 } 16251 return Shuffles[0]; 16252 } 16253 16254 // Try to turn a build vector of zero extends of extract vector elts into a 16255 // a vector zero extend and possibly an extract subvector. 16256 // TODO: Support sign extend or any extend? 16257 // TODO: Allow undef elements? 16258 // TODO: Don't require the extracts to start at element 0. 16259 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 16260 if (LegalOperations) 16261 return SDValue(); 16262 16263 EVT VT = N->getValueType(0); 16264 16265 SDValue Op0 = N->getOperand(0); 16266 auto checkElem = [&](SDValue Op) -> int64_t { 16267 if (Op.getOpcode() == ISD::ZERO_EXTEND && 16268 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 16269 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 16270 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 16271 return C->getZExtValue(); 16272 return -1; 16273 }; 16274 16275 // Make sure the first element matches 16276 // (zext (extract_vector_elt X, C)) 16277 int64_t Offset = checkElem(Op0); 16278 if (Offset < 0) 16279 return SDValue(); 16280 16281 unsigned NumElems = N->getNumOperands(); 16282 SDValue In = Op0.getOperand(0).getOperand(0); 16283 EVT InSVT = In.getValueType().getScalarType(); 16284 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 16285 16286 // Don't create an illegal input type after type legalization. 16287 if (LegalTypes && !TLI.isTypeLegal(InVT)) 16288 return SDValue(); 16289 16290 // Ensure all the elements come from the same vector and are adjacent. 16291 for (unsigned i = 1; i != NumElems; ++i) { 16292 if ((Offset + i) != checkElem(N->getOperand(i))) 16293 return SDValue(); 16294 } 16295 16296 SDLoc DL(N); 16297 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 16298 Op0.getOperand(0).getOperand(1)); 16299 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In); 16300 } 16301 16302 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 16303 EVT VT = N->getValueType(0); 16304 16305 // A vector built entirely of undefs is undef. 16306 if (ISD::allOperandsUndef(N)) 16307 return DAG.getUNDEF(VT); 16308 16309 // If this is a splat of a bitcast from another vector, change to a 16310 // concat_vector. 16311 // For example: 16312 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 16313 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 16314 // 16315 // If X is a build_vector itself, the concat can become a larger build_vector. 16316 // TODO: Maybe this is useful for non-splat too? 16317 if (!LegalOperations) { 16318 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 16319 Splat = peekThroughBitcasts(Splat); 16320 EVT SrcVT = Splat.getValueType(); 16321 if (SrcVT.isVector()) { 16322 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 16323 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 16324 SrcVT.getVectorElementType(), NumElts); 16325 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 16326 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 16327 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 16328 NewVT, Ops); 16329 return DAG.getBitcast(VT, Concat); 16330 } 16331 } 16332 } 16333 } 16334 16335 // Check if we can express BUILD VECTOR via subvector extract. 16336 if (!LegalTypes && (N->getNumOperands() > 1)) { 16337 SDValue Op0 = N->getOperand(0); 16338 auto checkElem = [&](SDValue Op) -> uint64_t { 16339 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 16340 (Op0.getOperand(0) == Op.getOperand(0))) 16341 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 16342 return CNode->getZExtValue(); 16343 return -1; 16344 }; 16345 16346 int Offset = checkElem(Op0); 16347 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 16348 if (Offset + i != checkElem(N->getOperand(i))) { 16349 Offset = -1; 16350 break; 16351 } 16352 } 16353 16354 if ((Offset == 0) && 16355 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 16356 return Op0.getOperand(0); 16357 if ((Offset != -1) && 16358 ((Offset % N->getValueType(0).getVectorNumElements()) == 16359 0)) // IDX must be multiple of output size. 16360 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 16361 Op0.getOperand(0), Op0.getOperand(1)); 16362 } 16363 16364 if (SDValue V = convertBuildVecZextToZext(N)) 16365 return V; 16366 16367 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 16368 return V; 16369 16370 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 16371 return V; 16372 16373 if (SDValue V = reduceBuildVecToShuffle(N)) 16374 return V; 16375 16376 return SDValue(); 16377 } 16378 16379 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 16380 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16381 EVT OpVT = N->getOperand(0).getValueType(); 16382 16383 // If the operands are legal vectors, leave them alone. 16384 if (TLI.isTypeLegal(OpVT)) 16385 return SDValue(); 16386 16387 SDLoc DL(N); 16388 EVT VT = N->getValueType(0); 16389 SmallVector<SDValue, 8> Ops; 16390 16391 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 16392 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16393 16394 // Keep track of what we encounter. 16395 bool AnyInteger = false; 16396 bool AnyFP = false; 16397 for (const SDValue &Op : N->ops()) { 16398 if (ISD::BITCAST == Op.getOpcode() && 16399 !Op.getOperand(0).getValueType().isVector()) 16400 Ops.push_back(Op.getOperand(0)); 16401 else if (ISD::UNDEF == Op.getOpcode()) 16402 Ops.push_back(ScalarUndef); 16403 else 16404 return SDValue(); 16405 16406 // Note whether we encounter an integer or floating point scalar. 16407 // If it's neither, bail out, it could be something weird like x86mmx. 16408 EVT LastOpVT = Ops.back().getValueType(); 16409 if (LastOpVT.isFloatingPoint()) 16410 AnyFP = true; 16411 else if (LastOpVT.isInteger()) 16412 AnyInteger = true; 16413 else 16414 return SDValue(); 16415 } 16416 16417 // If any of the operands is a floating point scalar bitcast to a vector, 16418 // use floating point types throughout, and bitcast everything. 16419 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 16420 if (AnyFP) { 16421 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 16422 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 16423 if (AnyInteger) { 16424 for (SDValue &Op : Ops) { 16425 if (Op.getValueType() == SVT) 16426 continue; 16427 if (Op.isUndef()) 16428 Op = ScalarUndef; 16429 else 16430 Op = DAG.getBitcast(SVT, Op); 16431 } 16432 } 16433 } 16434 16435 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 16436 VT.getSizeInBits() / SVT.getSizeInBits()); 16437 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 16438 } 16439 16440 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 16441 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 16442 // most two distinct vectors the same size as the result, attempt to turn this 16443 // into a legal shuffle. 16444 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 16445 EVT VT = N->getValueType(0); 16446 EVT OpVT = N->getOperand(0).getValueType(); 16447 int NumElts = VT.getVectorNumElements(); 16448 int NumOpElts = OpVT.getVectorNumElements(); 16449 16450 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 16451 SmallVector<int, 8> Mask; 16452 16453 for (SDValue Op : N->ops()) { 16454 Op = peekThroughBitcasts(Op); 16455 16456 // UNDEF nodes convert to UNDEF shuffle mask values. 16457 if (Op.isUndef()) { 16458 Mask.append((unsigned)NumOpElts, -1); 16459 continue; 16460 } 16461 16462 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16463 return SDValue(); 16464 16465 // What vector are we extracting the subvector from and at what index? 16466 SDValue ExtVec = Op.getOperand(0); 16467 16468 // We want the EVT of the original extraction to correctly scale the 16469 // extraction index. 16470 EVT ExtVT = ExtVec.getValueType(); 16471 ExtVec = peekThroughBitcasts(ExtVec); 16472 16473 // UNDEF nodes convert to UNDEF shuffle mask values. 16474 if (ExtVec.isUndef()) { 16475 Mask.append((unsigned)NumOpElts, -1); 16476 continue; 16477 } 16478 16479 if (!isa<ConstantSDNode>(Op.getOperand(1))) 16480 return SDValue(); 16481 int ExtIdx = Op.getConstantOperandVal(1); 16482 16483 // Ensure that we are extracting a subvector from a vector the same 16484 // size as the result. 16485 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 16486 return SDValue(); 16487 16488 // Scale the subvector index to account for any bitcast. 16489 int NumExtElts = ExtVT.getVectorNumElements(); 16490 if (0 == (NumExtElts % NumElts)) 16491 ExtIdx /= (NumExtElts / NumElts); 16492 else if (0 == (NumElts % NumExtElts)) 16493 ExtIdx *= (NumElts / NumExtElts); 16494 else 16495 return SDValue(); 16496 16497 // At most we can reference 2 inputs in the final shuffle. 16498 if (SV0.isUndef() || SV0 == ExtVec) { 16499 SV0 = ExtVec; 16500 for (int i = 0; i != NumOpElts; ++i) 16501 Mask.push_back(i + ExtIdx); 16502 } else if (SV1.isUndef() || SV1 == ExtVec) { 16503 SV1 = ExtVec; 16504 for (int i = 0; i != NumOpElts; ++i) 16505 Mask.push_back(i + ExtIdx + NumElts); 16506 } else { 16507 return SDValue(); 16508 } 16509 } 16510 16511 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 16512 return SDValue(); 16513 16514 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 16515 DAG.getBitcast(VT, SV1), Mask); 16516 } 16517 16518 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 16519 // If we only have one input vector, we don't need to do any concatenation. 16520 if (N->getNumOperands() == 1) 16521 return N->getOperand(0); 16522 16523 // Check if all of the operands are undefs. 16524 EVT VT = N->getValueType(0); 16525 if (ISD::allOperandsUndef(N)) 16526 return DAG.getUNDEF(VT); 16527 16528 // Optimize concat_vectors where all but the first of the vectors are undef. 16529 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 16530 return Op.isUndef(); 16531 })) { 16532 SDValue In = N->getOperand(0); 16533 assert(In.getValueType().isVector() && "Must concat vectors"); 16534 16535 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 16536 if (In->getOpcode() == ISD::BITCAST && 16537 !In->getOperand(0).getValueType().isVector()) { 16538 SDValue Scalar = In->getOperand(0); 16539 16540 // If the bitcast type isn't legal, it might be a trunc of a legal type; 16541 // look through the trunc so we can still do the transform: 16542 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 16543 if (Scalar->getOpcode() == ISD::TRUNCATE && 16544 !TLI.isTypeLegal(Scalar.getValueType()) && 16545 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 16546 Scalar = Scalar->getOperand(0); 16547 16548 EVT SclTy = Scalar->getValueType(0); 16549 16550 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 16551 return SDValue(); 16552 16553 // Bail out if the vector size is not a multiple of the scalar size. 16554 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 16555 return SDValue(); 16556 16557 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 16558 if (VNTNumElms < 2) 16559 return SDValue(); 16560 16561 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 16562 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 16563 return SDValue(); 16564 16565 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 16566 return DAG.getBitcast(VT, Res); 16567 } 16568 } 16569 16570 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 16571 // We have already tested above for an UNDEF only concatenation. 16572 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 16573 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 16574 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 16575 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 16576 }; 16577 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 16578 SmallVector<SDValue, 8> Opnds; 16579 EVT SVT = VT.getScalarType(); 16580 16581 EVT MinVT = SVT; 16582 if (!SVT.isFloatingPoint()) { 16583 // If BUILD_VECTOR are from built from integer, they may have different 16584 // operand types. Get the smallest type and truncate all operands to it. 16585 bool FoundMinVT = false; 16586 for (const SDValue &Op : N->ops()) 16587 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16588 EVT OpSVT = Op.getOperand(0).getValueType(); 16589 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 16590 FoundMinVT = true; 16591 } 16592 assert(FoundMinVT && "Concat vector type mismatch"); 16593 } 16594 16595 for (const SDValue &Op : N->ops()) { 16596 EVT OpVT = Op.getValueType(); 16597 unsigned NumElts = OpVT.getVectorNumElements(); 16598 16599 if (ISD::UNDEF == Op.getOpcode()) 16600 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 16601 16602 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 16603 if (SVT.isFloatingPoint()) { 16604 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 16605 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 16606 } else { 16607 for (unsigned i = 0; i != NumElts; ++i) 16608 Opnds.push_back( 16609 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 16610 } 16611 } 16612 } 16613 16614 assert(VT.getVectorNumElements() == Opnds.size() && 16615 "Concat vector type mismatch"); 16616 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 16617 } 16618 16619 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 16620 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 16621 return V; 16622 16623 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 16624 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 16625 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 16626 return V; 16627 16628 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 16629 // nodes often generate nop CONCAT_VECTOR nodes. 16630 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 16631 // place the incoming vectors at the exact same location. 16632 SDValue SingleSource = SDValue(); 16633 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 16634 16635 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16636 SDValue Op = N->getOperand(i); 16637 16638 if (Op.isUndef()) 16639 continue; 16640 16641 // Check if this is the identity extract: 16642 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 16643 return SDValue(); 16644 16645 // Find the single incoming vector for the extract_subvector. 16646 if (SingleSource.getNode()) { 16647 if (Op.getOperand(0) != SingleSource) 16648 return SDValue(); 16649 } else { 16650 SingleSource = Op.getOperand(0); 16651 16652 // Check the source type is the same as the type of the result. 16653 // If not, this concat may extend the vector, so we can not 16654 // optimize it away. 16655 if (SingleSource.getValueType() != N->getValueType(0)) 16656 return SDValue(); 16657 } 16658 16659 unsigned IdentityIndex = i * PartNumElem; 16660 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 16661 // The extract index must be constant. 16662 if (!CS) 16663 return SDValue(); 16664 16665 // Check that we are reading from the identity index. 16666 if (CS->getZExtValue() != IdentityIndex) 16667 return SDValue(); 16668 } 16669 16670 if (SingleSource.getNode()) 16671 return SingleSource; 16672 16673 return SDValue(); 16674 } 16675 16676 /// If we are extracting a subvector produced by a wide binary operator with at 16677 /// at least one operand that was the result of a vector concatenation, then try 16678 /// to use the narrow vector operands directly to avoid the concatenation and 16679 /// extraction. 16680 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 16681 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 16682 // some of these bailouts with other transforms. 16683 16684 // The extract index must be a constant, so we can map it to a concat operand. 16685 auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16686 if (!ExtractIndexC) 16687 return SDValue(); 16688 16689 // We are looking for an optionally bitcasted wide vector binary operator 16690 // feeding an extract subvector. 16691 SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0)); 16692 if (!ISD::isBinaryOp(BinOp.getNode())) 16693 return SDValue(); 16694 16695 // The binop must be a vector type, so we can chop it in half. 16696 EVT WideBVT = BinOp.getValueType(); 16697 if (!WideBVT.isVector()) 16698 return SDValue(); 16699 16700 // Bail out if the target does not support a narrower version of the binop. 16701 unsigned BOpcode = BinOp.getOpcode(); 16702 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 16703 WideBVT.getVectorNumElements() / 2); 16704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16705 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 16706 return SDValue(); 16707 16708 // Only handle the case where we are doubling and then halving. A larger ratio 16709 // may require more than two narrow binops to replace the wide binop. 16710 EVT VT = Extract->getValueType(0); 16711 unsigned NumElems = VT.getVectorNumElements(); 16712 unsigned ExtractIndex = ExtractIndexC->getZExtValue(); 16713 assert(ExtractIndex % NumElems == 0 && 16714 "Extract index is not a multiple of the vector length."); 16715 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 16716 return SDValue(); 16717 16718 // TODO: The motivating case for this transform is an x86 AVX1 target. That 16719 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 16720 // flavors, but no other 256-bit integer support. This could be extended to 16721 // handle any binop, but that may require fixing/adding other folds to avoid 16722 // codegen regressions. 16723 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 16724 return SDValue(); 16725 16726 // We need at least one concatenation operation of a binop operand to make 16727 // this transform worthwhile. The concat must double the input vector sizes. 16728 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 16729 SDValue LHS = peekThroughBitcasts(BinOp.getOperand(0)); 16730 SDValue RHS = peekThroughBitcasts(BinOp.getOperand(1)); 16731 bool ConcatL = 16732 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 16733 bool ConcatR = 16734 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 16735 if (!ConcatL && !ConcatR) 16736 return SDValue(); 16737 16738 // If one of the binop operands was not the result of a concat, we must 16739 // extract a half-sized operand for our new narrow binop. We can't just reuse 16740 // the original extract index operand because we may have bitcasted. 16741 unsigned ConcatOpNum = ExtractIndex / NumElems; 16742 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 16743 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 16744 SDLoc DL(Extract); 16745 16746 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 16747 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 16748 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 16749 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 16750 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16751 BinOp.getOperand(0), 16752 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16753 16754 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 16755 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 16756 BinOp.getOperand(1), 16757 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 16758 16759 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 16760 return DAG.getBitcast(VT, NarrowBinOp); 16761 } 16762 16763 /// If we are extracting a subvector from a wide vector load, convert to a 16764 /// narrow load to eliminate the extraction: 16765 /// (extract_subvector (load wide vector)) --> (load narrow vector) 16766 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 16767 // TODO: Add support for big-endian. The offset calculation must be adjusted. 16768 if (DAG.getDataLayout().isBigEndian()) 16769 return SDValue(); 16770 16771 // TODO: The one-use check is overly conservative. Check the cost of the 16772 // extract instead or remove that condition entirely. 16773 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 16774 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 16775 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 16776 !ExtIdx) 16777 return SDValue(); 16778 16779 // The narrow load will be offset from the base address of the old load if 16780 // we are extracting from something besides index 0 (little-endian). 16781 EVT VT = Extract->getValueType(0); 16782 SDLoc DL(Extract); 16783 SDValue BaseAddr = Ld->getOperand(1); 16784 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 16785 16786 // TODO: Use "BaseIndexOffset" to make this more effective. 16787 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 16788 MachineFunction &MF = DAG.getMachineFunction(); 16789 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 16790 VT.getStoreSize()); 16791 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 16792 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 16793 return NewLd; 16794 } 16795 16796 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 16797 EVT NVT = N->getValueType(0); 16798 SDValue V = N->getOperand(0); 16799 16800 // Extract from UNDEF is UNDEF. 16801 if (V.isUndef()) 16802 return DAG.getUNDEF(NVT); 16803 16804 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 16805 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 16806 return NarrowLoad; 16807 16808 // Combine: 16809 // (extract_subvec (concat V1, V2, ...), i) 16810 // Into: 16811 // Vi if possible 16812 // Only operand 0 is checked as 'concat' assumes all inputs of the same 16813 // type. 16814 if (V->getOpcode() == ISD::CONCAT_VECTORS && 16815 isa<ConstantSDNode>(N->getOperand(1)) && 16816 V->getOperand(0).getValueType() == NVT) { 16817 unsigned Idx = N->getConstantOperandVal(1); 16818 unsigned NumElems = NVT.getVectorNumElements(); 16819 assert((Idx % NumElems) == 0 && 16820 "IDX in concat is not a multiple of the result vector length."); 16821 return V->getOperand(Idx / NumElems); 16822 } 16823 16824 V = peekThroughBitcasts(V); 16825 16826 // If the input is a build vector. Try to make a smaller build vector. 16827 if (V->getOpcode() == ISD::BUILD_VECTOR) { 16828 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 16829 EVT InVT = V->getValueType(0); 16830 unsigned ExtractSize = NVT.getSizeInBits(); 16831 unsigned EltSize = InVT.getScalarSizeInBits(); 16832 // Only do this if we won't split any elements. 16833 if (ExtractSize % EltSize == 0) { 16834 unsigned NumElems = ExtractSize / EltSize; 16835 EVT EltVT = InVT.getVectorElementType(); 16836 EVT ExtractVT = NumElems == 1 ? EltVT : 16837 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 16838 if ((Level < AfterLegalizeDAG || 16839 (NumElems == 1 || 16840 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 16841 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 16842 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 16843 EltSize; 16844 if (NumElems == 1) { 16845 SDValue Src = V->getOperand(IdxVal); 16846 if (EltVT != Src.getValueType()) 16847 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 16848 16849 return DAG.getBitcast(NVT, Src); 16850 } 16851 16852 // Extract the pieces from the original build_vector. 16853 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 16854 makeArrayRef(V->op_begin() + IdxVal, 16855 NumElems)); 16856 return DAG.getBitcast(NVT, BuildVec); 16857 } 16858 } 16859 } 16860 } 16861 16862 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 16863 // Handle only simple case where vector being inserted and vector 16864 // being extracted are of same size. 16865 EVT SmallVT = V->getOperand(1).getValueType(); 16866 if (!NVT.bitsEq(SmallVT)) 16867 return SDValue(); 16868 16869 // Only handle cases where both indexes are constants. 16870 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16871 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 16872 16873 if (InsIdx && ExtIdx) { 16874 // Combine: 16875 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 16876 // Into: 16877 // indices are equal or bit offsets are equal => V1 16878 // otherwise => (extract_subvec V1, ExtIdx) 16879 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 16880 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 16881 return DAG.getBitcast(NVT, V->getOperand(1)); 16882 return DAG.getNode( 16883 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 16884 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 16885 N->getOperand(1)); 16886 } 16887 } 16888 16889 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 16890 return NarrowBOp; 16891 16892 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 16893 return SDValue(N, 0); 16894 16895 return SDValue(); 16896 } 16897 16898 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 16899 // or turn a shuffle of a single concat into simpler shuffle then concat. 16900 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 16901 EVT VT = N->getValueType(0); 16902 unsigned NumElts = VT.getVectorNumElements(); 16903 16904 SDValue N0 = N->getOperand(0); 16905 SDValue N1 = N->getOperand(1); 16906 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 16907 16908 SmallVector<SDValue, 4> Ops; 16909 EVT ConcatVT = N0.getOperand(0).getValueType(); 16910 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 16911 unsigned NumConcats = NumElts / NumElemsPerConcat; 16912 16913 // Special case: shuffle(concat(A,B)) can be more efficiently represented 16914 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 16915 // half vector elements. 16916 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 16917 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 16918 SVN->getMask().end(), [](int i) { return i == -1; })) { 16919 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 16920 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 16921 N1 = DAG.getUNDEF(ConcatVT); 16922 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 16923 } 16924 16925 // Look at every vector that's inserted. We're looking for exact 16926 // subvector-sized copies from a concatenated vector 16927 for (unsigned I = 0; I != NumConcats; ++I) { 16928 // Make sure we're dealing with a copy. 16929 unsigned Begin = I * NumElemsPerConcat; 16930 bool AllUndef = true, NoUndef = true; 16931 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 16932 if (SVN->getMaskElt(J) >= 0) 16933 AllUndef = false; 16934 else 16935 NoUndef = false; 16936 } 16937 16938 if (NoUndef) { 16939 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 16940 return SDValue(); 16941 16942 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 16943 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 16944 return SDValue(); 16945 16946 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 16947 if (FirstElt < N0.getNumOperands()) 16948 Ops.push_back(N0.getOperand(FirstElt)); 16949 else 16950 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 16951 16952 } else if (AllUndef) { 16953 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 16954 } else { // Mixed with general masks and undefs, can't do optimization. 16955 return SDValue(); 16956 } 16957 } 16958 16959 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16960 } 16961 16962 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 16963 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 16964 // 16965 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 16966 // a simplification in some sense, but it isn't appropriate in general: some 16967 // BUILD_VECTORs are substantially cheaper than others. The general case 16968 // of a BUILD_VECTOR requires inserting each element individually (or 16969 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 16970 // all constants is a single constant pool load. A BUILD_VECTOR where each 16971 // element is identical is a splat. A BUILD_VECTOR where most of the operands 16972 // are undef lowers to a small number of element insertions. 16973 // 16974 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 16975 // We don't fold shuffles where one side is a non-zero constant, and we don't 16976 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 16977 // non-constant operands. This seems to work out reasonably well in practice. 16978 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 16979 SelectionDAG &DAG, 16980 const TargetLowering &TLI) { 16981 EVT VT = SVN->getValueType(0); 16982 unsigned NumElts = VT.getVectorNumElements(); 16983 SDValue N0 = SVN->getOperand(0); 16984 SDValue N1 = SVN->getOperand(1); 16985 16986 if (!N0->hasOneUse() || !N1->hasOneUse()) 16987 return SDValue(); 16988 16989 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 16990 // discussed above. 16991 if (!N1.isUndef()) { 16992 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 16993 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 16994 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 16995 return SDValue(); 16996 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 16997 return SDValue(); 16998 } 16999 17000 // If both inputs are splats of the same value then we can safely merge this 17001 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 17002 bool IsSplat = false; 17003 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 17004 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 17005 if (BV0 && BV1) 17006 if (SDValue Splat0 = BV0->getSplatValue()) 17007 IsSplat = (Splat0 == BV1->getSplatValue()); 17008 17009 SmallVector<SDValue, 8> Ops; 17010 SmallSet<SDValue, 16> DuplicateOps; 17011 for (int M : SVN->getMask()) { 17012 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 17013 if (M >= 0) { 17014 int Idx = M < (int)NumElts ? M : M - NumElts; 17015 SDValue &S = (M < (int)NumElts ? N0 : N1); 17016 if (S.getOpcode() == ISD::BUILD_VECTOR) { 17017 Op = S.getOperand(Idx); 17018 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 17019 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 17020 Op = S.getOperand(0); 17021 } else { 17022 // Operand can't be combined - bail out. 17023 return SDValue(); 17024 } 17025 } 17026 17027 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 17028 // generating a splat; semantically, this is fine, but it's likely to 17029 // generate low-quality code if the target can't reconstruct an appropriate 17030 // shuffle. 17031 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 17032 if (!IsSplat && !DuplicateOps.insert(Op).second) 17033 return SDValue(); 17034 17035 Ops.push_back(Op); 17036 } 17037 17038 // BUILD_VECTOR requires all inputs to be of the same type, find the 17039 // maximum type and extend them all. 17040 EVT SVT = VT.getScalarType(); 17041 if (SVT.isInteger()) 17042 for (SDValue &Op : Ops) 17043 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 17044 if (SVT != VT.getScalarType()) 17045 for (SDValue &Op : Ops) 17046 Op = TLI.isZExtFree(Op.getValueType(), SVT) 17047 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 17048 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 17049 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 17050 } 17051 17052 // Match shuffles that can be converted to any_vector_extend_in_reg. 17053 // This is often generated during legalization. 17054 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 17055 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 17056 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 17057 SelectionDAG &DAG, 17058 const TargetLowering &TLI, 17059 bool LegalOperations, 17060 bool LegalTypes) { 17061 EVT VT = SVN->getValueType(0); 17062 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 17063 17064 // TODO Add support for big-endian when we have a test case. 17065 if (!VT.isInteger() || IsBigEndian) 17066 return SDValue(); 17067 17068 unsigned NumElts = VT.getVectorNumElements(); 17069 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 17070 ArrayRef<int> Mask = SVN->getMask(); 17071 SDValue N0 = SVN->getOperand(0); 17072 17073 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 17074 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 17075 for (unsigned i = 0; i != NumElts; ++i) { 17076 if (Mask[i] < 0) 17077 continue; 17078 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 17079 continue; 17080 return false; 17081 } 17082 return true; 17083 }; 17084 17085 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 17086 // power-of-2 extensions as they are the most likely. 17087 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 17088 // Check for non power of 2 vector sizes 17089 if (NumElts % Scale != 0) 17090 continue; 17091 if (!isAnyExtend(Scale)) 17092 continue; 17093 17094 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 17095 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 17096 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 17097 if (!LegalOperations || 17098 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 17099 return DAG.getBitcast(VT, 17100 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 17101 } 17102 17103 return SDValue(); 17104 } 17105 17106 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 17107 // each source element of a large type into the lowest elements of a smaller 17108 // destination type. This is often generated during legalization. 17109 // If the source node itself was a '*_extend_vector_inreg' node then we should 17110 // then be able to remove it. 17111 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 17112 SelectionDAG &DAG) { 17113 EVT VT = SVN->getValueType(0); 17114 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 17115 17116 // TODO Add support for big-endian when we have a test case. 17117 if (!VT.isInteger() || IsBigEndian) 17118 return SDValue(); 17119 17120 SDValue N0 = peekThroughBitcasts(SVN->getOperand(0)); 17121 17122 unsigned Opcode = N0.getOpcode(); 17123 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 17124 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 17125 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 17126 return SDValue(); 17127 17128 SDValue N00 = N0.getOperand(0); 17129 ArrayRef<int> Mask = SVN->getMask(); 17130 unsigned NumElts = VT.getVectorNumElements(); 17131 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 17132 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 17133 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 17134 17135 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 17136 return SDValue(); 17137 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 17138 17139 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 17140 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 17141 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 17142 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 17143 for (unsigned i = 0; i != NumElts; ++i) { 17144 if (Mask[i] < 0) 17145 continue; 17146 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 17147 continue; 17148 return false; 17149 } 17150 return true; 17151 }; 17152 17153 // At the moment we just handle the case where we've truncated back to the 17154 // same size as before the extension. 17155 // TODO: handle more extension/truncation cases as cases arise. 17156 if (EltSizeInBits != ExtSrcSizeInBits) 17157 return SDValue(); 17158 17159 // We can remove *extend_vector_inreg only if the truncation happens at 17160 // the same scale as the extension. 17161 if (isTruncate(ExtScale)) 17162 return DAG.getBitcast(VT, N00); 17163 17164 return SDValue(); 17165 } 17166 17167 // Combine shuffles of splat-shuffles of the form: 17168 // shuffle (shuffle V, undef, splat-mask), undef, M 17169 // If splat-mask contains undef elements, we need to be careful about 17170 // introducing undef's in the folded mask which are not the result of composing 17171 // the masks of the shuffles. 17172 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 17173 ShuffleVectorSDNode *Splat, 17174 SelectionDAG &DAG) { 17175 ArrayRef<int> SplatMask = Splat->getMask(); 17176 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 17177 17178 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 17179 // every undef mask element in the splat-shuffle has a corresponding undef 17180 // element in the user-shuffle's mask or if the composition of mask elements 17181 // would result in undef. 17182 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 17183 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 17184 // In this case it is not legal to simplify to the splat-shuffle because we 17185 // may be exposing the users of the shuffle an undef element at index 1 17186 // which was not there before the combine. 17187 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 17188 // In this case the composition of masks yields SplatMask, so it's ok to 17189 // simplify to the splat-shuffle. 17190 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 17191 // In this case the composed mask includes all undef elements of SplatMask 17192 // and in addition sets element zero to undef. It is safe to simplify to 17193 // the splat-shuffle. 17194 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 17195 ArrayRef<int> SplatMask) { 17196 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 17197 if (UserMask[i] != -1 && SplatMask[i] == -1 && 17198 SplatMask[UserMask[i]] != -1) 17199 return false; 17200 return true; 17201 }; 17202 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 17203 return SDValue(Splat, 0); 17204 17205 // Create a new shuffle with a mask that is composed of the two shuffles' 17206 // masks. 17207 SmallVector<int, 32> NewMask; 17208 for (int Idx : UserMask) 17209 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 17210 17211 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 17212 Splat->getOperand(0), Splat->getOperand(1), 17213 NewMask); 17214 } 17215 17216 /// If the shuffle mask is taking exactly one element from the first vector 17217 /// operand and passing through all other elements from the second vector 17218 /// operand, return the index of the mask element that is choosing an element 17219 /// from the first operand. Otherwise, return -1. 17220 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 17221 int MaskSize = Mask.size(); 17222 int EltFromOp0 = -1; 17223 // TODO: This does not match if there are undef elements in the shuffle mask. 17224 // Should we ignore undefs in the shuffle mask instead? The trade-off is 17225 // removing an instruction (a shuffle), but losing the knowledge that some 17226 // vector lanes are not needed. 17227 for (int i = 0; i != MaskSize; ++i) { 17228 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 17229 // We're looking for a shuffle of exactly one element from operand 0. 17230 if (EltFromOp0 != -1) 17231 return -1; 17232 EltFromOp0 = i; 17233 } else if (Mask[i] != i + MaskSize) { 17234 // Nothing from operand 1 can change lanes. 17235 return -1; 17236 } 17237 } 17238 return EltFromOp0; 17239 } 17240 17241 /// If a shuffle inserts exactly one element from a source vector operand into 17242 /// another vector operand and we can access the specified element as a scalar, 17243 /// then we can eliminate the shuffle. 17244 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 17245 SelectionDAG &DAG) { 17246 // First, check if we are taking one element of a vector and shuffling that 17247 // element into another vector. 17248 ArrayRef<int> Mask = Shuf->getMask(); 17249 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 17250 SDValue Op0 = Shuf->getOperand(0); 17251 SDValue Op1 = Shuf->getOperand(1); 17252 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 17253 if (ShufOp0Index == -1) { 17254 // Commute mask and check again. 17255 ShuffleVectorSDNode::commuteMask(CommutedMask); 17256 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 17257 if (ShufOp0Index == -1) 17258 return SDValue(); 17259 // Commute operands to match the commuted shuffle mask. 17260 std::swap(Op0, Op1); 17261 Mask = CommutedMask; 17262 } 17263 17264 // The shuffle inserts exactly one element from operand 0 into operand 1. 17265 // Now see if we can access that element as a scalar via a real insert element 17266 // instruction. 17267 // TODO: We can try harder to locate the element as a scalar. Examples: it 17268 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 17269 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 17270 "Shuffle mask value must be from operand 0"); 17271 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 17272 return SDValue(); 17273 17274 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 17275 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 17276 return SDValue(); 17277 17278 // There's an existing insertelement with constant insertion index, so we 17279 // don't need to check the legality/profitability of a replacement operation 17280 // that differs at most in the constant value. The target should be able to 17281 // lower any of those in a similar way. If not, legalization will expand this 17282 // to a scalar-to-vector plus shuffle. 17283 // 17284 // Note that the shuffle may move the scalar from the position that the insert 17285 // element used. Therefore, our new insert element occurs at the shuffle's 17286 // mask index value, not the insert's index value. 17287 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 17288 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 17289 Op0.getOperand(2).getValueType()); 17290 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 17291 Op1, Op0.getOperand(1), NewInsIndex); 17292 } 17293 17294 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 17295 EVT VT = N->getValueType(0); 17296 unsigned NumElts = VT.getVectorNumElements(); 17297 17298 SDValue N0 = N->getOperand(0); 17299 SDValue N1 = N->getOperand(1); 17300 17301 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 17302 17303 // Canonicalize shuffle undef, undef -> undef 17304 if (N0.isUndef() && N1.isUndef()) 17305 return DAG.getUNDEF(VT); 17306 17307 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 17308 17309 // Canonicalize shuffle v, v -> v, undef 17310 if (N0 == N1) { 17311 SmallVector<int, 8> NewMask; 17312 for (unsigned i = 0; i != NumElts; ++i) { 17313 int Idx = SVN->getMaskElt(i); 17314 if (Idx >= (int)NumElts) Idx -= NumElts; 17315 NewMask.push_back(Idx); 17316 } 17317 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 17318 } 17319 17320 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 17321 if (N0.isUndef()) 17322 return DAG.getCommutedVectorShuffle(*SVN); 17323 17324 // Remove references to rhs if it is undef 17325 if (N1.isUndef()) { 17326 bool Changed = false; 17327 SmallVector<int, 8> NewMask; 17328 for (unsigned i = 0; i != NumElts; ++i) { 17329 int Idx = SVN->getMaskElt(i); 17330 if (Idx >= (int)NumElts) { 17331 Idx = -1; 17332 Changed = true; 17333 } 17334 NewMask.push_back(Idx); 17335 } 17336 if (Changed) 17337 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 17338 } 17339 17340 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 17341 return InsElt; 17342 17343 // A shuffle of a single vector that is a splat can always be folded. 17344 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 17345 if (N1->isUndef() && N0Shuf->isSplat()) 17346 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 17347 17348 // If it is a splat, check if the argument vector is another splat or a 17349 // build_vector. 17350 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 17351 SDNode *V = N0.getNode(); 17352 17353 // If this is a bit convert that changes the element type of the vector but 17354 // not the number of vector elements, look through it. Be careful not to 17355 // look though conversions that change things like v4f32 to v2f64. 17356 if (V->getOpcode() == ISD::BITCAST) { 17357 SDValue ConvInput = V->getOperand(0); 17358 if (ConvInput.getValueType().isVector() && 17359 ConvInput.getValueType().getVectorNumElements() == NumElts) 17360 V = ConvInput.getNode(); 17361 } 17362 17363 if (V->getOpcode() == ISD::BUILD_VECTOR) { 17364 assert(V->getNumOperands() == NumElts && 17365 "BUILD_VECTOR has wrong number of operands"); 17366 SDValue Base; 17367 bool AllSame = true; 17368 for (unsigned i = 0; i != NumElts; ++i) { 17369 if (!V->getOperand(i).isUndef()) { 17370 Base = V->getOperand(i); 17371 break; 17372 } 17373 } 17374 // Splat of <u, u, u, u>, return <u, u, u, u> 17375 if (!Base.getNode()) 17376 return N0; 17377 for (unsigned i = 0; i != NumElts; ++i) { 17378 if (V->getOperand(i) != Base) { 17379 AllSame = false; 17380 break; 17381 } 17382 } 17383 // Splat of <x, x, x, x>, return <x, x, x, x> 17384 if (AllSame) 17385 return N0; 17386 17387 // Canonicalize any other splat as a build_vector. 17388 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 17389 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 17390 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 17391 17392 // We may have jumped through bitcasts, so the type of the 17393 // BUILD_VECTOR may not match the type of the shuffle. 17394 if (V->getValueType(0) != VT) 17395 NewBV = DAG.getBitcast(VT, NewBV); 17396 return NewBV; 17397 } 17398 } 17399 17400 // Simplify source operands based on shuffle mask. 17401 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 17402 return SDValue(N, 0); 17403 17404 // Match shuffles that can be converted to any_vector_extend_in_reg. 17405 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 17406 return V; 17407 17408 // Combine "truncate_vector_in_reg" style shuffles. 17409 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 17410 return V; 17411 17412 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 17413 Level < AfterLegalizeVectorOps && 17414 (N1.isUndef() || 17415 (N1.getOpcode() == ISD::CONCAT_VECTORS && 17416 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 17417 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 17418 return V; 17419 } 17420 17421 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 17422 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 17423 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 17424 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 17425 return Res; 17426 17427 // If this shuffle only has a single input that is a bitcasted shuffle, 17428 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 17429 // back to their original types. 17430 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 17431 N1.isUndef() && Level < AfterLegalizeVectorOps && 17432 TLI.isTypeLegal(VT)) { 17433 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 17434 if (Scale == 1) 17435 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 17436 17437 SmallVector<int, 8> NewMask; 17438 for (int M : Mask) 17439 for (int s = 0; s != Scale; ++s) 17440 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 17441 return NewMask; 17442 }; 17443 17444 SDValue BC0 = peekThroughOneUseBitcasts(N0); 17445 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 17446 EVT SVT = VT.getScalarType(); 17447 EVT InnerVT = BC0->getValueType(0); 17448 EVT InnerSVT = InnerVT.getScalarType(); 17449 17450 // Determine which shuffle works with the smaller scalar type. 17451 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 17452 EVT ScaleSVT = ScaleVT.getScalarType(); 17453 17454 if (TLI.isTypeLegal(ScaleVT) && 17455 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 17456 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 17457 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17458 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 17459 17460 // Scale the shuffle masks to the smaller scalar type. 17461 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 17462 SmallVector<int, 8> InnerMask = 17463 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 17464 SmallVector<int, 8> OuterMask = 17465 ScaleShuffleMask(SVN->getMask(), OuterScale); 17466 17467 // Merge the shuffle masks. 17468 SmallVector<int, 8> NewMask; 17469 for (int M : OuterMask) 17470 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 17471 17472 // Test for shuffle mask legality over both commutations. 17473 SDValue SV0 = BC0->getOperand(0); 17474 SDValue SV1 = BC0->getOperand(1); 17475 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17476 if (!LegalMask) { 17477 std::swap(SV0, SV1); 17478 ShuffleVectorSDNode::commuteMask(NewMask); 17479 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 17480 } 17481 17482 if (LegalMask) { 17483 SV0 = DAG.getBitcast(ScaleVT, SV0); 17484 SV1 = DAG.getBitcast(ScaleVT, SV1); 17485 return DAG.getBitcast( 17486 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 17487 } 17488 } 17489 } 17490 } 17491 17492 // Canonicalize shuffles according to rules: 17493 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 17494 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 17495 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 17496 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 17497 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 17498 TLI.isTypeLegal(VT)) { 17499 // The incoming shuffle must be of the same type as the result of the 17500 // current shuffle. 17501 assert(N1->getOperand(0).getValueType() == VT && 17502 "Shuffle types don't match"); 17503 17504 SDValue SV0 = N1->getOperand(0); 17505 SDValue SV1 = N1->getOperand(1); 17506 bool HasSameOp0 = N0 == SV0; 17507 bool IsSV1Undef = SV1.isUndef(); 17508 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 17509 // Commute the operands of this shuffle so that next rule 17510 // will trigger. 17511 return DAG.getCommutedVectorShuffle(*SVN); 17512 } 17513 17514 // Try to fold according to rules: 17515 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17516 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17517 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17518 // Don't try to fold shuffles with illegal type. 17519 // Only fold if this shuffle is the only user of the other shuffle. 17520 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 17521 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 17522 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 17523 17524 // Don't try to fold splats; they're likely to simplify somehow, or they 17525 // might be free. 17526 if (OtherSV->isSplat()) 17527 return SDValue(); 17528 17529 // The incoming shuffle must be of the same type as the result of the 17530 // current shuffle. 17531 assert(OtherSV->getOperand(0).getValueType() == VT && 17532 "Shuffle types don't match"); 17533 17534 SDValue SV0, SV1; 17535 SmallVector<int, 4> Mask; 17536 // Compute the combined shuffle mask for a shuffle with SV0 as the first 17537 // operand, and SV1 as the second operand. 17538 for (unsigned i = 0; i != NumElts; ++i) { 17539 int Idx = SVN->getMaskElt(i); 17540 if (Idx < 0) { 17541 // Propagate Undef. 17542 Mask.push_back(Idx); 17543 continue; 17544 } 17545 17546 SDValue CurrentVec; 17547 if (Idx < (int)NumElts) { 17548 // This shuffle index refers to the inner shuffle N0. Lookup the inner 17549 // shuffle mask to identify which vector is actually referenced. 17550 Idx = OtherSV->getMaskElt(Idx); 17551 if (Idx < 0) { 17552 // Propagate Undef. 17553 Mask.push_back(Idx); 17554 continue; 17555 } 17556 17557 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 17558 : OtherSV->getOperand(1); 17559 } else { 17560 // This shuffle index references an element within N1. 17561 CurrentVec = N1; 17562 } 17563 17564 // Simple case where 'CurrentVec' is UNDEF. 17565 if (CurrentVec.isUndef()) { 17566 Mask.push_back(-1); 17567 continue; 17568 } 17569 17570 // Canonicalize the shuffle index. We don't know yet if CurrentVec 17571 // will be the first or second operand of the combined shuffle. 17572 Idx = Idx % NumElts; 17573 if (!SV0.getNode() || SV0 == CurrentVec) { 17574 // Ok. CurrentVec is the left hand side. 17575 // Update the mask accordingly. 17576 SV0 = CurrentVec; 17577 Mask.push_back(Idx); 17578 continue; 17579 } 17580 17581 // Bail out if we cannot convert the shuffle pair into a single shuffle. 17582 if (SV1.getNode() && SV1 != CurrentVec) 17583 return SDValue(); 17584 17585 // Ok. CurrentVec is the right hand side. 17586 // Update the mask accordingly. 17587 SV1 = CurrentVec; 17588 Mask.push_back(Idx + NumElts); 17589 } 17590 17591 // Check if all indices in Mask are Undef. In case, propagate Undef. 17592 bool isUndefMask = true; 17593 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 17594 isUndefMask &= Mask[i] < 0; 17595 17596 if (isUndefMask) 17597 return DAG.getUNDEF(VT); 17598 17599 if (!SV0.getNode()) 17600 SV0 = DAG.getUNDEF(VT); 17601 if (!SV1.getNode()) 17602 SV1 = DAG.getUNDEF(VT); 17603 17604 // Avoid introducing shuffles with illegal mask. 17605 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 17606 ShuffleVectorSDNode::commuteMask(Mask); 17607 17608 if (!TLI.isShuffleMaskLegal(Mask, VT)) 17609 return SDValue(); 17610 17611 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 17612 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 17613 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 17614 std::swap(SV0, SV1); 17615 } 17616 17617 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 17618 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 17619 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 17620 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 17621 } 17622 17623 return SDValue(); 17624 } 17625 17626 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 17627 SDValue InVal = N->getOperand(0); 17628 EVT VT = N->getValueType(0); 17629 17630 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 17631 // with a VECTOR_SHUFFLE and possible truncate. 17632 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 17633 SDValue InVec = InVal->getOperand(0); 17634 SDValue EltNo = InVal->getOperand(1); 17635 auto InVecT = InVec.getValueType(); 17636 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 17637 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 17638 int Elt = C0->getZExtValue(); 17639 NewMask[0] = Elt; 17640 SDValue Val; 17641 // If we have an implict truncate do truncate here as long as it's legal. 17642 // if it's not legal, this should 17643 if (VT.getScalarType() != InVal.getValueType() && 17644 InVal.getValueType().isScalarInteger() && 17645 isTypeLegal(VT.getScalarType())) { 17646 Val = 17647 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 17648 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 17649 } 17650 if (VT.getScalarType() == InVecT.getScalarType() && 17651 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 17652 TLI.isShuffleMaskLegal(NewMask, VT)) { 17653 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 17654 DAG.getUNDEF(InVecT), NewMask); 17655 // If the initial vector is the correct size this shuffle is a 17656 // valid result. 17657 if (VT == InVecT) 17658 return Val; 17659 // If not we must truncate the vector. 17660 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 17661 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 17662 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 17663 EVT SubVT = 17664 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 17665 VT.getVectorNumElements()); 17666 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 17667 ZeroIdx); 17668 return Val; 17669 } 17670 } 17671 } 17672 } 17673 17674 return SDValue(); 17675 } 17676 17677 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 17678 EVT VT = N->getValueType(0); 17679 SDValue N0 = N->getOperand(0); 17680 SDValue N1 = N->getOperand(1); 17681 SDValue N2 = N->getOperand(2); 17682 17683 // If inserting an UNDEF, just return the original vector. 17684 if (N1.isUndef()) 17685 return N0; 17686 17687 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 17688 // us to pull BITCASTs from input to output. 17689 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 17690 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 17691 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 17692 17693 // If this is an insert of an extracted vector into an undef vector, we can 17694 // just use the input to the extract. 17695 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 17696 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 17697 return N1.getOperand(0); 17698 17699 // If we are inserting a bitcast value into an undef, with the same 17700 // number of elements, just use the bitcast input of the extract. 17701 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 17702 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 17703 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 17704 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 17705 N1.getOperand(0).getOperand(1) == N2 && 17706 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 17707 VT.getVectorNumElements() && 17708 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 17709 VT.getSizeInBits()) { 17710 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 17711 } 17712 17713 // If both N1 and N2 are bitcast values on which insert_subvector 17714 // would makes sense, pull the bitcast through. 17715 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 17716 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 17717 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 17718 SDValue CN0 = N0.getOperand(0); 17719 SDValue CN1 = N1.getOperand(0); 17720 EVT CN0VT = CN0.getValueType(); 17721 EVT CN1VT = CN1.getValueType(); 17722 if (CN0VT.isVector() && CN1VT.isVector() && 17723 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 17724 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) { 17725 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 17726 CN0.getValueType(), CN0, CN1, N2); 17727 return DAG.getBitcast(VT, NewINSERT); 17728 } 17729 } 17730 17731 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 17732 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 17733 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 17734 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 17735 N0.getOperand(1).getValueType() == N1.getValueType() && 17736 N0.getOperand(2) == N2) 17737 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 17738 N1, N2); 17739 17740 if (!isa<ConstantSDNode>(N2)) 17741 return SDValue(); 17742 17743 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 17744 17745 // Canonicalize insert_subvector dag nodes. 17746 // Example: 17747 // (insert_subvector (insert_subvector A, Idx0), Idx1) 17748 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 17749 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 17750 N1.getValueType() == N0.getOperand(1).getValueType() && 17751 isa<ConstantSDNode>(N0.getOperand(2))) { 17752 unsigned OtherIdx = N0.getConstantOperandVal(2); 17753 if (InsIdx < OtherIdx) { 17754 // Swap nodes. 17755 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 17756 N0.getOperand(0), N1, N2); 17757 AddToWorklist(NewOp.getNode()); 17758 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 17759 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 17760 } 17761 } 17762 17763 // If the input vector is a concatenation, and the insert replaces 17764 // one of the pieces, we can optimize into a single concat_vectors. 17765 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 17766 N0.getOperand(0).getValueType() == N1.getValueType()) { 17767 unsigned Factor = N1.getValueType().getVectorNumElements(); 17768 17769 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 17770 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 17771 17772 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 17773 } 17774 17775 return SDValue(); 17776 } 17777 17778 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 17779 SDValue N0 = N->getOperand(0); 17780 17781 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 17782 if (N0->getOpcode() == ISD::FP16_TO_FP) 17783 return N0->getOperand(0); 17784 17785 return SDValue(); 17786 } 17787 17788 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 17789 SDValue N0 = N->getOperand(0); 17790 17791 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 17792 if (N0->getOpcode() == ISD::AND) { 17793 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 17794 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 17795 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 17796 N0.getOperand(0)); 17797 } 17798 } 17799 17800 return SDValue(); 17801 } 17802 17803 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 17804 /// with the destination vector and a zero vector. 17805 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 17806 /// vector_shuffle V, Zero, <0, 4, 2, 4> 17807 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 17808 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 17809 17810 EVT VT = N->getValueType(0); 17811 SDValue LHS = N->getOperand(0); 17812 SDValue RHS = peekThroughBitcasts(N->getOperand(1)); 17813 SDLoc DL(N); 17814 17815 // Make sure we're not running after operation legalization where it 17816 // may have custom lowered the vector shuffles. 17817 if (LegalOperations) 17818 return SDValue(); 17819 17820 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 17821 return SDValue(); 17822 17823 EVT RVT = RHS.getValueType(); 17824 unsigned NumElts = RHS.getNumOperands(); 17825 17826 // Attempt to create a valid clear mask, splitting the mask into 17827 // sub elements and checking to see if each is 17828 // all zeros or all ones - suitable for shuffle masking. 17829 auto BuildClearMask = [&](int Split) { 17830 int NumSubElts = NumElts * Split; 17831 int NumSubBits = RVT.getScalarSizeInBits() / Split; 17832 17833 SmallVector<int, 8> Indices; 17834 for (int i = 0; i != NumSubElts; ++i) { 17835 int EltIdx = i / Split; 17836 int SubIdx = i % Split; 17837 SDValue Elt = RHS.getOperand(EltIdx); 17838 if (Elt.isUndef()) { 17839 Indices.push_back(-1); 17840 continue; 17841 } 17842 17843 APInt Bits; 17844 if (isa<ConstantSDNode>(Elt)) 17845 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 17846 else if (isa<ConstantFPSDNode>(Elt)) 17847 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 17848 else 17849 return SDValue(); 17850 17851 // Extract the sub element from the constant bit mask. 17852 if (DAG.getDataLayout().isBigEndian()) { 17853 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 17854 } else { 17855 Bits.lshrInPlace(SubIdx * NumSubBits); 17856 } 17857 17858 if (Split > 1) 17859 Bits = Bits.trunc(NumSubBits); 17860 17861 if (Bits.isAllOnesValue()) 17862 Indices.push_back(i); 17863 else if (Bits == 0) 17864 Indices.push_back(i + NumSubElts); 17865 else 17866 return SDValue(); 17867 } 17868 17869 // Let's see if the target supports this vector_shuffle. 17870 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 17871 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 17872 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 17873 return SDValue(); 17874 17875 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 17876 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 17877 DAG.getBitcast(ClearVT, LHS), 17878 Zero, Indices)); 17879 }; 17880 17881 // Determine maximum split level (byte level masking). 17882 int MaxSplit = 1; 17883 if (RVT.getScalarSizeInBits() % 8 == 0) 17884 MaxSplit = RVT.getScalarSizeInBits() / 8; 17885 17886 for (int Split = 1; Split <= MaxSplit; ++Split) 17887 if (RVT.getScalarSizeInBits() % Split == 0) 17888 if (SDValue S = BuildClearMask(Split)) 17889 return S; 17890 17891 return SDValue(); 17892 } 17893 17894 /// Visit a binary vector operation, like ADD. 17895 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 17896 assert(N->getValueType(0).isVector() && 17897 "SimplifyVBinOp only works on vectors!"); 17898 17899 SDValue LHS = N->getOperand(0); 17900 SDValue RHS = N->getOperand(1); 17901 SDValue Ops[] = {LHS, RHS}; 17902 17903 // See if we can constant fold the vector operation. 17904 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 17905 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 17906 return Fold; 17907 17908 // Type legalization might introduce new shuffles in the DAG. 17909 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 17910 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 17911 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 17912 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 17913 LHS.getOperand(1).isUndef() && 17914 RHS.getOperand(1).isUndef()) { 17915 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 17916 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 17917 17918 if (SVN0->getMask().equals(SVN1->getMask())) { 17919 EVT VT = N->getValueType(0); 17920 SDValue UndefVector = LHS.getOperand(1); 17921 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 17922 LHS.getOperand(0), RHS.getOperand(0), 17923 N->getFlags()); 17924 AddUsersToWorklist(N); 17925 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 17926 SVN0->getMask()); 17927 } 17928 } 17929 17930 return SDValue(); 17931 } 17932 17933 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 17934 SDValue N2) { 17935 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 17936 17937 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 17938 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 17939 17940 // If we got a simplified select_cc node back from SimplifySelectCC, then 17941 // break it down into a new SETCC node, and a new SELECT node, and then return 17942 // the SELECT node, since we were called with a SELECT node. 17943 if (SCC.getNode()) { 17944 // Check to see if we got a select_cc back (to turn into setcc/select). 17945 // Otherwise, just return whatever node we got back, like fabs. 17946 if (SCC.getOpcode() == ISD::SELECT_CC) { 17947 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 17948 N0.getValueType(), 17949 SCC.getOperand(0), SCC.getOperand(1), 17950 SCC.getOperand(4)); 17951 AddToWorklist(SETCC.getNode()); 17952 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 17953 SCC.getOperand(2), SCC.getOperand(3)); 17954 } 17955 17956 return SCC; 17957 } 17958 return SDValue(); 17959 } 17960 17961 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 17962 /// being selected between, see if we can simplify the select. Callers of this 17963 /// should assume that TheSelect is deleted if this returns true. As such, they 17964 /// should return the appropriate thing (e.g. the node) back to the top-level of 17965 /// the DAG combiner loop to avoid it being looked at. 17966 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 17967 SDValue RHS) { 17968 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17969 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 17970 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 17971 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 17972 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 17973 SDValue Sqrt = RHS; 17974 ISD::CondCode CC; 17975 SDValue CmpLHS; 17976 const ConstantFPSDNode *Zero = nullptr; 17977 17978 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 17979 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 17980 CmpLHS = TheSelect->getOperand(0); 17981 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 17982 } else { 17983 // SELECT or VSELECT 17984 SDValue Cmp = TheSelect->getOperand(0); 17985 if (Cmp.getOpcode() == ISD::SETCC) { 17986 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 17987 CmpLHS = Cmp.getOperand(0); 17988 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 17989 } 17990 } 17991 if (Zero && Zero->isZero() && 17992 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 17993 CC == ISD::SETULT || CC == ISD::SETLT)) { 17994 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 17995 CombineTo(TheSelect, Sqrt); 17996 return true; 17997 } 17998 } 17999 } 18000 // Cannot simplify select with vector condition 18001 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 18002 18003 // If this is a select from two identical things, try to pull the operation 18004 // through the select. 18005 if (LHS.getOpcode() != RHS.getOpcode() || 18006 !LHS.hasOneUse() || !RHS.hasOneUse()) 18007 return false; 18008 18009 // If this is a load and the token chain is identical, replace the select 18010 // of two loads with a load through a select of the address to load from. 18011 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 18012 // constants have been dropped into the constant pool. 18013 if (LHS.getOpcode() == ISD::LOAD) { 18014 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 18015 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 18016 18017 // Token chains must be identical. 18018 if (LHS.getOperand(0) != RHS.getOperand(0) || 18019 // Do not let this transformation reduce the number of volatile loads. 18020 LLD->isVolatile() || RLD->isVolatile() || 18021 // FIXME: If either is a pre/post inc/dec load, 18022 // we'd need to split out the address adjustment. 18023 LLD->isIndexed() || RLD->isIndexed() || 18024 // If this is an EXTLOAD, the VT's must match. 18025 LLD->getMemoryVT() != RLD->getMemoryVT() || 18026 // If this is an EXTLOAD, the kind of extension must match. 18027 (LLD->getExtensionType() != RLD->getExtensionType() && 18028 // The only exception is if one of the extensions is anyext. 18029 LLD->getExtensionType() != ISD::EXTLOAD && 18030 RLD->getExtensionType() != ISD::EXTLOAD) || 18031 // FIXME: this discards src value information. This is 18032 // over-conservative. It would be beneficial to be able to remember 18033 // both potential memory locations. Since we are discarding 18034 // src value info, don't do the transformation if the memory 18035 // locations are not in the default address space. 18036 LLD->getPointerInfo().getAddrSpace() != 0 || 18037 RLD->getPointerInfo().getAddrSpace() != 0 || 18038 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 18039 LLD->getBasePtr().getValueType())) 18040 return false; 18041 18042 // The loads must not depend on one another. 18043 if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD)) 18044 return false; 18045 18046 // Check that the select condition doesn't reach either load. If so, 18047 // folding this will induce a cycle into the DAG. If not, this is safe to 18048 // xform, so create a select of the addresses. 18049 18050 SmallPtrSet<const SDNode *, 32> Visited; 18051 SmallVector<const SDNode *, 16> Worklist; 18052 18053 // Always fail if LLD and RLD are not independent. TheSelect is a 18054 // predecessor to all Nodes in question so we need not search past it. 18055 18056 Visited.insert(TheSelect); 18057 Worklist.push_back(LLD); 18058 Worklist.push_back(RLD); 18059 18060 if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) || 18061 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)) 18062 return false; 18063 18064 SDValue Addr; 18065 if (TheSelect->getOpcode() == ISD::SELECT) { 18066 // We cannot do this optimization if any pair of {RLD, LLD} is a 18067 // predecessor to {RLD, LLD, CondNode}. As we've already compared the 18068 // Loads, we only need to check if CondNode is a successor to one of the 18069 // loads. We can further avoid this if there's no use of their chain 18070 // value. 18071 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 18072 Worklist.push_back(CondNode); 18073 18074 if ((LLD->hasAnyUseOfValue(1) && 18075 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 18076 (RLD->hasAnyUseOfValue(1) && 18077 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 18078 return false; 18079 18080 Addr = DAG.getSelect(SDLoc(TheSelect), 18081 LLD->getBasePtr().getValueType(), 18082 TheSelect->getOperand(0), LLD->getBasePtr(), 18083 RLD->getBasePtr()); 18084 } else { // Otherwise SELECT_CC 18085 // We cannot do this optimization if any pair of {RLD, LLD} is a 18086 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared 18087 // the Loads, we only need to check if CondLHS/CondRHS is a successor to 18088 // one of the loads. We can further avoid this if there's no use of their 18089 // chain value. 18090 18091 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 18092 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 18093 Worklist.push_back(CondLHS); 18094 Worklist.push_back(CondRHS); 18095 18096 if ((LLD->hasAnyUseOfValue(1) && 18097 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 18098 (RLD->hasAnyUseOfValue(1) && 18099 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 18100 return false; 18101 18102 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 18103 LLD->getBasePtr().getValueType(), 18104 TheSelect->getOperand(0), 18105 TheSelect->getOperand(1), 18106 LLD->getBasePtr(), RLD->getBasePtr(), 18107 TheSelect->getOperand(4)); 18108 } 18109 18110 SDValue Load; 18111 // It is safe to replace the two loads if they have different alignments, 18112 // but the new load must be the minimum (most restrictive) alignment of the 18113 // inputs. 18114 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 18115 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 18116 if (!RLD->isInvariant()) 18117 MMOFlags &= ~MachineMemOperand::MOInvariant; 18118 if (!RLD->isDereferenceable()) 18119 MMOFlags &= ~MachineMemOperand::MODereferenceable; 18120 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 18121 // FIXME: Discards pointer and AA info. 18122 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 18123 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 18124 MMOFlags); 18125 } else { 18126 // FIXME: Discards pointer and AA info. 18127 Load = DAG.getExtLoad( 18128 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 18129 : LLD->getExtensionType(), 18130 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 18131 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 18132 } 18133 18134 // Users of the select now use the result of the load. 18135 CombineTo(TheSelect, Load); 18136 18137 // Users of the old loads now use the new load's chain. We know the 18138 // old-load value is dead now. 18139 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 18140 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 18141 return true; 18142 } 18143 18144 return false; 18145 } 18146 18147 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 18148 /// bitwise 'and'. 18149 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 18150 SDValue N1, SDValue N2, SDValue N3, 18151 ISD::CondCode CC) { 18152 // If this is a select where the false operand is zero and the compare is a 18153 // check of the sign bit, see if we can perform the "gzip trick": 18154 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 18155 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 18156 EVT XType = N0.getValueType(); 18157 EVT AType = N2.getValueType(); 18158 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 18159 return SDValue(); 18160 18161 // If the comparison is testing for a positive value, we have to invert 18162 // the sign bit mask, so only do that transform if the target has a bitwise 18163 // 'and not' instruction (the invert is free). 18164 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 18165 // (X > -1) ? A : 0 18166 // (X > 0) ? X : 0 <-- This is canonical signed max. 18167 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 18168 return SDValue(); 18169 } else if (CC == ISD::SETLT) { 18170 // (X < 0) ? A : 0 18171 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 18172 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 18173 return SDValue(); 18174 } else { 18175 return SDValue(); 18176 } 18177 18178 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 18179 // constant. 18180 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 18181 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 18182 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 18183 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 18184 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 18185 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 18186 AddToWorklist(Shift.getNode()); 18187 18188 if (XType.bitsGT(AType)) { 18189 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 18190 AddToWorklist(Shift.getNode()); 18191 } 18192 18193 if (CC == ISD::SETGT) 18194 Shift = DAG.getNOT(DL, Shift, AType); 18195 18196 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 18197 } 18198 18199 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 18200 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 18201 AddToWorklist(Shift.getNode()); 18202 18203 if (XType.bitsGT(AType)) { 18204 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 18205 AddToWorklist(Shift.getNode()); 18206 } 18207 18208 if (CC == ISD::SETGT) 18209 Shift = DAG.getNOT(DL, Shift, AType); 18210 18211 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 18212 } 18213 18214 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 18215 /// where 'cond' is the comparison specified by CC. 18216 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 18217 SDValue N2, SDValue N3, ISD::CondCode CC, 18218 bool NotExtCompare) { 18219 // (x ? y : y) -> y. 18220 if (N2 == N3) return N2; 18221 18222 EVT VT = N2.getValueType(); 18223 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 18224 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 18225 18226 // Determine if the condition we're dealing with is constant 18227 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 18228 N0, N1, CC, DL, false); 18229 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 18230 18231 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 18232 // fold select_cc true, x, y -> x 18233 // fold select_cc false, x, y -> y 18234 return !SCCC->isNullValue() ? N2 : N3; 18235 } 18236 18237 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 18238 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 18239 // in it. This is a win when the constant is not otherwise available because 18240 // it replaces two constant pool loads with one. We only do this if the FP 18241 // type is known to be legal, because if it isn't, then we are before legalize 18242 // types an we want the other legalization to happen first (e.g. to avoid 18243 // messing with soft float) and if the ConstantFP is not legal, because if 18244 // it is legal, we may not need to store the FP constant in a constant pool. 18245 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 18246 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 18247 if (TLI.isTypeLegal(N2.getValueType()) && 18248 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 18249 TargetLowering::Legal && 18250 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 18251 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 18252 // If both constants have multiple uses, then we won't need to do an 18253 // extra load, they are likely around in registers for other users. 18254 (TV->hasOneUse() || FV->hasOneUse())) { 18255 Constant *Elts[] = { 18256 const_cast<ConstantFP*>(FV->getConstantFPValue()), 18257 const_cast<ConstantFP*>(TV->getConstantFPValue()) 18258 }; 18259 Type *FPTy = Elts[0]->getType(); 18260 const DataLayout &TD = DAG.getDataLayout(); 18261 18262 // Create a ConstantArray of the two constants. 18263 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 18264 SDValue CPIdx = 18265 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 18266 TD.getPrefTypeAlignment(FPTy)); 18267 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 18268 18269 // Get the offsets to the 0 and 1 element of the array so that we can 18270 // select between them. 18271 SDValue Zero = DAG.getIntPtrConstant(0, DL); 18272 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 18273 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 18274 18275 SDValue Cond = DAG.getSetCC(DL, 18276 getSetCCResultType(N0.getValueType()), 18277 N0, N1, CC); 18278 AddToWorklist(Cond.getNode()); 18279 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 18280 Cond, One, Zero); 18281 AddToWorklist(CstOffset.getNode()); 18282 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 18283 CstOffset); 18284 AddToWorklist(CPIdx.getNode()); 18285 return DAG.getLoad( 18286 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 18287 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 18288 Alignment); 18289 } 18290 } 18291 18292 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 18293 return V; 18294 18295 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 18296 // where y is has a single bit set. 18297 // A plaintext description would be, we can turn the SELECT_CC into an AND 18298 // when the condition can be materialized as an all-ones register. Any 18299 // single bit-test can be materialized as an all-ones register with 18300 // shift-left and shift-right-arith. 18301 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 18302 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 18303 SDValue AndLHS = N0->getOperand(0); 18304 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 18305 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 18306 // Shift the tested bit over the sign bit. 18307 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 18308 SDValue ShlAmt = 18309 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 18310 getShiftAmountTy(AndLHS.getValueType())); 18311 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 18312 18313 // Now arithmetic right shift it all the way over, so the result is either 18314 // all-ones, or zero. 18315 SDValue ShrAmt = 18316 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 18317 getShiftAmountTy(Shl.getValueType())); 18318 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 18319 18320 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 18321 } 18322 } 18323 18324 // fold select C, 16, 0 -> shl C, 4 18325 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 18326 TLI.getBooleanContents(N0.getValueType()) == 18327 TargetLowering::ZeroOrOneBooleanContent) { 18328 18329 // If the caller doesn't want us to simplify this into a zext of a compare, 18330 // don't do it. 18331 if (NotExtCompare && N2C->isOne()) 18332 return SDValue(); 18333 18334 // Get a SetCC of the condition 18335 // NOTE: Don't create a SETCC if it's not legal on this target. 18336 if (!LegalOperations || 18337 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 18338 SDValue Temp, SCC; 18339 // cast from setcc result type to select result type 18340 if (LegalTypes) { 18341 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 18342 N0, N1, CC); 18343 if (N2.getValueType().bitsLT(SCC.getValueType())) 18344 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 18345 N2.getValueType()); 18346 else 18347 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 18348 N2.getValueType(), SCC); 18349 } else { 18350 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 18351 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 18352 N2.getValueType(), SCC); 18353 } 18354 18355 AddToWorklist(SCC.getNode()); 18356 AddToWorklist(Temp.getNode()); 18357 18358 if (N2C->isOne()) 18359 return Temp; 18360 18361 // shl setcc result by log2 n2c 18362 return DAG.getNode( 18363 ISD::SHL, DL, N2.getValueType(), Temp, 18364 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 18365 getShiftAmountTy(Temp.getValueType()))); 18366 } 18367 } 18368 18369 // Check to see if this is an integer abs. 18370 // select_cc setg[te] X, 0, X, -X -> 18371 // select_cc setgt X, -1, X, -X -> 18372 // select_cc setl[te] X, 0, -X, X -> 18373 // select_cc setlt X, 1, -X, X -> 18374 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 18375 if (N1C) { 18376 ConstantSDNode *SubC = nullptr; 18377 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 18378 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 18379 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 18380 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 18381 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 18382 (N1C->isOne() && CC == ISD::SETLT)) && 18383 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 18384 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 18385 18386 EVT XType = N0.getValueType(); 18387 if (SubC && SubC->isNullValue() && XType.isInteger()) { 18388 SDLoc DL(N0); 18389 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 18390 N0, 18391 DAG.getConstant(XType.getSizeInBits() - 1, DL, 18392 getShiftAmountTy(N0.getValueType()))); 18393 SDValue Add = DAG.getNode(ISD::ADD, DL, 18394 XType, N0, Shift); 18395 AddToWorklist(Shift.getNode()); 18396 AddToWorklist(Add.getNode()); 18397 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 18398 } 18399 } 18400 18401 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 18402 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 18403 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 18404 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 18405 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 18406 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 18407 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 18408 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 18409 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 18410 SDValue ValueOnZero = N2; 18411 SDValue Count = N3; 18412 // If the condition is NE instead of E, swap the operands. 18413 if (CC == ISD::SETNE) 18414 std::swap(ValueOnZero, Count); 18415 // Check if the value on zero is a constant equal to the bits in the type. 18416 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 18417 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 18418 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 18419 // legal, combine to just cttz. 18420 if ((Count.getOpcode() == ISD::CTTZ || 18421 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 18422 N0 == Count.getOperand(0) && 18423 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 18424 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 18425 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 18426 // legal, combine to just ctlz. 18427 if ((Count.getOpcode() == ISD::CTLZ || 18428 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 18429 N0 == Count.getOperand(0) && 18430 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 18431 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 18432 } 18433 } 18434 } 18435 18436 return SDValue(); 18437 } 18438 18439 /// This is a stub for TargetLowering::SimplifySetCC. 18440 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 18441 ISD::CondCode Cond, const SDLoc &DL, 18442 bool foldBooleans) { 18443 TargetLowering::DAGCombinerInfo 18444 DagCombineInfo(DAG, Level, false, this); 18445 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 18446 } 18447 18448 /// Given an ISD::SDIV node expressing a divide by constant, return 18449 /// a DAG expression to select that will generate the same value by multiplying 18450 /// by a magic number. 18451 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18452 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 18453 // when optimising for minimum size, we don't want to expand a div to a mul 18454 // and a shift. 18455 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18456 return SDValue(); 18457 18458 SmallVector<SDNode *, 8> Built; 18459 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { 18460 for (SDNode *N : Built) 18461 AddToWorklist(N); 18462 return S; 18463 } 18464 18465 return SDValue(); 18466 } 18467 18468 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 18469 /// DAG expression that will generate the same value by right shifting. 18470 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 18471 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 18472 if (!C) 18473 return SDValue(); 18474 18475 // Avoid division by zero. 18476 if (C->isNullValue()) 18477 return SDValue(); 18478 18479 SmallVector<SDNode *, 8> Built; 18480 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { 18481 for (SDNode *N : Built) 18482 AddToWorklist(N); 18483 return S; 18484 } 18485 18486 return SDValue(); 18487 } 18488 18489 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 18490 /// expression that will generate the same value by multiplying by a magic 18491 /// number. 18492 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 18493 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 18494 // when optimising for minimum size, we don't want to expand a div to a mul 18495 // and a shift. 18496 if (DAG.getMachineFunction().getFunction().optForMinSize()) 18497 return SDValue(); 18498 18499 SmallVector<SDNode *, 8> Built; 18500 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { 18501 for (SDNode *N : Built) 18502 AddToWorklist(N); 18503 return S; 18504 } 18505 18506 return SDValue(); 18507 } 18508 18509 /// Determines the LogBase2 value for a non-null input value using the 18510 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 18511 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 18512 EVT VT = V.getValueType(); 18513 unsigned EltBits = VT.getScalarSizeInBits(); 18514 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 18515 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 18516 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 18517 return LogBase2; 18518 } 18519 18520 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18521 /// For the reciprocal, we need to find the zero of the function: 18522 /// F(X) = A X - 1 [which has a zero at X = 1/A] 18523 /// => 18524 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 18525 /// does not require additional intermediate precision] 18526 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 18527 if (Level >= AfterLegalizeDAG) 18528 return SDValue(); 18529 18530 // TODO: Handle half and/or extended types? 18531 EVT VT = Op.getValueType(); 18532 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18533 return SDValue(); 18534 18535 // If estimates are explicitly disabled for this function, we're done. 18536 MachineFunction &MF = DAG.getMachineFunction(); 18537 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 18538 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18539 return SDValue(); 18540 18541 // Estimates may be explicitly enabled for this type with a custom number of 18542 // refinement steps. 18543 int Iterations = TLI.getDivRefinementSteps(VT, MF); 18544 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 18545 AddToWorklist(Est.getNode()); 18546 18547 if (Iterations) { 18548 EVT VT = Op.getValueType(); 18549 SDLoc DL(Op); 18550 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 18551 18552 // Newton iterations: Est = Est + Est (1 - Arg * Est) 18553 for (int i = 0; i < Iterations; ++i) { 18554 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 18555 AddToWorklist(NewEst.getNode()); 18556 18557 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 18558 AddToWorklist(NewEst.getNode()); 18559 18560 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18561 AddToWorklist(NewEst.getNode()); 18562 18563 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 18564 AddToWorklist(Est.getNode()); 18565 } 18566 } 18567 return Est; 18568 } 18569 18570 return SDValue(); 18571 } 18572 18573 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18574 /// For the reciprocal sqrt, we need to find the zero of the function: 18575 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18576 /// => 18577 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 18578 /// As a result, we precompute A/2 prior to the iteration loop. 18579 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 18580 unsigned Iterations, 18581 SDNodeFlags Flags, bool Reciprocal) { 18582 EVT VT = Arg.getValueType(); 18583 SDLoc DL(Arg); 18584 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 18585 18586 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 18587 // this entire sequence requires only one FP constant. 18588 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 18589 AddToWorklist(HalfArg.getNode()); 18590 18591 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 18592 AddToWorklist(HalfArg.getNode()); 18593 18594 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 18595 for (unsigned i = 0; i < Iterations; ++i) { 18596 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 18597 AddToWorklist(NewEst.getNode()); 18598 18599 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 18600 AddToWorklist(NewEst.getNode()); 18601 18602 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 18603 AddToWorklist(NewEst.getNode()); 18604 18605 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 18606 AddToWorklist(Est.getNode()); 18607 } 18608 18609 // If non-reciprocal square root is requested, multiply the result by Arg. 18610 if (!Reciprocal) { 18611 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 18612 AddToWorklist(Est.getNode()); 18613 } 18614 18615 return Est; 18616 } 18617 18618 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 18619 /// For the reciprocal sqrt, we need to find the zero of the function: 18620 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 18621 /// => 18622 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 18623 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 18624 unsigned Iterations, 18625 SDNodeFlags Flags, bool Reciprocal) { 18626 EVT VT = Arg.getValueType(); 18627 SDLoc DL(Arg); 18628 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 18629 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 18630 18631 // This routine must enter the loop below to work correctly 18632 // when (Reciprocal == false). 18633 assert(Iterations > 0); 18634 18635 // Newton iterations for reciprocal square root: 18636 // E = (E * -0.5) * ((A * E) * E + -3.0) 18637 for (unsigned i = 0; i < Iterations; ++i) { 18638 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 18639 AddToWorklist(AE.getNode()); 18640 18641 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 18642 AddToWorklist(AEE.getNode()); 18643 18644 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 18645 AddToWorklist(RHS.getNode()); 18646 18647 // When calculating a square root at the last iteration build: 18648 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 18649 // (notice a common subexpression) 18650 SDValue LHS; 18651 if (Reciprocal || (i + 1) < Iterations) { 18652 // RSQRT: LHS = (E * -0.5) 18653 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 18654 } else { 18655 // SQRT: LHS = (A * E) * -0.5 18656 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 18657 } 18658 AddToWorklist(LHS.getNode()); 18659 18660 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 18661 AddToWorklist(Est.getNode()); 18662 } 18663 18664 return Est; 18665 } 18666 18667 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 18668 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 18669 /// Op can be zero. 18670 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 18671 bool Reciprocal) { 18672 if (Level >= AfterLegalizeDAG) 18673 return SDValue(); 18674 18675 // TODO: Handle half and/or extended types? 18676 EVT VT = Op.getValueType(); 18677 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 18678 return SDValue(); 18679 18680 // If estimates are explicitly disabled for this function, we're done. 18681 MachineFunction &MF = DAG.getMachineFunction(); 18682 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 18683 if (Enabled == TLI.ReciprocalEstimate::Disabled) 18684 return SDValue(); 18685 18686 // Estimates may be explicitly enabled for this type with a custom number of 18687 // refinement steps. 18688 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 18689 18690 bool UseOneConstNR = false; 18691 if (SDValue Est = 18692 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 18693 Reciprocal)) { 18694 AddToWorklist(Est.getNode()); 18695 18696 if (Iterations) { 18697 Est = UseOneConstNR 18698 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 18699 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 18700 18701 if (!Reciprocal) { 18702 // The estimate is now completely wrong if the input was exactly 0.0 or 18703 // possibly a denormal. Force the answer to 0.0 for those cases. 18704 EVT VT = Op.getValueType(); 18705 SDLoc DL(Op); 18706 EVT CCVT = getSetCCResultType(VT); 18707 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; 18708 const Function &F = DAG.getMachineFunction().getFunction(); 18709 Attribute Denorms = F.getFnAttribute("denormal-fp-math"); 18710 if (Denorms.getValueAsString().equals("ieee")) { 18711 // fabs(X) < SmallestNormal ? 0.0 : Est 18712 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 18713 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 18714 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 18715 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18716 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 18717 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 18718 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est); 18719 AddToWorklist(Fabs.getNode()); 18720 AddToWorklist(IsDenorm.getNode()); 18721 AddToWorklist(Est.getNode()); 18722 } else { 18723 // X == 0.0 ? 0.0 : Est 18724 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 18725 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 18726 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est); 18727 AddToWorklist(IsZero.getNode()); 18728 AddToWorklist(Est.getNode()); 18729 } 18730 } 18731 } 18732 return Est; 18733 } 18734 18735 return SDValue(); 18736 } 18737 18738 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18739 return buildSqrtEstimateImpl(Op, Flags, true); 18740 } 18741 18742 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 18743 return buildSqrtEstimateImpl(Op, Flags, false); 18744 } 18745 18746 /// Return true if there is any possibility that the two addresses overlap. 18747 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 18748 // If they are the same then they must be aliases. 18749 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 18750 18751 // If they are both volatile then they cannot be reordered. 18752 if (Op0->isVolatile() && Op1->isVolatile()) return true; 18753 18754 // If one operation reads from invariant memory, and the other may store, they 18755 // cannot alias. These should really be checking the equivalent of mayWrite, 18756 // but it only matters for memory nodes other than load /store. 18757 if (Op0->isInvariant() && Op1->writeMem()) 18758 return false; 18759 18760 if (Op1->isInvariant() && Op0->writeMem()) 18761 return false; 18762 18763 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 18764 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 18765 18766 // Check for BaseIndexOffset matching. 18767 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG); 18768 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG); 18769 int64_t PtrDiff; 18770 if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) { 18771 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 18772 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 18773 18774 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 18775 // able to calculate their relative offset if at least one arises 18776 // from an alloca. However, these allocas cannot overlap and we 18777 // can infer there is no alias. 18778 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 18779 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 18780 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 18781 // If the base are the same frame index but the we couldn't find a 18782 // constant offset, (indices are different) be conservative. 18783 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 18784 !MFI.isFixedObjectIndex(B->getIndex()))) 18785 return false; 18786 } 18787 18788 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase()); 18789 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase()); 18790 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase()); 18791 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase()); 18792 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase()); 18793 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase()); 18794 18795 // If of mismatched base types or checkable indices we can check 18796 // they do not alias. 18797 if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) || 18798 (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) && 18799 (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) 18800 return false; 18801 } 18802 18803 // If we know required SrcValue1 and SrcValue2 have relatively large 18804 // alignment compared to the size and offset of the access, we may be able 18805 // to prove they do not alias. This check is conservative for now to catch 18806 // cases created by splitting vector types. 18807 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 18808 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 18809 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 18810 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 18811 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 18812 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 18813 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 18814 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 18815 18816 // There is no overlap between these relatively aligned accesses of 18817 // similar size. Return no alias. 18818 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 18819 (OffAlign1 + NumBytes1) <= OffAlign0) 18820 return false; 18821 } 18822 18823 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 18824 ? CombinerGlobalAA 18825 : DAG.getSubtarget().useAA(); 18826 #ifndef NDEBUG 18827 if (CombinerAAOnlyFunc.getNumOccurrences() && 18828 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 18829 UseAA = false; 18830 #endif 18831 18832 if (UseAA && AA && 18833 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 18834 // Use alias analysis information. 18835 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 18836 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 18837 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 18838 AliasResult AAResult = 18839 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 18840 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 18841 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 18842 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 18843 if (AAResult == NoAlias) 18844 return false; 18845 } 18846 18847 // Otherwise we have to assume they alias. 18848 return true; 18849 } 18850 18851 /// Walk up chain skipping non-aliasing memory nodes, 18852 /// looking for aliasing nodes and adding them to the Aliases vector. 18853 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 18854 SmallVectorImpl<SDValue> &Aliases) { 18855 SmallVector<SDValue, 8> Chains; // List of chains to visit. 18856 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 18857 18858 // Get alias information for node. 18859 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 18860 18861 // Starting off. 18862 Chains.push_back(OriginalChain); 18863 unsigned Depth = 0; 18864 18865 // Look at each chain and determine if it is an alias. If so, add it to the 18866 // aliases list. If not, then continue up the chain looking for the next 18867 // candidate. 18868 while (!Chains.empty()) { 18869 SDValue Chain = Chains.pop_back_val(); 18870 18871 // For TokenFactor nodes, look at each operand and only continue up the 18872 // chain until we reach the depth limit. 18873 // 18874 // FIXME: The depth check could be made to return the last non-aliasing 18875 // chain we found before we hit a tokenfactor rather than the original 18876 // chain. 18877 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 18878 Aliases.clear(); 18879 Aliases.push_back(OriginalChain); 18880 return; 18881 } 18882 18883 // Don't bother if we've been before. 18884 if (!Visited.insert(Chain.getNode()).second) 18885 continue; 18886 18887 switch (Chain.getOpcode()) { 18888 case ISD::EntryToken: 18889 // Entry token is ideal chain operand, but handled in FindBetterChain. 18890 break; 18891 18892 case ISD::LOAD: 18893 case ISD::STORE: { 18894 // Get alias information for Chain. 18895 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 18896 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 18897 18898 // If chain is alias then stop here. 18899 if (!(IsLoad && IsOpLoad) && 18900 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 18901 Aliases.push_back(Chain); 18902 } else { 18903 // Look further up the chain. 18904 Chains.push_back(Chain.getOperand(0)); 18905 ++Depth; 18906 } 18907 break; 18908 } 18909 18910 case ISD::TokenFactor: 18911 // We have to check each of the operands of the token factor for "small" 18912 // token factors, so we queue them up. Adding the operands to the queue 18913 // (stack) in reverse order maintains the original order and increases the 18914 // likelihood that getNode will find a matching token factor (CSE.) 18915 if (Chain.getNumOperands() > 16) { 18916 Aliases.push_back(Chain); 18917 break; 18918 } 18919 for (unsigned n = Chain.getNumOperands(); n;) 18920 Chains.push_back(Chain.getOperand(--n)); 18921 ++Depth; 18922 break; 18923 18924 case ISD::CopyFromReg: 18925 // Forward past CopyFromReg. 18926 Chains.push_back(Chain.getOperand(0)); 18927 ++Depth; 18928 break; 18929 18930 default: 18931 // For all other instructions we will just have to take what we can get. 18932 Aliases.push_back(Chain); 18933 break; 18934 } 18935 } 18936 } 18937 18938 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 18939 /// (aliasing node.) 18940 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 18941 if (OptLevel == CodeGenOpt::None) 18942 return OldChain; 18943 18944 // Ops for replacing token factor. 18945 SmallVector<SDValue, 8> Aliases; 18946 18947 // Accumulate all the aliases to this node. 18948 GatherAllAliases(N, OldChain, Aliases); 18949 18950 // If no operands then chain to entry token. 18951 if (Aliases.size() == 0) 18952 return DAG.getEntryNode(); 18953 18954 // If a single operand then chain to it. We don't need to revisit it. 18955 if (Aliases.size() == 1) 18956 return Aliases[0]; 18957 18958 // Construct a custom tailored token factor. 18959 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 18960 } 18961 18962 // This function tries to collect a bunch of potentially interesting 18963 // nodes to improve the chains of, all at once. This might seem 18964 // redundant, as this function gets called when visiting every store 18965 // node, so why not let the work be done on each store as it's visited? 18966 // 18967 // I believe this is mainly important because MergeConsecutiveStores 18968 // is unable to deal with merging stores of different sizes, so unless 18969 // we improve the chains of all the potential candidates up-front 18970 // before running MergeConsecutiveStores, it might only see some of 18971 // the nodes that will eventually be candidates, and then not be able 18972 // to go from a partially-merged state to the desired final 18973 // fully-merged state. 18974 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 18975 if (OptLevel == CodeGenOpt::None) 18976 return false; 18977 18978 // This holds the base pointer, index, and the offset in bytes from the base 18979 // pointer. 18980 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 18981 18982 // We must have a base and an offset. 18983 if (!BasePtr.getBase().getNode()) 18984 return false; 18985 18986 // Do not handle stores to undef base pointers. 18987 if (BasePtr.getBase().isUndef()) 18988 return false; 18989 18990 SmallVector<StoreSDNode *, 8> ChainedStores; 18991 ChainedStores.push_back(St); 18992 18993 // Walk up the chain and look for nodes with offsets from the same 18994 // base pointer. Stop when reaching an instruction with a different kind 18995 // or instruction which has a different base pointer. 18996 StoreSDNode *Index = St; 18997 while (Index) { 18998 // If the chain has more than one use, then we can't reorder the mem ops. 18999 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 19000 break; 19001 19002 if (Index->isVolatile() || Index->isIndexed()) 19003 break; 19004 19005 // Find the base pointer and offset for this memory node. 19006 BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG); 19007 19008 // Check that the base pointer is the same as the original one. 19009 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 19010 break; 19011 19012 // Walk up the chain to find the next store node, ignoring any 19013 // intermediate loads. Any other kind of node will halt the loop. 19014 SDNode *NextInChain = Index->getChain().getNode(); 19015 while (true) { 19016 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 19017 // We found a store node. Use it for the next iteration. 19018 if (STn->isVolatile() || STn->isIndexed()) { 19019 Index = nullptr; 19020 break; 19021 } 19022 ChainedStores.push_back(STn); 19023 Index = STn; 19024 break; 19025 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 19026 NextInChain = Ldn->getChain().getNode(); 19027 continue; 19028 } else { 19029 Index = nullptr; 19030 break; 19031 } 19032 }// end while 19033 } 19034 19035 // At this point, ChainedStores lists all of the Store nodes 19036 // reachable by iterating up through chain nodes matching the above 19037 // conditions. For each such store identified, try to find an 19038 // earlier chain to attach the store to which won't violate the 19039 // required ordering. 19040 bool MadeChangeToSt = false; 19041 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 19042 19043 for (StoreSDNode *ChainedStore : ChainedStores) { 19044 SDValue Chain = ChainedStore->getChain(); 19045 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 19046 19047 if (Chain != BetterChain) { 19048 if (ChainedStore == St) 19049 MadeChangeToSt = true; 19050 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 19051 } 19052 } 19053 19054 // Do all replacements after finding the replacements to make to avoid making 19055 // the chains more complicated by introducing new TokenFactors. 19056 for (auto Replacement : BetterChains) 19057 replaceStoreChain(Replacement.first, Replacement.second); 19058 19059 return MadeChangeToSt; 19060 } 19061 19062 /// This is the entry point for the file. 19063 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 19064 CodeGenOpt::Level OptLevel) { 19065 /// This is the main entry point to this class. 19066 DAGCombiner(*this, AA, OptLevel).Run(Level); 19067 } 19068