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/MachineValueType.h" 40 #include "llvm/CodeGen/RuntimeLibcalls.h" 41 #include "llvm/CodeGen/SelectionDAG.h" 42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 43 #include "llvm/CodeGen/SelectionDAGNodes.h" 44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 45 #include "llvm/CodeGen/TargetLowering.h" 46 #include "llvm/CodeGen/TargetRegisterInfo.h" 47 #include "llvm/CodeGen/TargetSubtargetInfo.h" 48 #include "llvm/CodeGen/ValueTypes.h" 49 #include "llvm/IR/Attributes.h" 50 #include "llvm/IR/Constant.h" 51 #include "llvm/IR/DataLayout.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Compiler.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/KnownBits.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetMachine.h" 66 #include "llvm/Target/TargetOptions.h" 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 #include <vector> 76 77 using namespace llvm; 78 79 #define DEBUG_TYPE "dagcombine" 80 81 STATISTIC(NodesCombined , "Number of dag nodes combined"); 82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 84 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 85 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 86 STATISTIC(SlicedLoads, "Number of load sliced"); 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 /// \brief 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 /// \brief 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 /// \brief 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 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 236 237 bool CombineToPreIndexedLoadStore(SDNode *N); 238 bool CombineToPostIndexedLoadStore(SDNode *N); 239 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 240 bool SliceUpLoad(SDNode *N); 241 242 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 243 /// load. 244 /// 245 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 246 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 247 /// \param EltNo index of the vector element to load. 248 /// \param OriginalLoad load that EVE came from to be replaced. 249 /// \returns EVE on success SDValue() on failure. 250 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 251 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 252 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 253 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 254 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 255 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 256 SDValue PromoteIntBinOp(SDValue Op); 257 SDValue PromoteIntShiftOp(SDValue Op); 258 SDValue PromoteExtend(SDValue Op); 259 bool PromoteLoad(SDValue Op); 260 261 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 262 SDValue ExtLoad, const SDLoc &DL, 263 ISD::NodeType ExtType); 264 265 /// Call the node-specific routine that knows how to fold each 266 /// particular type of node. If that doesn't do anything, try the 267 /// target-specific DAG combines. 268 SDValue combine(SDNode *N); 269 270 // Visitation implementation - Implement dag node combining for different 271 // node types. The semantics are as follows: 272 // Return Value: 273 // SDValue.getNode() == 0 - No change was made 274 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 275 // otherwise - N should be replaced by the returned Operand. 276 // 277 SDValue visitTokenFactor(SDNode *N); 278 SDValue visitMERGE_VALUES(SDNode *N); 279 SDValue visitADD(SDNode *N); 280 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 281 SDValue visitSUB(SDNode *N); 282 SDValue visitADDC(SDNode *N); 283 SDValue visitUADDO(SDNode *N); 284 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 285 SDValue visitSUBC(SDNode *N); 286 SDValue visitUSUBO(SDNode *N); 287 SDValue visitADDE(SDNode *N); 288 SDValue visitADDCARRY(SDNode *N); 289 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 290 SDValue visitSUBE(SDNode *N); 291 SDValue visitSUBCARRY(SDNode *N); 292 SDValue visitMUL(SDNode *N); 293 SDValue useDivRem(SDNode *N); 294 SDValue visitSDIV(SDNode *N); 295 SDValue visitUDIV(SDNode *N); 296 SDValue visitREM(SDNode *N); 297 SDValue visitMULHU(SDNode *N); 298 SDValue visitMULHS(SDNode *N); 299 SDValue visitSMUL_LOHI(SDNode *N); 300 SDValue visitUMUL_LOHI(SDNode *N); 301 SDValue visitSMULO(SDNode *N); 302 SDValue visitUMULO(SDNode *N); 303 SDValue visitIMINMAX(SDNode *N); 304 SDValue visitAND(SDNode *N); 305 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 306 SDValue visitOR(SDNode *N); 307 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 308 SDValue visitXOR(SDNode *N); 309 SDValue SimplifyVBinOp(SDNode *N); 310 SDValue visitSHL(SDNode *N); 311 SDValue visitSRA(SDNode *N); 312 SDValue visitSRL(SDNode *N); 313 SDValue visitRotate(SDNode *N); 314 SDValue visitABS(SDNode *N); 315 SDValue visitBSWAP(SDNode *N); 316 SDValue visitBITREVERSE(SDNode *N); 317 SDValue visitCTLZ(SDNode *N); 318 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 319 SDValue visitCTTZ(SDNode *N); 320 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 321 SDValue visitCTPOP(SDNode *N); 322 SDValue visitSELECT(SDNode *N); 323 SDValue visitVSELECT(SDNode *N); 324 SDValue visitSELECT_CC(SDNode *N); 325 SDValue visitSETCC(SDNode *N); 326 SDValue visitSETCCE(SDNode *N); 327 SDValue visitSETCCCARRY(SDNode *N); 328 SDValue visitSIGN_EXTEND(SDNode *N); 329 SDValue visitZERO_EXTEND(SDNode *N); 330 SDValue visitANY_EXTEND(SDNode *N); 331 SDValue visitAssertExt(SDNode *N); 332 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 333 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 334 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 335 SDValue visitTRUNCATE(SDNode *N); 336 SDValue visitBITCAST(SDNode *N); 337 SDValue visitBUILD_PAIR(SDNode *N); 338 SDValue visitFADD(SDNode *N); 339 SDValue visitFSUB(SDNode *N); 340 SDValue visitFMUL(SDNode *N); 341 SDValue visitFMA(SDNode *N); 342 SDValue visitFDIV(SDNode *N); 343 SDValue visitFREM(SDNode *N); 344 SDValue visitFSQRT(SDNode *N); 345 SDValue visitFCOPYSIGN(SDNode *N); 346 SDValue visitSINT_TO_FP(SDNode *N); 347 SDValue visitUINT_TO_FP(SDNode *N); 348 SDValue visitFP_TO_SINT(SDNode *N); 349 SDValue visitFP_TO_UINT(SDNode *N); 350 SDValue visitFP_ROUND(SDNode *N); 351 SDValue visitFP_ROUND_INREG(SDNode *N); 352 SDValue visitFP_EXTEND(SDNode *N); 353 SDValue visitFNEG(SDNode *N); 354 SDValue visitFABS(SDNode *N); 355 SDValue visitFCEIL(SDNode *N); 356 SDValue visitFTRUNC(SDNode *N); 357 SDValue visitFFLOOR(SDNode *N); 358 SDValue visitFMINNUM(SDNode *N); 359 SDValue visitFMAXNUM(SDNode *N); 360 SDValue visitBRCOND(SDNode *N); 361 SDValue visitBR_CC(SDNode *N); 362 SDValue visitLOAD(SDNode *N); 363 364 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 365 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 366 367 SDValue visitSTORE(SDNode *N); 368 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 369 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 370 SDValue visitBUILD_VECTOR(SDNode *N); 371 SDValue visitCONCAT_VECTORS(SDNode *N); 372 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 373 SDValue visitVECTOR_SHUFFLE(SDNode *N); 374 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 375 SDValue visitINSERT_SUBVECTOR(SDNode *N); 376 SDValue visitMLOAD(SDNode *N); 377 SDValue visitMSTORE(SDNode *N); 378 SDValue visitMGATHER(SDNode *N); 379 SDValue visitMSCATTER(SDNode *N); 380 SDValue visitFP_TO_FP16(SDNode *N); 381 SDValue visitFP16_TO_FP(SDNode *N); 382 383 SDValue visitFADDForFMACombine(SDNode *N); 384 SDValue visitFSUBForFMACombine(SDNode *N); 385 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 386 387 SDValue XformToShuffleWithZero(SDNode *N); 388 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 389 SDValue RHS); 390 391 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 392 393 SDValue foldSelectOfConstants(SDNode *N); 394 SDValue foldVSelectOfConstants(SDNode *N); 395 SDValue foldBinOpIntoSelect(SDNode *BO); 396 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 397 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 398 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 399 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 400 SDValue N2, SDValue N3, ISD::CondCode CC, 401 bool NotExtCompare = false); 402 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 403 SDValue N2, SDValue N3, ISD::CondCode CC); 404 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 405 const SDLoc &DL); 406 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 407 const SDLoc &DL, bool foldBooleans = true); 408 409 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 410 SDValue &CC) const; 411 bool isOneUseSetCC(SDValue N) const; 412 413 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 414 unsigned HiOp); 415 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 416 SDValue CombineExtLoad(SDNode *N); 417 SDValue combineRepeatedFPDivisors(SDNode *N); 418 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 419 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 420 SDValue BuildSDIV(SDNode *N); 421 SDValue BuildSDIVPow2(SDNode *N); 422 SDValue BuildUDIV(SDNode *N); 423 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 424 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 425 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 426 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 427 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 428 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 429 SDNodeFlags Flags, bool Reciprocal); 430 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 431 SDNodeFlags Flags, bool Reciprocal); 432 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 433 bool DemandHighBits = true); 434 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 435 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 436 SDValue InnerPos, SDValue InnerNeg, 437 unsigned PosOpcode, unsigned NegOpcode, 438 const SDLoc &DL); 439 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 440 SDValue MatchLoadCombine(SDNode *N); 441 SDValue ReduceLoadWidth(SDNode *N); 442 SDValue ReduceLoadOpStoreWidth(SDNode *N); 443 SDValue splitMergedValStore(StoreSDNode *ST); 444 SDValue TransformFPLoadStorePair(SDNode *N); 445 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 446 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 447 SDValue reduceBuildVecToShuffle(SDNode *N); 448 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 449 ArrayRef<int> VectorMask, SDValue VecIn1, 450 SDValue VecIn2, unsigned LeftIdx); 451 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 452 453 /// Walk up chain skipping non-aliasing memory nodes, 454 /// looking for aliasing nodes and adding them to the Aliases vector. 455 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 456 SmallVectorImpl<SDValue> &Aliases); 457 458 /// Return true if there is any possibility that the two addresses overlap. 459 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 460 461 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 462 /// chain (aliasing node.) 463 SDValue FindBetterChain(SDNode *N, SDValue Chain); 464 465 /// Try to replace a store and any possibly adjacent stores on 466 /// consecutive chains with better chains. Return true only if St is 467 /// replaced. 468 /// 469 /// Notice that other chains may still be replaced even if the function 470 /// returns false. 471 bool findBetterNeighborChains(StoreSDNode *St); 472 473 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 474 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 475 476 /// Holds a pointer to an LSBaseSDNode as well as information on where it 477 /// is located in a sequence of memory operations connected by a chain. 478 struct MemOpLink { 479 // Ptr to the mem node. 480 LSBaseSDNode *MemNode; 481 482 // Offset from the base ptr. 483 int64_t OffsetFromBase; 484 485 MemOpLink(LSBaseSDNode *N, int64_t Offset) 486 : MemNode(N), OffsetFromBase(Offset) {} 487 }; 488 489 /// This is a helper function for visitMUL to check the profitability 490 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 491 /// MulNode is the original multiply, AddNode is (add x, c1), 492 /// and ConstNode is c2. 493 bool isMulAddWithConstProfitable(SDNode *MulNode, 494 SDValue &AddNode, 495 SDValue &ConstNode); 496 497 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 498 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 499 /// the type of the loaded value to be extended. LoadedVT returns the type 500 /// of the original loaded value. NarrowLoad returns whether the load would 501 /// need to be narrowed in order to match. 502 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 503 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 504 bool &NarrowLoad); 505 506 /// Helper function for MergeConsecutiveStores which merges the 507 /// component store chains. 508 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 509 unsigned NumStores); 510 511 /// This is a helper function for MergeConsecutiveStores. When the 512 /// source elements of the consecutive stores are all constants or 513 /// all extracted vector elements, try to merge them into one 514 /// larger store introducing bitcasts if necessary. \return True 515 /// if a merged store was created. 516 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 517 EVT MemVT, unsigned NumStores, 518 bool IsConstantSrc, bool UseVector, 519 bool UseTrunc); 520 521 /// This is a helper function for MergeConsecutiveStores. Stores 522 /// that potentially may be merged with St are placed in 523 /// StoreNodes. 524 void getStoreMergeCandidates(StoreSDNode *St, 525 SmallVectorImpl<MemOpLink> &StoreNodes); 526 527 /// Helper function for MergeConsecutiveStores. Checks if 528 /// candidate stores have indirect dependency through their 529 /// operands. \return True if safe to merge. 530 bool checkMergeStoreCandidatesForDependencies( 531 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 532 533 /// Merge consecutive store operations into a wide store. 534 /// This optimization uses wide integers or vectors when possible. 535 /// \return number of stores that were merged into a merged store (the 536 /// affected nodes are stored as a prefix in \p StoreNodes). 537 bool MergeConsecutiveStores(StoreSDNode *N); 538 539 /// \brief Try to transform a truncation where C is a constant: 540 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 541 /// 542 /// \p N needs to be a truncation and its first operand an AND. Other 543 /// requirements are checked by the function (e.g. that trunc is 544 /// single-use) and if missed an empty SDValue is returned. 545 SDValue distributeTruncateThroughAnd(SDNode *N); 546 547 public: 548 /// Runs the dag combiner on all nodes in the work list 549 void Run(CombineLevel AtLevel); 550 551 SelectionDAG &getDAG() const { return DAG; } 552 553 /// Returns a type large enough to hold any valid shift amount - before type 554 /// legalization these can be huge. 555 EVT getShiftAmountTy(EVT LHSTy) { 556 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 557 if (LHSTy.isVector()) 558 return LHSTy; 559 auto &DL = DAG.getDataLayout(); 560 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 561 : TLI.getPointerTy(DL); 562 } 563 564 /// This method returns true if we are running before type legalization or 565 /// if the specified VT is legal. 566 bool isTypeLegal(const EVT &VT) { 567 if (!LegalTypes) return true; 568 return TLI.isTypeLegal(VT); 569 } 570 571 /// Convenience wrapper around TargetLowering::getSetCCResultType 572 EVT getSetCCResultType(EVT VT) const { 573 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 574 } 575 }; 576 577 /// This class is a DAGUpdateListener that removes any deleted 578 /// nodes from the worklist. 579 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 580 DAGCombiner &DC; 581 582 public: 583 explicit WorklistRemover(DAGCombiner &dc) 584 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 585 586 void NodeDeleted(SDNode *N, SDNode *E) override { 587 DC.removeFromWorklist(N); 588 } 589 }; 590 591 } // end anonymous namespace 592 593 //===----------------------------------------------------------------------===// 594 // TargetLowering::DAGCombinerInfo implementation 595 //===----------------------------------------------------------------------===// 596 597 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 598 ((DAGCombiner*)DC)->AddToWorklist(N); 599 } 600 601 SDValue TargetLowering::DAGCombinerInfo:: 602 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 603 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 604 } 605 606 SDValue TargetLowering::DAGCombinerInfo:: 607 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 608 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 609 } 610 611 SDValue TargetLowering::DAGCombinerInfo:: 612 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 613 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 614 } 615 616 void TargetLowering::DAGCombinerInfo:: 617 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 618 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 619 } 620 621 //===----------------------------------------------------------------------===// 622 // Helper Functions 623 //===----------------------------------------------------------------------===// 624 625 void DAGCombiner::deleteAndRecombine(SDNode *N) { 626 removeFromWorklist(N); 627 628 // If the operands of this node are only used by the node, they will now be 629 // dead. Make sure to re-visit them and recursively delete dead nodes. 630 for (const SDValue &Op : N->ops()) 631 // For an operand generating multiple values, one of the values may 632 // become dead allowing further simplification (e.g. split index 633 // arithmetic from an indexed load). 634 if (Op->hasOneUse() || Op->getNumValues() > 1) 635 AddToWorklist(Op.getNode()); 636 637 DAG.DeleteNode(N); 638 } 639 640 /// Return 1 if we can compute the negated form of the specified expression for 641 /// the same cost as the expression itself, or 2 if we can compute the negated 642 /// form more cheaply than the expression itself. 643 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 644 const TargetLowering &TLI, 645 const TargetOptions *Options, 646 unsigned Depth = 0) { 647 // fneg is removable even if it has multiple uses. 648 if (Op.getOpcode() == ISD::FNEG) return 2; 649 650 // Don't allow anything with multiple uses. 651 if (!Op.hasOneUse()) return 0; 652 653 // Don't recurse exponentially. 654 if (Depth > 6) return 0; 655 656 switch (Op.getOpcode()) { 657 default: return false; 658 case ISD::ConstantFP: { 659 if (!LegalOperations) 660 return 1; 661 662 // Don't invert constant FP values after legalization unless the target says 663 // the negated constant is legal. 664 EVT VT = Op.getValueType(); 665 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 666 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 667 } 668 case ISD::FADD: 669 // FIXME: determine better conditions for this xform. 670 if (!Options->UnsafeFPMath) return 0; 671 672 // After operation legalization, it might not be legal to create new FSUBs. 673 if (LegalOperations && 674 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 675 return 0; 676 677 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 678 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 679 Options, Depth + 1)) 680 return V; 681 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 682 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 683 Depth + 1); 684 case ISD::FSUB: 685 // We can't turn -(A-B) into B-A when we honor signed zeros. 686 if (!Options->NoSignedZerosFPMath && 687 !Op.getNode()->getFlags().hasNoSignedZeros()) 688 return 0; 689 690 // fold (fneg (fsub A, B)) -> (fsub B, A) 691 return 1; 692 693 case ISD::FMUL: 694 case ISD::FDIV: 695 if (Options->HonorSignDependentRoundingFPMath()) return 0; 696 697 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 698 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 699 Options, Depth + 1)) 700 return V; 701 702 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 703 Depth + 1); 704 705 case ISD::FP_EXTEND: 706 case ISD::FP_ROUND: 707 case ISD::FSIN: 708 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 709 Depth + 1); 710 } 711 } 712 713 /// If isNegatibleForFree returns true, return the newly negated expression. 714 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 715 bool LegalOperations, unsigned Depth = 0) { 716 const TargetOptions &Options = DAG.getTarget().Options; 717 // fneg is removable even if it has multiple uses. 718 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 719 720 // Don't allow anything with multiple uses. 721 assert(Op.hasOneUse() && "Unknown reuse!"); 722 723 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 724 725 const SDNodeFlags Flags = Op.getNode()->getFlags(); 726 727 switch (Op.getOpcode()) { 728 default: llvm_unreachable("Unknown code"); 729 case ISD::ConstantFP: { 730 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 731 V.changeSign(); 732 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 733 } 734 case ISD::FADD: 735 // FIXME: determine better conditions for this xform. 736 assert(Options.UnsafeFPMath); 737 738 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 739 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 740 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 741 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 742 GetNegatedExpression(Op.getOperand(0), DAG, 743 LegalOperations, Depth+1), 744 Op.getOperand(1), Flags); 745 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 746 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 747 GetNegatedExpression(Op.getOperand(1), DAG, 748 LegalOperations, Depth+1), 749 Op.getOperand(0), Flags); 750 case ISD::FSUB: 751 // fold (fneg (fsub 0, B)) -> B 752 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 753 if (N0CFP->isZero()) 754 return Op.getOperand(1); 755 756 // fold (fneg (fsub A, B)) -> (fsub B, A) 757 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 758 Op.getOperand(1), Op.getOperand(0), Flags); 759 760 case ISD::FMUL: 761 case ISD::FDIV: 762 assert(!Options.HonorSignDependentRoundingFPMath()); 763 764 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 765 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 766 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 767 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 768 GetNegatedExpression(Op.getOperand(0), DAG, 769 LegalOperations, Depth+1), 770 Op.getOperand(1), Flags); 771 772 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 773 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 774 Op.getOperand(0), 775 GetNegatedExpression(Op.getOperand(1), DAG, 776 LegalOperations, Depth+1), Flags); 777 778 case ISD::FP_EXTEND: 779 case ISD::FSIN: 780 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 781 GetNegatedExpression(Op.getOperand(0), DAG, 782 LegalOperations, Depth+1)); 783 case ISD::FP_ROUND: 784 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 785 GetNegatedExpression(Op.getOperand(0), DAG, 786 LegalOperations, Depth+1), 787 Op.getOperand(1)); 788 } 789 } 790 791 // APInts must be the same size for most operations, this helper 792 // function zero extends the shorter of the pair so that they match. 793 // We provide an Offset so that we can create bitwidths that won't overflow. 794 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 795 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 796 LHS = LHS.zextOrSelf(Bits); 797 RHS = RHS.zextOrSelf(Bits); 798 } 799 800 // Return true if this node is a setcc, or is a select_cc 801 // that selects between the target values used for true and false, making it 802 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 803 // the appropriate nodes based on the type of node we are checking. This 804 // simplifies life a bit for the callers. 805 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 806 SDValue &CC) const { 807 if (N.getOpcode() == ISD::SETCC) { 808 LHS = N.getOperand(0); 809 RHS = N.getOperand(1); 810 CC = N.getOperand(2); 811 return true; 812 } 813 814 if (N.getOpcode() != ISD::SELECT_CC || 815 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 816 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 817 return false; 818 819 if (TLI.getBooleanContents(N.getValueType()) == 820 TargetLowering::UndefinedBooleanContent) 821 return false; 822 823 LHS = N.getOperand(0); 824 RHS = N.getOperand(1); 825 CC = N.getOperand(4); 826 return true; 827 } 828 829 /// Return true if this is a SetCC-equivalent operation with only one use. 830 /// If this is true, it allows the users to invert the operation for free when 831 /// it is profitable to do so. 832 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 833 SDValue N0, N1, N2; 834 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 835 return true; 836 return false; 837 } 838 839 // \brief Returns the SDNode if it is a constant float BuildVector 840 // or constant float. 841 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 842 if (isa<ConstantFPSDNode>(N)) 843 return N.getNode(); 844 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 845 return N.getNode(); 846 return nullptr; 847 } 848 849 // Determines if it is a constant integer or a build vector of constant 850 // integers (and undefs). 851 // Do not permit build vector implicit truncation. 852 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 853 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 854 return !(Const->isOpaque() && NoOpaques); 855 if (N.getOpcode() != ISD::BUILD_VECTOR) 856 return false; 857 unsigned BitWidth = N.getScalarValueSizeInBits(); 858 for (const SDValue &Op : N->op_values()) { 859 if (Op.isUndef()) 860 continue; 861 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 862 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 863 (Const->isOpaque() && NoOpaques)) 864 return false; 865 } 866 return true; 867 } 868 869 // Determines if it is a constant null integer or a splatted vector of a 870 // constant null integer (with no undefs). 871 // Build vector implicit truncation is not an issue for null values. 872 static bool isNullConstantOrNullSplatConstant(SDValue N) { 873 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 874 return Splat->isNullValue(); 875 return false; 876 } 877 878 // Determines if it is a constant integer of one or a splatted vector of a 879 // constant integer of one (with no undefs). 880 // Do not permit build vector implicit truncation. 881 static bool isOneConstantOrOneSplatConstant(SDValue N) { 882 unsigned BitWidth = N.getScalarValueSizeInBits(); 883 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 884 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 885 return false; 886 } 887 888 // Determines if it is a constant integer of all ones or a splatted vector of a 889 // constant integer of all ones (with no undefs). 890 // Do not permit build vector implicit truncation. 891 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 892 unsigned BitWidth = N.getScalarValueSizeInBits(); 893 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 894 return Splat->isAllOnesValue() && 895 Splat->getAPIntValue().getBitWidth() == BitWidth; 896 return false; 897 } 898 899 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 900 // undef's. 901 static bool isAnyConstantBuildVector(const SDNode *N) { 902 return ISD::isBuildVectorOfConstantSDNodes(N) || 903 ISD::isBuildVectorOfConstantFPSDNodes(N); 904 } 905 906 // Attempt to match a unary predicate against a scalar/splat constant or 907 // every element of a constant BUILD_VECTOR. 908 static bool matchUnaryPredicate(SDValue Op, 909 std::function<bool(ConstantSDNode *)> Match) { 910 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 911 return Match(Cst); 912 913 if (ISD::BUILD_VECTOR != Op.getOpcode()) 914 return false; 915 916 EVT SVT = Op.getValueType().getScalarType(); 917 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 918 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 919 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 920 return false; 921 } 922 return true; 923 } 924 925 // Attempt to match a binary predicate against a pair of scalar/splat constants 926 // or every element of a pair of constant BUILD_VECTORs. 927 static bool matchBinaryPredicate( 928 SDValue LHS, SDValue RHS, 929 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) { 930 if (LHS.getValueType() != RHS.getValueType()) 931 return false; 932 933 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 934 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 935 return Match(LHSCst, RHSCst); 936 937 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 938 ISD::BUILD_VECTOR != RHS.getOpcode()) 939 return false; 940 941 EVT SVT = LHS.getValueType().getScalarType(); 942 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 943 auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i)); 944 auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i)); 945 if (!LHSCst || !RHSCst) 946 return false; 947 if (LHSCst->getValueType(0) != SVT || 948 LHSCst->getValueType(0) != RHSCst->getValueType(0)) 949 return false; 950 if (!Match(LHSCst, RHSCst)) 951 return false; 952 } 953 return true; 954 } 955 956 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 957 SDValue N1) { 958 EVT VT = N0.getValueType(); 959 if (N0.getOpcode() == Opc) { 960 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 961 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 962 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 963 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 964 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 965 return SDValue(); 966 } 967 if (N0.hasOneUse()) { 968 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 969 // use 970 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 971 if (!OpNode.getNode()) 972 return SDValue(); 973 AddToWorklist(OpNode.getNode()); 974 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 975 } 976 } 977 } 978 979 if (N1.getOpcode() == Opc) { 980 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 981 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 982 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 983 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 984 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 985 return SDValue(); 986 } 987 if (N1.hasOneUse()) { 988 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 989 // use 990 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 991 if (!OpNode.getNode()) 992 return SDValue(); 993 AddToWorklist(OpNode.getNode()); 994 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 995 } 996 } 997 } 998 999 return SDValue(); 1000 } 1001 1002 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 1003 bool AddTo) { 1004 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1005 ++NodesCombined; 1006 DEBUG(dbgs() << "\nReplacing.1 "; 1007 N->dump(&DAG); 1008 dbgs() << "\nWith: "; 1009 To[0].getNode()->dump(&DAG); 1010 dbgs() << " and " << NumTo-1 << " other values\n"); 1011 for (unsigned i = 0, e = NumTo; i != e; ++i) 1012 assert((!To[i].getNode() || 1013 N->getValueType(i) == To[i].getValueType()) && 1014 "Cannot combine value to value of different type!"); 1015 1016 WorklistRemover DeadNodes(*this); 1017 DAG.ReplaceAllUsesWith(N, To); 1018 if (AddTo) { 1019 // Push the new nodes and any users onto the worklist 1020 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1021 if (To[i].getNode()) { 1022 AddToWorklist(To[i].getNode()); 1023 AddUsersToWorklist(To[i].getNode()); 1024 } 1025 } 1026 } 1027 1028 // Finally, if the node is now dead, remove it from the graph. The node 1029 // may not be dead if the replacement process recursively simplified to 1030 // something else needing this node. 1031 if (N->use_empty()) 1032 deleteAndRecombine(N); 1033 return SDValue(N, 0); 1034 } 1035 1036 void DAGCombiner:: 1037 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1038 // Replace all uses. If any nodes become isomorphic to other nodes and 1039 // are deleted, make sure to remove them from our worklist. 1040 WorklistRemover DeadNodes(*this); 1041 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1042 1043 // Push the new node and any (possibly new) users onto the worklist. 1044 AddToWorklist(TLO.New.getNode()); 1045 AddUsersToWorklist(TLO.New.getNode()); 1046 1047 // Finally, if the node is now dead, remove it from the graph. The node 1048 // may not be dead if the replacement process recursively simplified to 1049 // something else needing this node. 1050 if (TLO.Old.getNode()->use_empty()) 1051 deleteAndRecombine(TLO.Old.getNode()); 1052 } 1053 1054 /// Check the specified integer node value to see if it can be simplified or if 1055 /// things it uses can be simplified by bit propagation. If so, return true. 1056 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 1057 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1058 KnownBits Known; 1059 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 1060 return false; 1061 1062 // Revisit the node. 1063 AddToWorklist(Op.getNode()); 1064 1065 // Replace the old value with the new one. 1066 ++NodesCombined; 1067 DEBUG(dbgs() << "\nReplacing.2 "; 1068 TLO.Old.getNode()->dump(&DAG); 1069 dbgs() << "\nWith: "; 1070 TLO.New.getNode()->dump(&DAG); 1071 dbgs() << '\n'); 1072 1073 CommitTargetLoweringOpt(TLO); 1074 return true; 1075 } 1076 1077 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1078 SDLoc DL(Load); 1079 EVT VT = Load->getValueType(0); 1080 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1081 1082 DEBUG(dbgs() << "\nReplacing.9 "; 1083 Load->dump(&DAG); 1084 dbgs() << "\nWith: "; 1085 Trunc.getNode()->dump(&DAG); 1086 dbgs() << '\n'); 1087 WorklistRemover DeadNodes(*this); 1088 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1089 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1090 deleteAndRecombine(Load); 1091 AddToWorklist(Trunc.getNode()); 1092 } 1093 1094 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1095 Replace = false; 1096 SDLoc DL(Op); 1097 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1098 LoadSDNode *LD = cast<LoadSDNode>(Op); 1099 EVT MemVT = LD->getMemoryVT(); 1100 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1101 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1102 : ISD::EXTLOAD) 1103 : LD->getExtensionType(); 1104 Replace = true; 1105 return DAG.getExtLoad(ExtType, DL, PVT, 1106 LD->getChain(), LD->getBasePtr(), 1107 MemVT, LD->getMemOperand()); 1108 } 1109 1110 unsigned Opc = Op.getOpcode(); 1111 switch (Opc) { 1112 default: break; 1113 case ISD::AssertSext: 1114 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1115 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1116 break; 1117 case ISD::AssertZext: 1118 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1119 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1120 break; 1121 case ISD::Constant: { 1122 unsigned ExtOpc = 1123 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1124 return DAG.getNode(ExtOpc, DL, PVT, Op); 1125 } 1126 } 1127 1128 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1129 return SDValue(); 1130 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1131 } 1132 1133 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1134 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1135 return SDValue(); 1136 EVT OldVT = Op.getValueType(); 1137 SDLoc DL(Op); 1138 bool Replace = false; 1139 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1140 if (!NewOp.getNode()) 1141 return SDValue(); 1142 AddToWorklist(NewOp.getNode()); 1143 1144 if (Replace) 1145 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1146 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1147 DAG.getValueType(OldVT)); 1148 } 1149 1150 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1151 EVT OldVT = Op.getValueType(); 1152 SDLoc DL(Op); 1153 bool Replace = false; 1154 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1155 if (!NewOp.getNode()) 1156 return SDValue(); 1157 AddToWorklist(NewOp.getNode()); 1158 1159 if (Replace) 1160 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1161 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1162 } 1163 1164 /// Promote the specified integer binary operation if the target indicates it is 1165 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1166 /// i32 since i16 instructions are longer. 1167 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1168 if (!LegalOperations) 1169 return SDValue(); 1170 1171 EVT VT = Op.getValueType(); 1172 if (VT.isVector() || !VT.isInteger()) 1173 return SDValue(); 1174 1175 // If operation type is 'undesirable', e.g. i16 on x86, consider 1176 // promoting it. 1177 unsigned Opc = Op.getOpcode(); 1178 if (TLI.isTypeDesirableForOp(Opc, VT)) 1179 return SDValue(); 1180 1181 EVT PVT = VT; 1182 // Consult target whether it is a good idea to promote this operation and 1183 // what's the right type to promote it to. 1184 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1185 assert(PVT != VT && "Don't know what type to promote to!"); 1186 1187 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1188 1189 bool Replace0 = false; 1190 SDValue N0 = Op.getOperand(0); 1191 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1192 1193 bool Replace1 = false; 1194 SDValue N1 = Op.getOperand(1); 1195 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1196 SDLoc DL(Op); 1197 1198 SDValue RV = 1199 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1200 1201 // We are always replacing N0/N1's use in N and only need 1202 // additional replacements if there are additional uses. 1203 Replace0 &= !N0->hasOneUse(); 1204 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1205 1206 // Combine Op here so it is preserved past replacements. 1207 CombineTo(Op.getNode(), RV); 1208 1209 // If operands have a use ordering, make sure we deal with 1210 // predecessor first. 1211 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1212 std::swap(N0, N1); 1213 std::swap(NN0, NN1); 1214 } 1215 1216 if (Replace0) { 1217 AddToWorklist(NN0.getNode()); 1218 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1219 } 1220 if (Replace1) { 1221 AddToWorklist(NN1.getNode()); 1222 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1223 } 1224 return Op; 1225 } 1226 return SDValue(); 1227 } 1228 1229 /// Promote the specified integer shift operation if the target indicates it is 1230 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1231 /// i32 since i16 instructions are longer. 1232 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1233 if (!LegalOperations) 1234 return SDValue(); 1235 1236 EVT VT = Op.getValueType(); 1237 if (VT.isVector() || !VT.isInteger()) 1238 return SDValue(); 1239 1240 // If operation type is 'undesirable', e.g. i16 on x86, consider 1241 // promoting it. 1242 unsigned Opc = Op.getOpcode(); 1243 if (TLI.isTypeDesirableForOp(Opc, VT)) 1244 return SDValue(); 1245 1246 EVT PVT = VT; 1247 // Consult target whether it is a good idea to promote this operation and 1248 // what's the right type to promote it to. 1249 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1250 assert(PVT != VT && "Don't know what type to promote to!"); 1251 1252 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1253 1254 bool Replace = false; 1255 SDValue N0 = Op.getOperand(0); 1256 SDValue N1 = Op.getOperand(1); 1257 if (Opc == ISD::SRA) 1258 N0 = SExtPromoteOperand(N0, PVT); 1259 else if (Opc == ISD::SRL) 1260 N0 = ZExtPromoteOperand(N0, PVT); 1261 else 1262 N0 = PromoteOperand(N0, PVT, Replace); 1263 1264 if (!N0.getNode()) 1265 return SDValue(); 1266 1267 SDLoc DL(Op); 1268 SDValue RV = 1269 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1270 1271 AddToWorklist(N0.getNode()); 1272 if (Replace) 1273 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1274 1275 // Deal with Op being deleted. 1276 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1277 return RV; 1278 } 1279 return SDValue(); 1280 } 1281 1282 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1283 if (!LegalOperations) 1284 return SDValue(); 1285 1286 EVT VT = Op.getValueType(); 1287 if (VT.isVector() || !VT.isInteger()) 1288 return SDValue(); 1289 1290 // If operation type is 'undesirable', e.g. i16 on x86, consider 1291 // promoting it. 1292 unsigned Opc = Op.getOpcode(); 1293 if (TLI.isTypeDesirableForOp(Opc, VT)) 1294 return SDValue(); 1295 1296 EVT PVT = VT; 1297 // Consult target whether it is a good idea to promote this operation and 1298 // what's the right type to promote it to. 1299 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1300 assert(PVT != VT && "Don't know what type to promote to!"); 1301 // fold (aext (aext x)) -> (aext x) 1302 // fold (aext (zext x)) -> (zext x) 1303 // fold (aext (sext x)) -> (sext x) 1304 DEBUG(dbgs() << "\nPromoting "; 1305 Op.getNode()->dump(&DAG)); 1306 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1307 } 1308 return SDValue(); 1309 } 1310 1311 bool DAGCombiner::PromoteLoad(SDValue Op) { 1312 if (!LegalOperations) 1313 return false; 1314 1315 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1316 return false; 1317 1318 EVT VT = Op.getValueType(); 1319 if (VT.isVector() || !VT.isInteger()) 1320 return false; 1321 1322 // If operation type is 'undesirable', e.g. i16 on x86, consider 1323 // promoting it. 1324 unsigned Opc = Op.getOpcode(); 1325 if (TLI.isTypeDesirableForOp(Opc, VT)) 1326 return false; 1327 1328 EVT PVT = VT; 1329 // Consult target whether it is a good idea to promote this operation and 1330 // what's the right type to promote it to. 1331 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1332 assert(PVT != VT && "Don't know what type to promote to!"); 1333 1334 SDLoc DL(Op); 1335 SDNode *N = Op.getNode(); 1336 LoadSDNode *LD = cast<LoadSDNode>(N); 1337 EVT MemVT = LD->getMemoryVT(); 1338 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1339 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1340 : ISD::EXTLOAD) 1341 : LD->getExtensionType(); 1342 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1343 LD->getChain(), LD->getBasePtr(), 1344 MemVT, LD->getMemOperand()); 1345 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1346 1347 DEBUG(dbgs() << "\nPromoting "; 1348 N->dump(&DAG); 1349 dbgs() << "\nTo: "; 1350 Result.getNode()->dump(&DAG); 1351 dbgs() << '\n'); 1352 WorklistRemover DeadNodes(*this); 1353 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1354 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1355 deleteAndRecombine(N); 1356 AddToWorklist(Result.getNode()); 1357 return true; 1358 } 1359 return false; 1360 } 1361 1362 /// \brief Recursively delete a node which has no uses and any operands for 1363 /// which it is the only use. 1364 /// 1365 /// Note that this both deletes the nodes and removes them from the worklist. 1366 /// It also adds any nodes who have had a user deleted to the worklist as they 1367 /// may now have only one use and subject to other combines. 1368 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1369 if (!N->use_empty()) 1370 return false; 1371 1372 SmallSetVector<SDNode *, 16> Nodes; 1373 Nodes.insert(N); 1374 do { 1375 N = Nodes.pop_back_val(); 1376 if (!N) 1377 continue; 1378 1379 if (N->use_empty()) { 1380 for (const SDValue &ChildN : N->op_values()) 1381 Nodes.insert(ChildN.getNode()); 1382 1383 removeFromWorklist(N); 1384 DAG.DeleteNode(N); 1385 } else { 1386 AddToWorklist(N); 1387 } 1388 } while (!Nodes.empty()); 1389 return true; 1390 } 1391 1392 //===----------------------------------------------------------------------===// 1393 // Main DAG Combiner implementation 1394 //===----------------------------------------------------------------------===// 1395 1396 void DAGCombiner::Run(CombineLevel AtLevel) { 1397 // set the instance variables, so that the various visit routines may use it. 1398 Level = AtLevel; 1399 LegalOperations = Level >= AfterLegalizeVectorOps; 1400 LegalTypes = Level >= AfterLegalizeTypes; 1401 1402 // Add all the dag nodes to the worklist. 1403 for (SDNode &Node : DAG.allnodes()) 1404 AddToWorklist(&Node); 1405 1406 // Create a dummy node (which is not added to allnodes), that adds a reference 1407 // to the root node, preventing it from being deleted, and tracking any 1408 // changes of the root. 1409 HandleSDNode Dummy(DAG.getRoot()); 1410 1411 // While the worklist isn't empty, find a node and try to combine it. 1412 while (!WorklistMap.empty()) { 1413 SDNode *N; 1414 // The Worklist holds the SDNodes in order, but it may contain null entries. 1415 do { 1416 N = Worklist.pop_back_val(); 1417 } while (!N); 1418 1419 bool GoodWorklistEntry = WorklistMap.erase(N); 1420 (void)GoodWorklistEntry; 1421 assert(GoodWorklistEntry && 1422 "Found a worklist entry without a corresponding map entry!"); 1423 1424 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1425 // N is deleted from the DAG, since they too may now be dead or may have a 1426 // reduced number of uses, allowing other xforms. 1427 if (recursivelyDeleteUnusedNodes(N)) 1428 continue; 1429 1430 WorklistRemover DeadNodes(*this); 1431 1432 // If this combine is running after legalizing the DAG, re-legalize any 1433 // nodes pulled off the worklist. 1434 if (Level == AfterLegalizeDAG) { 1435 SmallSetVector<SDNode *, 16> UpdatedNodes; 1436 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1437 1438 for (SDNode *LN : UpdatedNodes) { 1439 AddToWorklist(LN); 1440 AddUsersToWorklist(LN); 1441 } 1442 if (!NIsValid) 1443 continue; 1444 } 1445 1446 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1447 1448 // Add any operands of the new node which have not yet been combined to the 1449 // worklist as well. Because the worklist uniques things already, this 1450 // won't repeatedly process the same operand. 1451 CombinedNodes.insert(N); 1452 for (const SDValue &ChildN : N->op_values()) 1453 if (!CombinedNodes.count(ChildN.getNode())) 1454 AddToWorklist(ChildN.getNode()); 1455 1456 SDValue RV = combine(N); 1457 1458 if (!RV.getNode()) 1459 continue; 1460 1461 ++NodesCombined; 1462 1463 // If we get back the same node we passed in, rather than a new node or 1464 // zero, we know that the node must have defined multiple values and 1465 // CombineTo was used. Since CombineTo takes care of the worklist 1466 // mechanics for us, we have no work to do in this case. 1467 if (RV.getNode() == N) 1468 continue; 1469 1470 assert(N->getOpcode() != ISD::DELETED_NODE && 1471 RV.getOpcode() != ISD::DELETED_NODE && 1472 "Node was deleted but visit returned new node!"); 1473 1474 DEBUG(dbgs() << " ... into: "; 1475 RV.getNode()->dump(&DAG)); 1476 1477 if (N->getNumValues() == RV.getNode()->getNumValues()) 1478 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1479 else { 1480 assert(N->getValueType(0) == RV.getValueType() && 1481 N->getNumValues() == 1 && "Type mismatch"); 1482 DAG.ReplaceAllUsesWith(N, &RV); 1483 } 1484 1485 // Push the new node and any users onto the worklist 1486 AddToWorklist(RV.getNode()); 1487 AddUsersToWorklist(RV.getNode()); 1488 1489 // Finally, if the node is now dead, remove it from the graph. The node 1490 // may not be dead if the replacement process recursively simplified to 1491 // something else needing this node. This will also take care of adding any 1492 // operands which have lost a user to the worklist. 1493 recursivelyDeleteUnusedNodes(N); 1494 } 1495 1496 // If the root changed (e.g. it was a dead load, update the root). 1497 DAG.setRoot(Dummy.getValue()); 1498 DAG.RemoveDeadNodes(); 1499 } 1500 1501 SDValue DAGCombiner::visit(SDNode *N) { 1502 switch (N->getOpcode()) { 1503 default: break; 1504 case ISD::TokenFactor: return visitTokenFactor(N); 1505 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1506 case ISD::ADD: return visitADD(N); 1507 case ISD::SUB: return visitSUB(N); 1508 case ISD::ADDC: return visitADDC(N); 1509 case ISD::UADDO: return visitUADDO(N); 1510 case ISD::SUBC: return visitSUBC(N); 1511 case ISD::USUBO: return visitUSUBO(N); 1512 case ISD::ADDE: return visitADDE(N); 1513 case ISD::ADDCARRY: return visitADDCARRY(N); 1514 case ISD::SUBE: return visitSUBE(N); 1515 case ISD::SUBCARRY: return visitSUBCARRY(N); 1516 case ISD::MUL: return visitMUL(N); 1517 case ISD::SDIV: return visitSDIV(N); 1518 case ISD::UDIV: return visitUDIV(N); 1519 case ISD::SREM: 1520 case ISD::UREM: return visitREM(N); 1521 case ISD::MULHU: return visitMULHU(N); 1522 case ISD::MULHS: return visitMULHS(N); 1523 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1524 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1525 case ISD::SMULO: return visitSMULO(N); 1526 case ISD::UMULO: return visitUMULO(N); 1527 case ISD::SMIN: 1528 case ISD::SMAX: 1529 case ISD::UMIN: 1530 case ISD::UMAX: return visitIMINMAX(N); 1531 case ISD::AND: return visitAND(N); 1532 case ISD::OR: return visitOR(N); 1533 case ISD::XOR: return visitXOR(N); 1534 case ISD::SHL: return visitSHL(N); 1535 case ISD::SRA: return visitSRA(N); 1536 case ISD::SRL: return visitSRL(N); 1537 case ISD::ROTR: 1538 case ISD::ROTL: return visitRotate(N); 1539 case ISD::ABS: return visitABS(N); 1540 case ISD::BSWAP: return visitBSWAP(N); 1541 case ISD::BITREVERSE: return visitBITREVERSE(N); 1542 case ISD::CTLZ: return visitCTLZ(N); 1543 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1544 case ISD::CTTZ: return visitCTTZ(N); 1545 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1546 case ISD::CTPOP: return visitCTPOP(N); 1547 case ISD::SELECT: return visitSELECT(N); 1548 case ISD::VSELECT: return visitVSELECT(N); 1549 case ISD::SELECT_CC: return visitSELECT_CC(N); 1550 case ISD::SETCC: return visitSETCC(N); 1551 case ISD::SETCCE: return visitSETCCE(N); 1552 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1553 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1554 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1555 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1556 case ISD::AssertSext: 1557 case ISD::AssertZext: return visitAssertExt(N); 1558 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1559 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1560 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1561 case ISD::TRUNCATE: return visitTRUNCATE(N); 1562 case ISD::BITCAST: return visitBITCAST(N); 1563 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1564 case ISD::FADD: return visitFADD(N); 1565 case ISD::FSUB: return visitFSUB(N); 1566 case ISD::FMUL: return visitFMUL(N); 1567 case ISD::FMA: return visitFMA(N); 1568 case ISD::FDIV: return visitFDIV(N); 1569 case ISD::FREM: return visitFREM(N); 1570 case ISD::FSQRT: return visitFSQRT(N); 1571 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1572 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1573 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1574 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1575 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1576 case ISD::FP_ROUND: return visitFP_ROUND(N); 1577 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1578 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1579 case ISD::FNEG: return visitFNEG(N); 1580 case ISD::FABS: return visitFABS(N); 1581 case ISD::FFLOOR: return visitFFLOOR(N); 1582 case ISD::FMINNUM: return visitFMINNUM(N); 1583 case ISD::FMAXNUM: return visitFMAXNUM(N); 1584 case ISD::FCEIL: return visitFCEIL(N); 1585 case ISD::FTRUNC: return visitFTRUNC(N); 1586 case ISD::BRCOND: return visitBRCOND(N); 1587 case ISD::BR_CC: return visitBR_CC(N); 1588 case ISD::LOAD: return visitLOAD(N); 1589 case ISD::STORE: return visitSTORE(N); 1590 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1591 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1592 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1593 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1594 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1595 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1596 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1597 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1598 case ISD::MGATHER: return visitMGATHER(N); 1599 case ISD::MLOAD: return visitMLOAD(N); 1600 case ISD::MSCATTER: return visitMSCATTER(N); 1601 case ISD::MSTORE: return visitMSTORE(N); 1602 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1603 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1604 } 1605 return SDValue(); 1606 } 1607 1608 SDValue DAGCombiner::combine(SDNode *N) { 1609 SDValue RV = visit(N); 1610 1611 // If nothing happened, try a target-specific DAG combine. 1612 if (!RV.getNode()) { 1613 assert(N->getOpcode() != ISD::DELETED_NODE && 1614 "Node was deleted but visit returned NULL!"); 1615 1616 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1617 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1618 1619 // Expose the DAG combiner to the target combiner impls. 1620 TargetLowering::DAGCombinerInfo 1621 DagCombineInfo(DAG, Level, false, this); 1622 1623 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1624 } 1625 } 1626 1627 // If nothing happened still, try promoting the operation. 1628 if (!RV.getNode()) { 1629 switch (N->getOpcode()) { 1630 default: break; 1631 case ISD::ADD: 1632 case ISD::SUB: 1633 case ISD::MUL: 1634 case ISD::AND: 1635 case ISD::OR: 1636 case ISD::XOR: 1637 RV = PromoteIntBinOp(SDValue(N, 0)); 1638 break; 1639 case ISD::SHL: 1640 case ISD::SRA: 1641 case ISD::SRL: 1642 RV = PromoteIntShiftOp(SDValue(N, 0)); 1643 break; 1644 case ISD::SIGN_EXTEND: 1645 case ISD::ZERO_EXTEND: 1646 case ISD::ANY_EXTEND: 1647 RV = PromoteExtend(SDValue(N, 0)); 1648 break; 1649 case ISD::LOAD: 1650 if (PromoteLoad(SDValue(N, 0))) 1651 RV = SDValue(N, 0); 1652 break; 1653 } 1654 } 1655 1656 // If N is a commutative binary node, try eliminate it if the commuted 1657 // version is already present in the DAG. 1658 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1659 N->getNumValues() == 1) { 1660 SDValue N0 = N->getOperand(0); 1661 SDValue N1 = N->getOperand(1); 1662 1663 // Constant operands are canonicalized to RHS. 1664 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1665 SDValue Ops[] = {N1, N0}; 1666 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1667 N->getFlags()); 1668 if (CSENode) 1669 return SDValue(CSENode, 0); 1670 } 1671 } 1672 1673 return RV; 1674 } 1675 1676 /// Given a node, return its input chain if it has one, otherwise return a null 1677 /// sd operand. 1678 static SDValue getInputChainForNode(SDNode *N) { 1679 if (unsigned NumOps = N->getNumOperands()) { 1680 if (N->getOperand(0).getValueType() == MVT::Other) 1681 return N->getOperand(0); 1682 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1683 return N->getOperand(NumOps-1); 1684 for (unsigned i = 1; i < NumOps-1; ++i) 1685 if (N->getOperand(i).getValueType() == MVT::Other) 1686 return N->getOperand(i); 1687 } 1688 return SDValue(); 1689 } 1690 1691 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1692 // If N has two operands, where one has an input chain equal to the other, 1693 // the 'other' chain is redundant. 1694 if (N->getNumOperands() == 2) { 1695 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1696 return N->getOperand(0); 1697 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1698 return N->getOperand(1); 1699 } 1700 1701 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1702 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1703 SmallPtrSet<SDNode*, 16> SeenOps; 1704 bool Changed = false; // If we should replace this token factor. 1705 1706 // Start out with this token factor. 1707 TFs.push_back(N); 1708 1709 // Iterate through token factors. The TFs grows when new token factors are 1710 // encountered. 1711 for (unsigned i = 0; i < TFs.size(); ++i) { 1712 SDNode *TF = TFs[i]; 1713 1714 // Check each of the operands. 1715 for (const SDValue &Op : TF->op_values()) { 1716 switch (Op.getOpcode()) { 1717 case ISD::EntryToken: 1718 // Entry tokens don't need to be added to the list. They are 1719 // redundant. 1720 Changed = true; 1721 break; 1722 1723 case ISD::TokenFactor: 1724 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1725 // Queue up for processing. 1726 TFs.push_back(Op.getNode()); 1727 // Clean up in case the token factor is removed. 1728 AddToWorklist(Op.getNode()); 1729 Changed = true; 1730 break; 1731 } 1732 LLVM_FALLTHROUGH; 1733 1734 default: 1735 // Only add if it isn't already in the list. 1736 if (SeenOps.insert(Op.getNode()).second) 1737 Ops.push_back(Op); 1738 else 1739 Changed = true; 1740 break; 1741 } 1742 } 1743 } 1744 1745 // Remove Nodes that are chained to another node in the list. Do so 1746 // by walking up chains breath-first stopping when we've seen 1747 // another operand. In general we must climb to the EntryNode, but we can exit 1748 // early if we find all remaining work is associated with just one operand as 1749 // no further pruning is possible. 1750 1751 // List of nodes to search through and original Ops from which they originate. 1752 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1753 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1754 SmallPtrSet<SDNode *, 16> SeenChains; 1755 bool DidPruneOps = false; 1756 1757 unsigned NumLeftToConsider = 0; 1758 for (const SDValue &Op : Ops) { 1759 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1760 OpWorkCount.push_back(1); 1761 } 1762 1763 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1764 // If this is an Op, we can remove the op from the list. Remark any 1765 // search associated with it as from the current OpNumber. 1766 if (SeenOps.count(Op) != 0) { 1767 Changed = true; 1768 DidPruneOps = true; 1769 unsigned OrigOpNumber = 0; 1770 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1771 OrigOpNumber++; 1772 assert((OrigOpNumber != Ops.size()) && 1773 "expected to find TokenFactor Operand"); 1774 // Re-mark worklist from OrigOpNumber to OpNumber 1775 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1776 if (Worklist[i].second == OrigOpNumber) { 1777 Worklist[i].second = OpNumber; 1778 } 1779 } 1780 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1781 OpWorkCount[OrigOpNumber] = 0; 1782 NumLeftToConsider--; 1783 } 1784 // Add if it's a new chain 1785 if (SeenChains.insert(Op).second) { 1786 OpWorkCount[OpNumber]++; 1787 Worklist.push_back(std::make_pair(Op, OpNumber)); 1788 } 1789 }; 1790 1791 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1792 // We need at least be consider at least 2 Ops to prune. 1793 if (NumLeftToConsider <= 1) 1794 break; 1795 auto CurNode = Worklist[i].first; 1796 auto CurOpNumber = Worklist[i].second; 1797 assert((OpWorkCount[CurOpNumber] > 0) && 1798 "Node should not appear in worklist"); 1799 switch (CurNode->getOpcode()) { 1800 case ISD::EntryToken: 1801 // Hitting EntryToken is the only way for the search to terminate without 1802 // hitting 1803 // another operand's search. Prevent us from marking this operand 1804 // considered. 1805 NumLeftToConsider++; 1806 break; 1807 case ISD::TokenFactor: 1808 for (const SDValue &Op : CurNode->op_values()) 1809 AddToWorklist(i, Op.getNode(), CurOpNumber); 1810 break; 1811 case ISD::CopyFromReg: 1812 case ISD::CopyToReg: 1813 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1814 break; 1815 default: 1816 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1817 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1818 break; 1819 } 1820 OpWorkCount[CurOpNumber]--; 1821 if (OpWorkCount[CurOpNumber] == 0) 1822 NumLeftToConsider--; 1823 } 1824 1825 // If we've changed things around then replace token factor. 1826 if (Changed) { 1827 SDValue Result; 1828 if (Ops.empty()) { 1829 // The entry token is the only possible outcome. 1830 Result = DAG.getEntryNode(); 1831 } else { 1832 if (DidPruneOps) { 1833 SmallVector<SDValue, 8> PrunedOps; 1834 // 1835 for (const SDValue &Op : Ops) { 1836 if (SeenChains.count(Op.getNode()) == 0) 1837 PrunedOps.push_back(Op); 1838 } 1839 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1840 } else { 1841 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1842 } 1843 } 1844 return Result; 1845 } 1846 return SDValue(); 1847 } 1848 1849 /// MERGE_VALUES can always be eliminated. 1850 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1851 WorklistRemover DeadNodes(*this); 1852 // Replacing results may cause a different MERGE_VALUES to suddenly 1853 // be CSE'd with N, and carry its uses with it. Iterate until no 1854 // uses remain, to ensure that the node can be safely deleted. 1855 // First add the users of this node to the work list so that they 1856 // can be tried again once they have new operands. 1857 AddUsersToWorklist(N); 1858 do { 1859 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1860 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1861 } while (!N->use_empty()); 1862 deleteAndRecombine(N); 1863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1864 } 1865 1866 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1867 /// ConstantSDNode pointer else nullptr. 1868 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1869 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1870 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1871 } 1872 1873 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1874 auto BinOpcode = BO->getOpcode(); 1875 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1876 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1877 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1878 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1879 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1880 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1881 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1882 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1883 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1884 "Unexpected binary operator"); 1885 1886 // Bail out if any constants are opaque because we can't constant fold those. 1887 SDValue C1 = BO->getOperand(1); 1888 if (!isConstantOrConstantVector(C1, true) && 1889 !isConstantFPBuildVectorOrConstantFP(C1)) 1890 return SDValue(); 1891 1892 // Don't do this unless the old select is going away. We want to eliminate the 1893 // binary operator, not replace a binop with a select. 1894 // TODO: Handle ISD::SELECT_CC. 1895 SDValue Sel = BO->getOperand(0); 1896 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1897 return SDValue(); 1898 1899 SDValue CT = Sel.getOperand(1); 1900 if (!isConstantOrConstantVector(CT, true) && 1901 !isConstantFPBuildVectorOrConstantFP(CT)) 1902 return SDValue(); 1903 1904 SDValue CF = Sel.getOperand(2); 1905 if (!isConstantOrConstantVector(CF, true) && 1906 !isConstantFPBuildVectorOrConstantFP(CF)) 1907 return SDValue(); 1908 1909 // We have a select-of-constants followed by a binary operator with a 1910 // constant. Eliminate the binop by pulling the constant math into the select. 1911 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1912 EVT VT = Sel.getValueType(); 1913 SDLoc DL(Sel); 1914 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1915 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) || 1916 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1917 "Failed to constant fold a binop with constant operands"); 1918 1919 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1920 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) || 1921 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1922 "Failed to constant fold a binop with constant operands"); 1923 1924 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1925 } 1926 1927 SDValue DAGCombiner::visitADD(SDNode *N) { 1928 SDValue N0 = N->getOperand(0); 1929 SDValue N1 = N->getOperand(1); 1930 EVT VT = N0.getValueType(); 1931 SDLoc DL(N); 1932 1933 // fold vector ops 1934 if (VT.isVector()) { 1935 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1936 return FoldedVOp; 1937 1938 // fold (add x, 0) -> x, vector edition 1939 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1940 return N0; 1941 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1942 return N1; 1943 } 1944 1945 // fold (add x, undef) -> undef 1946 if (N0.isUndef()) 1947 return N0; 1948 1949 if (N1.isUndef()) 1950 return N1; 1951 1952 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1953 // canonicalize constant to RHS 1954 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1955 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1956 // fold (add c1, c2) -> c1+c2 1957 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1958 N1.getNode()); 1959 } 1960 1961 // fold (add x, 0) -> x 1962 if (isNullConstant(N1)) 1963 return N0; 1964 1965 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1966 // fold ((c1-A)+c2) -> (c1+c2)-A 1967 if (N0.getOpcode() == ISD::SUB && 1968 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1969 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1970 return DAG.getNode(ISD::SUB, DL, VT, 1971 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1972 N0.getOperand(1)); 1973 } 1974 1975 // add (sext i1 X), 1 -> zext (not i1 X) 1976 // We don't transform this pattern: 1977 // add (zext i1 X), -1 -> sext (not i1 X) 1978 // because most (?) targets generate better code for the zext form. 1979 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1980 isOneConstantOrOneSplatConstant(N1)) { 1981 SDValue X = N0.getOperand(0); 1982 if ((!LegalOperations || 1983 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1984 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1985 X.getScalarValueSizeInBits() == 1) { 1986 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1987 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1988 } 1989 } 1990 1991 // Undo the add -> or combine to merge constant offsets from a frame index. 1992 if (N0.getOpcode() == ISD::OR && 1993 isa<FrameIndexSDNode>(N0.getOperand(0)) && 1994 isa<ConstantSDNode>(N0.getOperand(1)) && 1995 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 1996 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 1997 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 1998 } 1999 } 2000 2001 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2002 return NewSel; 2003 2004 // reassociate add 2005 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 2006 return RADD; 2007 2008 // fold ((0-A) + B) -> B-A 2009 if (N0.getOpcode() == ISD::SUB && 2010 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 2011 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2012 2013 // fold (A + (0-B)) -> A-B 2014 if (N1.getOpcode() == ISD::SUB && 2015 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 2016 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2017 2018 // fold (A+(B-A)) -> B 2019 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2020 return N1.getOperand(0); 2021 2022 // fold ((B-A)+A) -> B 2023 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2024 return N0.getOperand(0); 2025 2026 // fold (A+(B-(A+C))) to (B-C) 2027 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2028 N0 == N1.getOperand(1).getOperand(0)) 2029 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2030 N1.getOperand(1).getOperand(1)); 2031 2032 // fold (A+(B-(C+A))) to (B-C) 2033 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2034 N0 == N1.getOperand(1).getOperand(1)) 2035 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2036 N1.getOperand(1).getOperand(0)); 2037 2038 // fold (A+((B-A)+or-C)) to (B+or-C) 2039 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2040 N1.getOperand(0).getOpcode() == ISD::SUB && 2041 N0 == N1.getOperand(0).getOperand(1)) 2042 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2043 N1.getOperand(1)); 2044 2045 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2046 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2047 SDValue N00 = N0.getOperand(0); 2048 SDValue N01 = N0.getOperand(1); 2049 SDValue N10 = N1.getOperand(0); 2050 SDValue N11 = N1.getOperand(1); 2051 2052 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2053 return DAG.getNode(ISD::SUB, DL, VT, 2054 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2055 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2056 } 2057 2058 if (SimplifyDemandedBits(SDValue(N, 0))) 2059 return SDValue(N, 0); 2060 2061 // fold (a+b) -> (a|b) iff a and b share no bits. 2062 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2063 DAG.haveNoCommonBitsSet(N0, N1)) 2064 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2065 2066 if (SDValue Combined = visitADDLike(N0, N1, N)) 2067 return Combined; 2068 2069 if (SDValue Combined = visitADDLike(N1, N0, N)) 2070 return Combined; 2071 2072 return SDValue(); 2073 } 2074 2075 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2076 bool Masked = false; 2077 2078 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2079 while (true) { 2080 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2081 V = V.getOperand(0); 2082 continue; 2083 } 2084 2085 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2086 Masked = true; 2087 V = V.getOperand(0); 2088 continue; 2089 } 2090 2091 break; 2092 } 2093 2094 // If this is not a carry, return. 2095 if (V.getResNo() != 1) 2096 return SDValue(); 2097 2098 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2099 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2100 return SDValue(); 2101 2102 // If the result is masked, then no matter what kind of bool it is we can 2103 // return. If it isn't, then we need to make sure the bool type is either 0 or 2104 // 1 and not other values. 2105 if (Masked || 2106 TLI.getBooleanContents(V.getValueType()) == 2107 TargetLoweringBase::ZeroOrOneBooleanContent) 2108 return V; 2109 2110 return SDValue(); 2111 } 2112 2113 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2114 EVT VT = N0.getValueType(); 2115 SDLoc DL(LocReference); 2116 2117 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2118 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2119 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2120 return DAG.getNode(ISD::SUB, DL, VT, N0, 2121 DAG.getNode(ISD::SHL, DL, VT, 2122 N1.getOperand(0).getOperand(1), 2123 N1.getOperand(1))); 2124 2125 if (N1.getOpcode() == ISD::AND) { 2126 SDValue AndOp0 = N1.getOperand(0); 2127 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2128 unsigned DestBits = VT.getScalarSizeInBits(); 2129 2130 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2131 // and similar xforms where the inner op is either ~0 or 0. 2132 if (NumSignBits == DestBits && 2133 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2134 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2135 } 2136 2137 // add (sext i1), X -> sub X, (zext i1) 2138 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2139 N0.getOperand(0).getValueType() == MVT::i1 && 2140 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2141 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2142 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2143 } 2144 2145 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2146 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2147 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2148 if (TN->getVT() == MVT::i1) { 2149 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2150 DAG.getConstant(1, DL, VT)); 2151 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2152 } 2153 } 2154 2155 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2156 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) 2157 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2158 N0, N1.getOperand(0), N1.getOperand(2)); 2159 2160 // (add X, Carry) -> (addcarry X, 0, Carry) 2161 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2162 if (SDValue Carry = getAsCarry(TLI, N1)) 2163 return DAG.getNode(ISD::ADDCARRY, DL, 2164 DAG.getVTList(VT, Carry.getValueType()), N0, 2165 DAG.getConstant(0, DL, VT), Carry); 2166 2167 return SDValue(); 2168 } 2169 2170 SDValue DAGCombiner::visitADDC(SDNode *N) { 2171 SDValue N0 = N->getOperand(0); 2172 SDValue N1 = N->getOperand(1); 2173 EVT VT = N0.getValueType(); 2174 SDLoc DL(N); 2175 2176 // If the flag result is dead, turn this into an ADD. 2177 if (!N->hasAnyUseOfValue(1)) 2178 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2179 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2180 2181 // canonicalize constant to RHS. 2182 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2183 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2184 if (N0C && !N1C) 2185 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2186 2187 // fold (addc x, 0) -> x + no carry out 2188 if (isNullConstant(N1)) 2189 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2190 DL, MVT::Glue)); 2191 2192 // If it cannot overflow, transform into an add. 2193 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2194 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2195 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2196 2197 return SDValue(); 2198 } 2199 2200 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2201 SDValue N0 = N->getOperand(0); 2202 SDValue N1 = N->getOperand(1); 2203 EVT VT = N0.getValueType(); 2204 if (VT.isVector()) 2205 return SDValue(); 2206 2207 EVT CarryVT = N->getValueType(1); 2208 SDLoc DL(N); 2209 2210 // If the flag result is dead, turn this into an ADD. 2211 if (!N->hasAnyUseOfValue(1)) 2212 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2213 DAG.getUNDEF(CarryVT)); 2214 2215 // canonicalize constant to RHS. 2216 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2218 if (N0C && !N1C) 2219 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2220 2221 // fold (uaddo x, 0) -> x + no carry out 2222 if (isNullConstant(N1)) 2223 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2224 2225 // If it cannot overflow, transform into an add. 2226 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2227 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2228 DAG.getConstant(0, DL, CarryVT)); 2229 2230 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2231 return Combined; 2232 2233 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2234 return Combined; 2235 2236 return SDValue(); 2237 } 2238 2239 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2240 auto VT = N0.getValueType(); 2241 2242 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2243 // If Y + 1 cannot overflow. 2244 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2245 SDValue Y = N1.getOperand(0); 2246 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2247 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2248 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2249 N1.getOperand(2)); 2250 } 2251 2252 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2253 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2254 if (SDValue Carry = getAsCarry(TLI, N1)) 2255 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2256 DAG.getConstant(0, SDLoc(N), VT), Carry); 2257 2258 return SDValue(); 2259 } 2260 2261 SDValue DAGCombiner::visitADDE(SDNode *N) { 2262 SDValue N0 = N->getOperand(0); 2263 SDValue N1 = N->getOperand(1); 2264 SDValue CarryIn = N->getOperand(2); 2265 2266 // canonicalize constant to RHS 2267 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2269 if (N0C && !N1C) 2270 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2271 N1, N0, CarryIn); 2272 2273 // fold (adde x, y, false) -> (addc x, y) 2274 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2275 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2276 2277 return SDValue(); 2278 } 2279 2280 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2281 SDValue N0 = N->getOperand(0); 2282 SDValue N1 = N->getOperand(1); 2283 SDValue CarryIn = N->getOperand(2); 2284 SDLoc DL(N); 2285 2286 // canonicalize constant to RHS 2287 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2288 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2289 if (N0C && !N1C) 2290 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2291 2292 // fold (addcarry x, y, false) -> (uaddo x, y) 2293 if (isNullConstant(CarryIn)) 2294 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2295 2296 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2297 if (isNullConstant(N0) && isNullConstant(N1)) { 2298 EVT VT = N0.getValueType(); 2299 EVT CarryVT = CarryIn.getValueType(); 2300 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2301 AddToWorklist(CarryExt.getNode()); 2302 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2303 DAG.getConstant(1, DL, VT)), 2304 DAG.getConstant(0, DL, CarryVT)); 2305 } 2306 2307 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2308 return Combined; 2309 2310 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2311 return Combined; 2312 2313 return SDValue(); 2314 } 2315 2316 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2317 SDNode *N) { 2318 // Iff the flag result is dead: 2319 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2320 if ((N0.getOpcode() == ISD::ADD || 2321 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2322 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2323 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2324 N0.getOperand(0), N0.getOperand(1), CarryIn); 2325 2326 /** 2327 * When one of the addcarry argument is itself a carry, we may be facing 2328 * a diamond carry propagation. In which case we try to transform the DAG 2329 * to ensure linear carry propagation if that is possible. 2330 * 2331 * We are trying to get: 2332 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2333 */ 2334 if (auto Y = getAsCarry(TLI, N1)) { 2335 /** 2336 * (uaddo A, B) 2337 * / \ 2338 * Carry Sum 2339 * | \ 2340 * | (addcarry *, 0, Z) 2341 * | / 2342 * \ Carry 2343 * | / 2344 * (addcarry X, *, *) 2345 */ 2346 if (Y.getOpcode() == ISD::UADDO && 2347 CarryIn.getResNo() == 1 && 2348 CarryIn.getOpcode() == ISD::ADDCARRY && 2349 isNullConstant(CarryIn.getOperand(1)) && 2350 CarryIn.getOperand(0) == Y.getValue(0)) { 2351 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2352 Y.getOperand(0), Y.getOperand(1), 2353 CarryIn.getOperand(2)); 2354 AddToWorklist(NewY.getNode()); 2355 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2356 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2357 NewY.getValue(1)); 2358 } 2359 } 2360 2361 return SDValue(); 2362 } 2363 2364 // Since it may not be valid to emit a fold to zero for vector initializers 2365 // check if we can before folding. 2366 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2367 SelectionDAG &DAG, bool LegalOperations, 2368 bool LegalTypes) { 2369 if (!VT.isVector()) 2370 return DAG.getConstant(0, DL, VT); 2371 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2372 return DAG.getConstant(0, DL, VT); 2373 return SDValue(); 2374 } 2375 2376 SDValue DAGCombiner::visitSUB(SDNode *N) { 2377 SDValue N0 = N->getOperand(0); 2378 SDValue N1 = N->getOperand(1); 2379 EVT VT = N0.getValueType(); 2380 SDLoc DL(N); 2381 2382 // fold vector ops 2383 if (VT.isVector()) { 2384 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2385 return FoldedVOp; 2386 2387 // fold (sub x, 0) -> x, vector edition 2388 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2389 return N0; 2390 } 2391 2392 // fold (sub x, x) -> 0 2393 // FIXME: Refactor this and xor and other similar operations together. 2394 if (N0 == N1) 2395 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2396 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2397 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2398 // fold (sub c1, c2) -> c1-c2 2399 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2400 N1.getNode()); 2401 } 2402 2403 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2404 return NewSel; 2405 2406 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2407 2408 // fold (sub x, c) -> (add x, -c) 2409 if (N1C) { 2410 return DAG.getNode(ISD::ADD, DL, VT, N0, 2411 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2412 } 2413 2414 if (isNullConstantOrNullSplatConstant(N0)) { 2415 unsigned BitWidth = VT.getScalarSizeInBits(); 2416 // Right-shifting everything out but the sign bit followed by negation is 2417 // the same as flipping arithmetic/logical shift type without the negation: 2418 // -(X >>u 31) -> (X >>s 31) 2419 // -(X >>s 31) -> (X >>u 31) 2420 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2421 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2422 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2423 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2424 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2425 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2426 } 2427 } 2428 2429 // 0 - X --> 0 if the sub is NUW. 2430 if (N->getFlags().hasNoUnsignedWrap()) 2431 return N0; 2432 2433 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2434 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2435 // N1 must be 0 because negating the minimum signed value is undefined. 2436 if (N->getFlags().hasNoSignedWrap()) 2437 return N0; 2438 2439 // 0 - X --> X if X is 0 or the minimum signed value. 2440 return N1; 2441 } 2442 } 2443 2444 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2445 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2446 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2447 2448 // fold A-(A-B) -> B 2449 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2450 return N1.getOperand(1); 2451 2452 // fold (A+B)-A -> B 2453 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2454 return N0.getOperand(1); 2455 2456 // fold (A+B)-B -> A 2457 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2458 return N0.getOperand(0); 2459 2460 // fold C2-(A+C1) -> (C2-C1)-A 2461 if (N1.getOpcode() == ISD::ADD) { 2462 SDValue N11 = N1.getOperand(1); 2463 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2464 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2465 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2466 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2467 } 2468 } 2469 2470 // fold ((A+(B+or-C))-B) -> A+or-C 2471 if (N0.getOpcode() == ISD::ADD && 2472 (N0.getOperand(1).getOpcode() == ISD::SUB || 2473 N0.getOperand(1).getOpcode() == ISD::ADD) && 2474 N0.getOperand(1).getOperand(0) == N1) 2475 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2476 N0.getOperand(1).getOperand(1)); 2477 2478 // fold ((A+(C+B))-B) -> A+C 2479 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2480 N0.getOperand(1).getOperand(1) == N1) 2481 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2482 N0.getOperand(1).getOperand(0)); 2483 2484 // fold ((A-(B-C))-C) -> A-B 2485 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2486 N0.getOperand(1).getOperand(1) == N1) 2487 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2488 N0.getOperand(1).getOperand(0)); 2489 2490 // If either operand of a sub is undef, the result is undef 2491 if (N0.isUndef()) 2492 return N0; 2493 if (N1.isUndef()) 2494 return N1; 2495 2496 // If the relocation model supports it, consider symbol offsets. 2497 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2498 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2499 // fold (sub Sym, c) -> Sym-c 2500 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2501 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2502 GA->getOffset() - 2503 (uint64_t)N1C->getSExtValue()); 2504 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2505 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2506 if (GA->getGlobal() == GB->getGlobal()) 2507 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2508 DL, VT); 2509 } 2510 2511 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2512 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2513 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2514 if (TN->getVT() == MVT::i1) { 2515 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2516 DAG.getConstant(1, DL, VT)); 2517 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2518 } 2519 } 2520 2521 return SDValue(); 2522 } 2523 2524 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2525 SDValue N0 = N->getOperand(0); 2526 SDValue N1 = N->getOperand(1); 2527 EVT VT = N0.getValueType(); 2528 SDLoc DL(N); 2529 2530 // If the flag result is dead, turn this into an SUB. 2531 if (!N->hasAnyUseOfValue(1)) 2532 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2533 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2534 2535 // fold (subc x, x) -> 0 + no borrow 2536 if (N0 == N1) 2537 return CombineTo(N, DAG.getConstant(0, DL, VT), 2538 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2539 2540 // fold (subc x, 0) -> x + no borrow 2541 if (isNullConstant(N1)) 2542 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2543 2544 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2545 if (isAllOnesConstant(N0)) 2546 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2547 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2548 2549 return SDValue(); 2550 } 2551 2552 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2553 SDValue N0 = N->getOperand(0); 2554 SDValue N1 = N->getOperand(1); 2555 EVT VT = N0.getValueType(); 2556 if (VT.isVector()) 2557 return SDValue(); 2558 2559 EVT CarryVT = N->getValueType(1); 2560 SDLoc DL(N); 2561 2562 // If the flag result is dead, turn this into an SUB. 2563 if (!N->hasAnyUseOfValue(1)) 2564 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2565 DAG.getUNDEF(CarryVT)); 2566 2567 // fold (usubo x, x) -> 0 + no borrow 2568 if (N0 == N1) 2569 return CombineTo(N, DAG.getConstant(0, DL, VT), 2570 DAG.getConstant(0, DL, CarryVT)); 2571 2572 // fold (usubo x, 0) -> x + no borrow 2573 if (isNullConstant(N1)) 2574 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2575 2576 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2577 if (isAllOnesConstant(N0)) 2578 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2579 DAG.getConstant(0, DL, CarryVT)); 2580 2581 return SDValue(); 2582 } 2583 2584 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2585 SDValue N0 = N->getOperand(0); 2586 SDValue N1 = N->getOperand(1); 2587 SDValue CarryIn = N->getOperand(2); 2588 2589 // fold (sube x, y, false) -> (subc x, y) 2590 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2591 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2592 2593 return SDValue(); 2594 } 2595 2596 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2597 SDValue N0 = N->getOperand(0); 2598 SDValue N1 = N->getOperand(1); 2599 SDValue CarryIn = N->getOperand(2); 2600 2601 // fold (subcarry x, y, false) -> (usubo x, y) 2602 if (isNullConstant(CarryIn)) 2603 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2604 2605 return SDValue(); 2606 } 2607 2608 SDValue DAGCombiner::visitMUL(SDNode *N) { 2609 SDValue N0 = N->getOperand(0); 2610 SDValue N1 = N->getOperand(1); 2611 EVT VT = N0.getValueType(); 2612 2613 // fold (mul x, undef) -> 0 2614 if (N0.isUndef() || N1.isUndef()) 2615 return DAG.getConstant(0, SDLoc(N), VT); 2616 2617 bool N0IsConst = false; 2618 bool N1IsConst = false; 2619 bool N1IsOpaqueConst = false; 2620 bool N0IsOpaqueConst = false; 2621 APInt ConstValue0, ConstValue1; 2622 // fold vector ops 2623 if (VT.isVector()) { 2624 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2625 return FoldedVOp; 2626 2627 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2628 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2629 assert((!N0IsConst || 2630 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 2631 "Splat APInt should be element width"); 2632 assert((!N1IsConst || 2633 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 2634 "Splat APInt should be element width"); 2635 } else { 2636 N0IsConst = isa<ConstantSDNode>(N0); 2637 if (N0IsConst) { 2638 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2639 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2640 } 2641 N1IsConst = isa<ConstantSDNode>(N1); 2642 if (N1IsConst) { 2643 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2644 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2645 } 2646 } 2647 2648 // fold (mul c1, c2) -> c1*c2 2649 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2650 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2651 N0.getNode(), N1.getNode()); 2652 2653 // canonicalize constant to RHS (vector doesn't have to splat) 2654 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2655 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2656 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2657 // fold (mul x, 0) -> 0 2658 if (N1IsConst && ConstValue1.isNullValue()) 2659 return N1; 2660 // fold (mul x, 1) -> x 2661 if (N1IsConst && ConstValue1.isOneValue()) 2662 return N0; 2663 2664 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2665 return NewSel; 2666 2667 // fold (mul x, -1) -> 0-x 2668 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2669 SDLoc DL(N); 2670 return DAG.getNode(ISD::SUB, DL, VT, 2671 DAG.getConstant(0, DL, VT), N0); 2672 } 2673 // fold (mul x, (1 << c)) -> x << c 2674 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2675 DAG.isKnownToBeAPowerOfTwo(N1)) { 2676 SDLoc DL(N); 2677 SDValue LogBase2 = BuildLogBase2(N1, DL); 2678 AddToWorklist(LogBase2.getNode()); 2679 2680 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2681 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2682 AddToWorklist(Trunc.getNode()); 2683 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 2684 } 2685 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2686 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 2687 unsigned Log2Val = (-ConstValue1).logBase2(); 2688 SDLoc DL(N); 2689 // FIXME: If the input is something that is easily negated (e.g. a 2690 // single-use add), we should put the negate there. 2691 return DAG.getNode(ISD::SUB, DL, VT, 2692 DAG.getConstant(0, DL, VT), 2693 DAG.getNode(ISD::SHL, DL, VT, N0, 2694 DAG.getConstant(Log2Val, DL, 2695 getShiftAmountTy(N0.getValueType())))); 2696 } 2697 2698 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2699 if (N0.getOpcode() == ISD::SHL && 2700 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2701 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2702 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2703 if (isConstantOrConstantVector(C3)) 2704 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2705 } 2706 2707 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2708 // use. 2709 { 2710 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2711 2712 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2713 if (N0.getOpcode() == ISD::SHL && 2714 isConstantOrConstantVector(N0.getOperand(1)) && 2715 N0.getNode()->hasOneUse()) { 2716 Sh = N0; Y = N1; 2717 } else if (N1.getOpcode() == ISD::SHL && 2718 isConstantOrConstantVector(N1.getOperand(1)) && 2719 N1.getNode()->hasOneUse()) { 2720 Sh = N1; Y = N0; 2721 } 2722 2723 if (Sh.getNode()) { 2724 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2725 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2726 } 2727 } 2728 2729 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2730 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2731 N0.getOpcode() == ISD::ADD && 2732 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2733 isMulAddWithConstProfitable(N, N0, N1)) 2734 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2735 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2736 N0.getOperand(0), N1), 2737 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2738 N0.getOperand(1), N1)); 2739 2740 // reassociate mul 2741 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2742 return RMUL; 2743 2744 return SDValue(); 2745 } 2746 2747 /// Return true if divmod libcall is available. 2748 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2749 const TargetLowering &TLI) { 2750 RTLIB::Libcall LC; 2751 EVT NodeType = Node->getValueType(0); 2752 if (!NodeType.isSimple()) 2753 return false; 2754 switch (NodeType.getSimpleVT().SimpleTy) { 2755 default: return false; // No libcall for vector types. 2756 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2757 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2758 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2759 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2760 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2761 } 2762 2763 return TLI.getLibcallName(LC) != nullptr; 2764 } 2765 2766 /// Issue divrem if both quotient and remainder are needed. 2767 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2768 if (Node->use_empty()) 2769 return SDValue(); // This is a dead node, leave it alone. 2770 2771 unsigned Opcode = Node->getOpcode(); 2772 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2773 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2774 2775 // DivMod lib calls can still work on non-legal types if using lib-calls. 2776 EVT VT = Node->getValueType(0); 2777 if (VT.isVector() || !VT.isInteger()) 2778 return SDValue(); 2779 2780 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2781 return SDValue(); 2782 2783 // If DIVREM is going to get expanded into a libcall, 2784 // but there is no libcall available, then don't combine. 2785 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2786 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2787 return SDValue(); 2788 2789 // If div is legal, it's better to do the normal expansion 2790 unsigned OtherOpcode = 0; 2791 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2792 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2793 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2794 return SDValue(); 2795 } else { 2796 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2797 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2798 return SDValue(); 2799 } 2800 2801 SDValue Op0 = Node->getOperand(0); 2802 SDValue Op1 = Node->getOperand(1); 2803 SDValue combined; 2804 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2805 UE = Op0.getNode()->use_end(); UI != UE;) { 2806 SDNode *User = *UI++; 2807 if (User == Node || User->use_empty()) 2808 continue; 2809 // Convert the other matching node(s), too; 2810 // otherwise, the DIVREM may get target-legalized into something 2811 // target-specific that we won't be able to recognize. 2812 unsigned UserOpc = User->getOpcode(); 2813 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2814 User->getOperand(0) == Op0 && 2815 User->getOperand(1) == Op1) { 2816 if (!combined) { 2817 if (UserOpc == OtherOpcode) { 2818 SDVTList VTs = DAG.getVTList(VT, VT); 2819 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2820 } else if (UserOpc == DivRemOpc) { 2821 combined = SDValue(User, 0); 2822 } else { 2823 assert(UserOpc == Opcode); 2824 continue; 2825 } 2826 } 2827 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2828 CombineTo(User, combined); 2829 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2830 CombineTo(User, combined.getValue(1)); 2831 } 2832 } 2833 return combined; 2834 } 2835 2836 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2837 SDValue N0 = N->getOperand(0); 2838 SDValue N1 = N->getOperand(1); 2839 EVT VT = N->getValueType(0); 2840 SDLoc DL(N); 2841 2842 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2843 return DAG.getUNDEF(VT); 2844 2845 // undef / X -> 0 2846 // undef % X -> 0 2847 if (N0.isUndef()) 2848 return DAG.getConstant(0, DL, VT); 2849 2850 return SDValue(); 2851 } 2852 2853 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2854 SDValue N0 = N->getOperand(0); 2855 SDValue N1 = N->getOperand(1); 2856 EVT VT = N->getValueType(0); 2857 2858 // fold vector ops 2859 if (VT.isVector()) 2860 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2861 return FoldedVOp; 2862 2863 SDLoc DL(N); 2864 2865 // fold (sdiv c1, c2) -> c1/c2 2866 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2867 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2868 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2869 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2870 // fold (sdiv X, 1) -> X 2871 if (N1C && N1C->isOne()) 2872 return N0; 2873 // fold (sdiv X, -1) -> 0-X 2874 if (N1C && N1C->isAllOnesValue()) 2875 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2876 2877 if (SDValue V = simplifyDivRem(N, DAG)) 2878 return V; 2879 2880 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2881 return NewSel; 2882 2883 // If we know the sign bits of both operands are zero, strength reduce to a 2884 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2885 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2886 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2887 2888 // fold (sdiv X, pow2) -> simple ops after legalize 2889 // FIXME: We check for the exact bit here because the generic lowering gives 2890 // better results in that case. The target-specific lowering should learn how 2891 // to handle exact sdivs efficiently. 2892 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2893 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2894 (-N1C->getAPIntValue()).isPowerOf2())) { 2895 // Target-specific implementation of sdiv x, pow2. 2896 if (SDValue Res = BuildSDIVPow2(N)) 2897 return Res; 2898 2899 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2900 2901 // Splat the sign bit into the register 2902 SDValue SGN = 2903 DAG.getNode(ISD::SRA, DL, VT, N0, 2904 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2905 getShiftAmountTy(N0.getValueType()))); 2906 AddToWorklist(SGN.getNode()); 2907 2908 // Add (N0 < 0) ? abs2 - 1 : 0; 2909 SDValue SRL = 2910 DAG.getNode(ISD::SRL, DL, VT, SGN, 2911 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2912 getShiftAmountTy(SGN.getValueType()))); 2913 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2914 AddToWorklist(SRL.getNode()); 2915 AddToWorklist(ADD.getNode()); // Divide by pow2 2916 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2917 DAG.getConstant(lg2, DL, 2918 getShiftAmountTy(ADD.getValueType()))); 2919 2920 // If we're dividing by a positive value, we're done. Otherwise, we must 2921 // negate the result. 2922 if (N1C->getAPIntValue().isNonNegative()) 2923 return SRA; 2924 2925 AddToWorklist(SRA.getNode()); 2926 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2927 } 2928 2929 // If integer divide is expensive and we satisfy the requirements, emit an 2930 // alternate sequence. Targets may check function attributes for size/speed 2931 // trade-offs. 2932 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2933 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2934 if (SDValue Op = BuildSDIV(N)) 2935 return Op; 2936 2937 // sdiv, srem -> sdivrem 2938 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2939 // true. Otherwise, we break the simplification logic in visitREM(). 2940 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2941 if (SDValue DivRem = useDivRem(N)) 2942 return DivRem; 2943 2944 return SDValue(); 2945 } 2946 2947 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2948 SDValue N0 = N->getOperand(0); 2949 SDValue N1 = N->getOperand(1); 2950 EVT VT = N->getValueType(0); 2951 2952 // fold vector ops 2953 if (VT.isVector()) 2954 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2955 return FoldedVOp; 2956 2957 SDLoc DL(N); 2958 2959 // fold (udiv c1, c2) -> c1/c2 2960 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2961 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2962 if (N0C && N1C) 2963 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2964 N0C, N1C)) 2965 return Folded; 2966 2967 if (SDValue V = simplifyDivRem(N, DAG)) 2968 return V; 2969 2970 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2971 return NewSel; 2972 2973 // fold (udiv x, (1 << c)) -> x >>u c 2974 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2975 DAG.isKnownToBeAPowerOfTwo(N1)) { 2976 SDValue LogBase2 = BuildLogBase2(N1, DL); 2977 AddToWorklist(LogBase2.getNode()); 2978 2979 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2980 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2981 AddToWorklist(Trunc.getNode()); 2982 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2983 } 2984 2985 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2986 if (N1.getOpcode() == ISD::SHL) { 2987 SDValue N10 = N1.getOperand(0); 2988 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2989 DAG.isKnownToBeAPowerOfTwo(N10)) { 2990 SDValue LogBase2 = BuildLogBase2(N10, DL); 2991 AddToWorklist(LogBase2.getNode()); 2992 2993 EVT ADDVT = N1.getOperand(1).getValueType(); 2994 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2995 AddToWorklist(Trunc.getNode()); 2996 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2997 AddToWorklist(Add.getNode()); 2998 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2999 } 3000 } 3001 3002 // fold (udiv x, c) -> alternate 3003 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 3004 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3005 if (SDValue Op = BuildUDIV(N)) 3006 return Op; 3007 3008 // sdiv, srem -> sdivrem 3009 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3010 // true. Otherwise, we break the simplification logic in visitREM(). 3011 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3012 if (SDValue DivRem = useDivRem(N)) 3013 return DivRem; 3014 3015 return SDValue(); 3016 } 3017 3018 // handles ISD::SREM and ISD::UREM 3019 SDValue DAGCombiner::visitREM(SDNode *N) { 3020 unsigned Opcode = N->getOpcode(); 3021 SDValue N0 = N->getOperand(0); 3022 SDValue N1 = N->getOperand(1); 3023 EVT VT = N->getValueType(0); 3024 bool isSigned = (Opcode == ISD::SREM); 3025 SDLoc DL(N); 3026 3027 // fold (rem c1, c2) -> c1%c2 3028 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3029 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3030 if (N0C && N1C) 3031 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3032 return Folded; 3033 3034 if (SDValue V = simplifyDivRem(N, DAG)) 3035 return V; 3036 3037 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3038 return NewSel; 3039 3040 if (isSigned) { 3041 // If we know the sign bits of both operands are zero, strength reduce to a 3042 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3043 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3044 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3045 } else { 3046 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3047 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3048 // fold (urem x, pow2) -> (and x, pow2-1) 3049 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3050 AddToWorklist(Add.getNode()); 3051 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3052 } 3053 if (N1.getOpcode() == ISD::SHL && 3054 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3055 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3056 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3057 AddToWorklist(Add.getNode()); 3058 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3059 } 3060 } 3061 3062 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 3063 3064 // If X/C can be simplified by the division-by-constant logic, lower 3065 // X%C to the equivalent of X-X/C*C. 3066 // To avoid mangling nodes, this simplification requires that the combine() 3067 // call for the speculative DIV must not cause a DIVREM conversion. We guard 3068 // against this by skipping the simplification if isIntDivCheap(). When 3069 // div is not cheap, combine will not return a DIVREM. Regardless, 3070 // checking cheapness here makes sense since the simplification results in 3071 // fatter code. 3072 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 3073 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3074 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 3075 AddToWorklist(Div.getNode()); 3076 SDValue OptimizedDiv = combine(Div.getNode()); 3077 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 3078 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 3079 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 3080 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3081 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3082 AddToWorklist(Mul.getNode()); 3083 return Sub; 3084 } 3085 } 3086 3087 // sdiv, srem -> sdivrem 3088 if (SDValue DivRem = useDivRem(N)) 3089 return DivRem.getValue(1); 3090 3091 return SDValue(); 3092 } 3093 3094 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3095 SDValue N0 = N->getOperand(0); 3096 SDValue N1 = N->getOperand(1); 3097 EVT VT = N->getValueType(0); 3098 SDLoc DL(N); 3099 3100 // fold (mulhs x, 0) -> 0 3101 if (isNullConstant(N1)) 3102 return N1; 3103 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3104 if (isOneConstant(N1)) { 3105 SDLoc DL(N); 3106 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3107 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3108 getShiftAmountTy(N0.getValueType()))); 3109 } 3110 // fold (mulhs x, undef) -> 0 3111 if (N0.isUndef() || N1.isUndef()) 3112 return DAG.getConstant(0, SDLoc(N), VT); 3113 3114 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3115 // plus a shift. 3116 if (VT.isSimple() && !VT.isVector()) { 3117 MVT Simple = VT.getSimpleVT(); 3118 unsigned SimpleSize = Simple.getSizeInBits(); 3119 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3120 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3121 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3122 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3123 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3124 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3125 DAG.getConstant(SimpleSize, DL, 3126 getShiftAmountTy(N1.getValueType()))); 3127 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3128 } 3129 } 3130 3131 return SDValue(); 3132 } 3133 3134 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3135 SDValue N0 = N->getOperand(0); 3136 SDValue N1 = N->getOperand(1); 3137 EVT VT = N->getValueType(0); 3138 SDLoc DL(N); 3139 3140 // fold (mulhu x, 0) -> 0 3141 if (isNullConstant(N1)) 3142 return N1; 3143 // fold (mulhu x, 1) -> 0 3144 if (isOneConstant(N1)) 3145 return DAG.getConstant(0, DL, N0.getValueType()); 3146 // fold (mulhu x, undef) -> 0 3147 if (N0.isUndef() || N1.isUndef()) 3148 return DAG.getConstant(0, DL, VT); 3149 3150 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3151 // plus a shift. 3152 if (VT.isSimple() && !VT.isVector()) { 3153 MVT Simple = VT.getSimpleVT(); 3154 unsigned SimpleSize = Simple.getSizeInBits(); 3155 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3156 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3157 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3158 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3159 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3160 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3161 DAG.getConstant(SimpleSize, DL, 3162 getShiftAmountTy(N1.getValueType()))); 3163 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3164 } 3165 } 3166 3167 return SDValue(); 3168 } 3169 3170 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3171 /// give the opcodes for the two computations that are being performed. Return 3172 /// true if a simplification was made. 3173 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3174 unsigned HiOp) { 3175 // If the high half is not needed, just compute the low half. 3176 bool HiExists = N->hasAnyUseOfValue(1); 3177 if (!HiExists && 3178 (!LegalOperations || 3179 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3180 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3181 return CombineTo(N, Res, Res); 3182 } 3183 3184 // If the low half is not needed, just compute the high half. 3185 bool LoExists = N->hasAnyUseOfValue(0); 3186 if (!LoExists && 3187 (!LegalOperations || 3188 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3189 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3190 return CombineTo(N, Res, Res); 3191 } 3192 3193 // If both halves are used, return as it is. 3194 if (LoExists && HiExists) 3195 return SDValue(); 3196 3197 // If the two computed results can be simplified separately, separate them. 3198 if (LoExists) { 3199 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3200 AddToWorklist(Lo.getNode()); 3201 SDValue LoOpt = combine(Lo.getNode()); 3202 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3203 (!LegalOperations || 3204 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3205 return CombineTo(N, LoOpt, LoOpt); 3206 } 3207 3208 if (HiExists) { 3209 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3210 AddToWorklist(Hi.getNode()); 3211 SDValue HiOpt = combine(Hi.getNode()); 3212 if (HiOpt.getNode() && HiOpt != Hi && 3213 (!LegalOperations || 3214 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3215 return CombineTo(N, HiOpt, HiOpt); 3216 } 3217 3218 return SDValue(); 3219 } 3220 3221 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3222 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3223 return Res; 3224 3225 EVT VT = N->getValueType(0); 3226 SDLoc DL(N); 3227 3228 // If the type is twice as wide is legal, transform the mulhu to a wider 3229 // multiply plus a shift. 3230 if (VT.isSimple() && !VT.isVector()) { 3231 MVT Simple = VT.getSimpleVT(); 3232 unsigned SimpleSize = Simple.getSizeInBits(); 3233 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3234 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3235 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3236 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3237 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3238 // Compute the high part as N1. 3239 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3240 DAG.getConstant(SimpleSize, DL, 3241 getShiftAmountTy(Lo.getValueType()))); 3242 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3243 // Compute the low part as N0. 3244 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3245 return CombineTo(N, Lo, Hi); 3246 } 3247 } 3248 3249 return SDValue(); 3250 } 3251 3252 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3253 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3254 return Res; 3255 3256 EVT VT = N->getValueType(0); 3257 SDLoc DL(N); 3258 3259 // If the type is twice as wide is legal, transform the mulhu to a wider 3260 // multiply plus a shift. 3261 if (VT.isSimple() && !VT.isVector()) { 3262 MVT Simple = VT.getSimpleVT(); 3263 unsigned SimpleSize = Simple.getSizeInBits(); 3264 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3265 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3266 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3267 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3268 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3269 // Compute the high part as N1. 3270 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3271 DAG.getConstant(SimpleSize, DL, 3272 getShiftAmountTy(Lo.getValueType()))); 3273 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3274 // Compute the low part as N0. 3275 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3276 return CombineTo(N, Lo, Hi); 3277 } 3278 } 3279 3280 return SDValue(); 3281 } 3282 3283 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3284 // (smulo x, 2) -> (saddo x, x) 3285 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3286 if (C2->getAPIntValue() == 2) 3287 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3288 N->getOperand(0), N->getOperand(0)); 3289 3290 return SDValue(); 3291 } 3292 3293 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3294 // (umulo x, 2) -> (uaddo x, x) 3295 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3296 if (C2->getAPIntValue() == 2) 3297 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3298 N->getOperand(0), N->getOperand(0)); 3299 3300 return SDValue(); 3301 } 3302 3303 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3304 SDValue N0 = N->getOperand(0); 3305 SDValue N1 = N->getOperand(1); 3306 EVT VT = N0.getValueType(); 3307 3308 // fold vector ops 3309 if (VT.isVector()) 3310 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3311 return FoldedVOp; 3312 3313 // fold operation with constant operands. 3314 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3315 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3316 if (N0C && N1C) 3317 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3318 3319 // canonicalize constant to RHS 3320 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3321 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3322 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3323 3324 return SDValue(); 3325 } 3326 3327 /// If this is a binary operator with two operands of the same opcode, try to 3328 /// simplify it. 3329 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3330 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3331 EVT VT = N0.getValueType(); 3332 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3333 3334 // Bail early if none of these transforms apply. 3335 if (N0.getNumOperands() == 0) return SDValue(); 3336 3337 // For each of OP in AND/OR/XOR: 3338 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3339 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3340 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3341 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3342 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3343 // 3344 // do not sink logical op inside of a vector extend, since it may combine 3345 // into a vsetcc. 3346 EVT Op0VT = N0.getOperand(0).getValueType(); 3347 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3348 N0.getOpcode() == ISD::SIGN_EXTEND || 3349 N0.getOpcode() == ISD::BSWAP || 3350 // Avoid infinite looping with PromoteIntBinOp. 3351 (N0.getOpcode() == ISD::ANY_EXTEND && 3352 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3353 (N0.getOpcode() == ISD::TRUNCATE && 3354 (!TLI.isZExtFree(VT, Op0VT) || 3355 !TLI.isTruncateFree(Op0VT, VT)) && 3356 TLI.isTypeLegal(Op0VT))) && 3357 !VT.isVector() && 3358 Op0VT == N1.getOperand(0).getValueType() && 3359 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3360 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3361 N0.getOperand(0).getValueType(), 3362 N0.getOperand(0), N1.getOperand(0)); 3363 AddToWorklist(ORNode.getNode()); 3364 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3365 } 3366 3367 // For each of OP in SHL/SRL/SRA/AND... 3368 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3369 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3370 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3371 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3372 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3373 N0.getOperand(1) == N1.getOperand(1)) { 3374 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3375 N0.getOperand(0).getValueType(), 3376 N0.getOperand(0), N1.getOperand(0)); 3377 AddToWorklist(ORNode.getNode()); 3378 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3379 ORNode, N0.getOperand(1)); 3380 } 3381 3382 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3383 // Only perform this optimization up until type legalization, before 3384 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3385 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3386 // we don't want to undo this promotion. 3387 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3388 // on scalars. 3389 if ((N0.getOpcode() == ISD::BITCAST || 3390 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3391 Level <= AfterLegalizeTypes) { 3392 SDValue In0 = N0.getOperand(0); 3393 SDValue In1 = N1.getOperand(0); 3394 EVT In0Ty = In0.getValueType(); 3395 EVT In1Ty = In1.getValueType(); 3396 SDLoc DL(N); 3397 // If both incoming values are integers, and the original types are the 3398 // same. 3399 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3400 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3401 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3402 AddToWorklist(Op.getNode()); 3403 return BC; 3404 } 3405 } 3406 3407 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3408 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3409 // If both shuffles use the same mask, and both shuffle within a single 3410 // vector, then it is worthwhile to move the swizzle after the operation. 3411 // The type-legalizer generates this pattern when loading illegal 3412 // vector types from memory. In many cases this allows additional shuffle 3413 // optimizations. 3414 // There are other cases where moving the shuffle after the xor/and/or 3415 // is profitable even if shuffles don't perform a swizzle. 3416 // If both shuffles use the same mask, and both shuffles have the same first 3417 // or second operand, then it might still be profitable to move the shuffle 3418 // after the xor/and/or operation. 3419 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3420 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3421 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3422 3423 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3424 "Inputs to shuffles are not the same type"); 3425 3426 // Check that both shuffles use the same mask. The masks are known to be of 3427 // the same length because the result vector type is the same. 3428 // Check also that shuffles have only one use to avoid introducing extra 3429 // instructions. 3430 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3431 SVN0->getMask().equals(SVN1->getMask())) { 3432 SDValue ShOp = N0->getOperand(1); 3433 3434 // Don't try to fold this node if it requires introducing a 3435 // build vector of all zeros that might be illegal at this stage. 3436 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3437 if (!LegalTypes) 3438 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3439 else 3440 ShOp = SDValue(); 3441 } 3442 3443 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3444 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3445 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3446 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3447 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3448 N0->getOperand(0), N1->getOperand(0)); 3449 AddToWorklist(NewNode.getNode()); 3450 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3451 SVN0->getMask()); 3452 } 3453 3454 // Don't try to fold this node if it requires introducing a 3455 // build vector of all zeros that might be illegal at this stage. 3456 ShOp = N0->getOperand(0); 3457 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3458 if (!LegalTypes) 3459 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3460 else 3461 ShOp = SDValue(); 3462 } 3463 3464 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3465 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3466 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3467 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3468 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3469 N0->getOperand(1), N1->getOperand(1)); 3470 AddToWorklist(NewNode.getNode()); 3471 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3472 SVN0->getMask()); 3473 } 3474 } 3475 } 3476 3477 return SDValue(); 3478 } 3479 3480 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3481 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3482 const SDLoc &DL) { 3483 SDValue LL, LR, RL, RR, N0CC, N1CC; 3484 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3485 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3486 return SDValue(); 3487 3488 assert(N0.getValueType() == N1.getValueType() && 3489 "Unexpected operand types for bitwise logic op"); 3490 assert(LL.getValueType() == LR.getValueType() && 3491 RL.getValueType() == RR.getValueType() && 3492 "Unexpected operand types for setcc"); 3493 3494 // If we're here post-legalization or the logic op type is not i1, the logic 3495 // op type must match a setcc result type. Also, all folds require new 3496 // operations on the left and right operands, so those types must match. 3497 EVT VT = N0.getValueType(); 3498 EVT OpVT = LL.getValueType(); 3499 if (LegalOperations || VT != MVT::i1) 3500 if (VT != getSetCCResultType(OpVT)) 3501 return SDValue(); 3502 if (OpVT != RL.getValueType()) 3503 return SDValue(); 3504 3505 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3506 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3507 bool IsInteger = OpVT.isInteger(); 3508 if (LR == RR && CC0 == CC1 && IsInteger) { 3509 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3510 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3511 3512 // All bits clear? 3513 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3514 // All sign bits clear? 3515 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3516 // Any bits set? 3517 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3518 // Any sign bits set? 3519 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3520 3521 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3522 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3523 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3524 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3525 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3526 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3527 AddToWorklist(Or.getNode()); 3528 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3529 } 3530 3531 // All bits set? 3532 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3533 // All sign bits set? 3534 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3535 // Any bits clear? 3536 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3537 // Any sign bits clear? 3538 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3539 3540 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3541 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3542 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3543 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3544 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3545 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3546 AddToWorklist(And.getNode()); 3547 return DAG.getSetCC(DL, VT, And, LR, CC1); 3548 } 3549 } 3550 3551 // TODO: What is the 'or' equivalent of this fold? 3552 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3553 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE && 3554 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3555 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3556 SDValue One = DAG.getConstant(1, DL, OpVT); 3557 SDValue Two = DAG.getConstant(2, DL, OpVT); 3558 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3559 AddToWorklist(Add.getNode()); 3560 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3561 } 3562 3563 // Try more general transforms if the predicates match and the only user of 3564 // the compares is the 'and' or 'or'. 3565 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3566 N0.hasOneUse() && N1.hasOneUse()) { 3567 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3568 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3569 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3570 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3571 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3572 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3573 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3574 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3575 } 3576 } 3577 3578 // Canonicalize equivalent operands to LL == RL. 3579 if (LL == RR && LR == RL) { 3580 CC1 = ISD::getSetCCSwappedOperands(CC1); 3581 std::swap(RL, RR); 3582 } 3583 3584 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3585 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3586 if (LL == RL && LR == RR) { 3587 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3588 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3589 if (NewCC != ISD::SETCC_INVALID && 3590 (!LegalOperations || 3591 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3592 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3593 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3594 } 3595 3596 return SDValue(); 3597 } 3598 3599 /// This contains all DAGCombine rules which reduce two values combined by 3600 /// an And operation to a single value. This makes them reusable in the context 3601 /// of visitSELECT(). Rules involving constants are not included as 3602 /// visitSELECT() already handles those cases. 3603 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3604 EVT VT = N1.getValueType(); 3605 SDLoc DL(N); 3606 3607 // fold (and x, undef) -> 0 3608 if (N0.isUndef() || N1.isUndef()) 3609 return DAG.getConstant(0, DL, VT); 3610 3611 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3612 return V; 3613 3614 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3615 VT.getSizeInBits() <= 64) { 3616 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3617 APInt ADDC = ADDI->getAPIntValue(); 3618 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3619 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3620 // immediate for an add, but it is legal if its top c2 bits are set, 3621 // transform the ADD so the immediate doesn't need to be materialized 3622 // in a register. 3623 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3624 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3625 SRLI->getZExtValue()); 3626 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3627 ADDC |= Mask; 3628 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3629 SDLoc DL0(N0); 3630 SDValue NewAdd = 3631 DAG.getNode(ISD::ADD, DL0, VT, 3632 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3633 CombineTo(N0.getNode(), NewAdd); 3634 // Return N so it doesn't get rechecked! 3635 return SDValue(N, 0); 3636 } 3637 } 3638 } 3639 } 3640 } 3641 } 3642 3643 // Reduce bit extract of low half of an integer to the narrower type. 3644 // (and (srl i64:x, K), KMask) -> 3645 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3646 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3647 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3648 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3649 unsigned Size = VT.getSizeInBits(); 3650 const APInt &AndMask = CAnd->getAPIntValue(); 3651 unsigned ShiftBits = CShift->getZExtValue(); 3652 3653 // Bail out, this node will probably disappear anyway. 3654 if (ShiftBits == 0) 3655 return SDValue(); 3656 3657 unsigned MaskBits = AndMask.countTrailingOnes(); 3658 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3659 3660 if (AndMask.isMask() && 3661 // Required bits must not span the two halves of the integer and 3662 // must fit in the half size type. 3663 (ShiftBits + MaskBits <= Size / 2) && 3664 TLI.isNarrowingProfitable(VT, HalfVT) && 3665 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3666 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3667 TLI.isTruncateFree(VT, HalfVT) && 3668 TLI.isZExtFree(HalfVT, VT)) { 3669 // The isNarrowingProfitable is to avoid regressions on PPC and 3670 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3671 // on downstream users of this. Those patterns could probably be 3672 // extended to handle extensions mixed in. 3673 3674 SDValue SL(N0); 3675 assert(MaskBits <= Size); 3676 3677 // Extracting the highest bit of the low half. 3678 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3679 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3680 N0.getOperand(0)); 3681 3682 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3683 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3684 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3685 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3686 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3687 } 3688 } 3689 } 3690 } 3691 3692 return SDValue(); 3693 } 3694 3695 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3696 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3697 bool &NarrowLoad) { 3698 if (!AndC->getAPIntValue().isMask()) 3699 return false; 3700 3701 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 3702 3703 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3704 LoadedVT = LoadN->getMemoryVT(); 3705 3706 if (ExtVT == LoadedVT && 3707 (!LegalOperations || 3708 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3709 // ZEXTLOAD will match without needing to change the size of the value being 3710 // loaded. 3711 NarrowLoad = false; 3712 return true; 3713 } 3714 3715 // Do not change the width of a volatile load. 3716 if (LoadN->isVolatile()) 3717 return false; 3718 3719 // Do not generate loads of non-round integer types since these can 3720 // be expensive (and would be wrong if the type is not byte sized). 3721 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3722 return false; 3723 3724 if (LegalOperations && 3725 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3726 return false; 3727 3728 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3729 return false; 3730 3731 NarrowLoad = true; 3732 return true; 3733 } 3734 3735 SDValue DAGCombiner::visitAND(SDNode *N) { 3736 SDValue N0 = N->getOperand(0); 3737 SDValue N1 = N->getOperand(1); 3738 EVT VT = N1.getValueType(); 3739 3740 // x & x --> x 3741 if (N0 == N1) 3742 return N0; 3743 3744 // fold vector ops 3745 if (VT.isVector()) { 3746 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3747 return FoldedVOp; 3748 3749 // fold (and x, 0) -> 0, vector edition 3750 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3751 // do not return N0, because undef node may exist in N0 3752 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3753 SDLoc(N), N0.getValueType()); 3754 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3755 // do not return N1, because undef node may exist in N1 3756 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3757 SDLoc(N), N1.getValueType()); 3758 3759 // fold (and x, -1) -> x, vector edition 3760 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3761 return N1; 3762 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3763 return N0; 3764 } 3765 3766 // fold (and c1, c2) -> c1&c2 3767 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3768 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3769 if (N0C && N1C && !N1C->isOpaque()) 3770 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3771 // canonicalize constant to RHS 3772 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3773 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3774 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3775 // fold (and x, -1) -> x 3776 if (isAllOnesConstant(N1)) 3777 return N0; 3778 // if (and x, c) is known to be zero, return 0 3779 unsigned BitWidth = VT.getScalarSizeInBits(); 3780 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3781 APInt::getAllOnesValue(BitWidth))) 3782 return DAG.getConstant(0, SDLoc(N), VT); 3783 3784 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3785 return NewSel; 3786 3787 // reassociate and 3788 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3789 return RAND; 3790 // fold (and (or x, C), D) -> D if (C & D) == D 3791 if (N1C && N0.getOpcode() == ISD::OR) 3792 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3793 if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue())) 3794 return N1; 3795 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3796 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3797 SDValue N0Op0 = N0.getOperand(0); 3798 APInt Mask = ~N1C->getAPIntValue(); 3799 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3800 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3801 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3802 N0.getValueType(), N0Op0); 3803 3804 // Replace uses of the AND with uses of the Zero extend node. 3805 CombineTo(N, Zext); 3806 3807 // We actually want to replace all uses of the any_extend with the 3808 // zero_extend, to avoid duplicating things. This will later cause this 3809 // AND to be folded. 3810 CombineTo(N0.getNode(), Zext); 3811 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3812 } 3813 } 3814 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3815 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3816 // already be zero by virtue of the width of the base type of the load. 3817 // 3818 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3819 // more cases. 3820 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3821 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3822 N0.getOperand(0).getOpcode() == ISD::LOAD && 3823 N0.getOperand(0).getResNo() == 0) || 3824 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3825 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3826 N0 : N0.getOperand(0) ); 3827 3828 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3829 // This can be a pure constant or a vector splat, in which case we treat the 3830 // vector as a scalar and use the splat value. 3831 APInt Constant = APInt::getNullValue(1); 3832 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3833 Constant = C->getAPIntValue(); 3834 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3835 APInt SplatValue, SplatUndef; 3836 unsigned SplatBitSize; 3837 bool HasAnyUndefs; 3838 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3839 SplatBitSize, HasAnyUndefs); 3840 if (IsSplat) { 3841 // Undef bits can contribute to a possible optimisation if set, so 3842 // set them. 3843 SplatValue |= SplatUndef; 3844 3845 // The splat value may be something like "0x00FFFFFF", which means 0 for 3846 // the first vector value and FF for the rest, repeating. We need a mask 3847 // that will apply equally to all members of the vector, so AND all the 3848 // lanes of the constant together. 3849 EVT VT = Vector->getValueType(0); 3850 unsigned BitWidth = VT.getScalarSizeInBits(); 3851 3852 // If the splat value has been compressed to a bitlength lower 3853 // than the size of the vector lane, we need to re-expand it to 3854 // the lane size. 3855 if (BitWidth > SplatBitSize) 3856 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3857 SplatBitSize < BitWidth; 3858 SplatBitSize = SplatBitSize * 2) 3859 SplatValue |= SplatValue.shl(SplatBitSize); 3860 3861 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3862 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3863 if (SplatBitSize % BitWidth == 0) { 3864 Constant = APInt::getAllOnesValue(BitWidth); 3865 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3866 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3867 } 3868 } 3869 } 3870 3871 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3872 // actually legal and isn't going to get expanded, else this is a false 3873 // optimisation. 3874 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3875 Load->getValueType(0), 3876 Load->getMemoryVT()); 3877 3878 // Resize the constant to the same size as the original memory access before 3879 // extension. If it is still the AllOnesValue then this AND is completely 3880 // unneeded. 3881 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3882 3883 bool B; 3884 switch (Load->getExtensionType()) { 3885 default: B = false; break; 3886 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3887 case ISD::ZEXTLOAD: 3888 case ISD::NON_EXTLOAD: B = true; break; 3889 } 3890 3891 if (B && Constant.isAllOnesValue()) { 3892 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3893 // preserve semantics once we get rid of the AND. 3894 SDValue NewLoad(Load, 0); 3895 3896 // Fold the AND away. NewLoad may get replaced immediately. 3897 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3898 3899 if (Load->getExtensionType() == ISD::EXTLOAD) { 3900 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3901 Load->getValueType(0), SDLoc(Load), 3902 Load->getChain(), Load->getBasePtr(), 3903 Load->getOffset(), Load->getMemoryVT(), 3904 Load->getMemOperand()); 3905 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3906 if (Load->getNumValues() == 3) { 3907 // PRE/POST_INC loads have 3 values. 3908 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3909 NewLoad.getValue(2) }; 3910 CombineTo(Load, To, 3, true); 3911 } else { 3912 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3913 } 3914 } 3915 3916 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3917 } 3918 } 3919 3920 // fold (and (load x), 255) -> (zextload x, i8) 3921 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3922 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3923 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3924 (N0.getOpcode() == ISD::ANY_EXTEND && 3925 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3926 if (SDValue Res = ReduceLoadWidth(N)) { 3927 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 3928 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 3929 3930 AddToWorklist(N); 3931 CombineTo(LN0, Res, Res.getValue(1)); 3932 return SDValue(N, 0); 3933 } 3934 } 3935 3936 if (SDValue Combined = visitANDLike(N0, N1, N)) 3937 return Combined; 3938 3939 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3940 if (N0.getOpcode() == N1.getOpcode()) 3941 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3942 return Tmp; 3943 3944 // Masking the negated extension of a boolean is just the zero-extended 3945 // boolean: 3946 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3947 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3948 // 3949 // Note: the SimplifyDemandedBits fold below can make an information-losing 3950 // transform, and then we have no way to find this better fold. 3951 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3952 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) { 3953 SDValue SubRHS = N0.getOperand(1); 3954 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3955 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3956 return SubRHS; 3957 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3958 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3959 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3960 } 3961 } 3962 3963 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3964 // fold (and (sra)) -> (and (srl)) when possible. 3965 if (SimplifyDemandedBits(SDValue(N, 0))) 3966 return SDValue(N, 0); 3967 3968 // fold (zext_inreg (extload x)) -> (zextload x) 3969 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3970 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3971 EVT MemVT = LN0->getMemoryVT(); 3972 // If we zero all the possible extended bits, then we can turn this into 3973 // a zextload if we are running before legalize or the operation is legal. 3974 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3975 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3976 BitWidth - MemVT.getScalarSizeInBits())) && 3977 ((!LegalOperations && !LN0->isVolatile()) || 3978 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3979 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3980 LN0->getChain(), LN0->getBasePtr(), 3981 MemVT, LN0->getMemOperand()); 3982 AddToWorklist(N); 3983 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3984 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3985 } 3986 } 3987 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3988 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3989 N0.hasOneUse()) { 3990 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3991 EVT MemVT = LN0->getMemoryVT(); 3992 // If we zero all the possible extended bits, then we can turn this into 3993 // a zextload if we are running before legalize or the operation is legal. 3994 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3995 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3996 BitWidth - MemVT.getScalarSizeInBits())) && 3997 ((!LegalOperations && !LN0->isVolatile()) || 3998 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3999 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 4000 LN0->getChain(), LN0->getBasePtr(), 4001 MemVT, LN0->getMemOperand()); 4002 AddToWorklist(N); 4003 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4004 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4005 } 4006 } 4007 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 4008 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 4009 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 4010 N0.getOperand(1), false)) 4011 return BSwap; 4012 } 4013 4014 return SDValue(); 4015 } 4016 4017 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 4018 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 4019 bool DemandHighBits) { 4020 if (!LegalOperations) 4021 return SDValue(); 4022 4023 EVT VT = N->getValueType(0); 4024 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 4025 return SDValue(); 4026 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4027 return SDValue(); 4028 4029 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 4030 bool LookPassAnd0 = false; 4031 bool LookPassAnd1 = false; 4032 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 4033 std::swap(N0, N1); 4034 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 4035 std::swap(N0, N1); 4036 if (N0.getOpcode() == ISD::AND) { 4037 if (!N0.getNode()->hasOneUse()) 4038 return SDValue(); 4039 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4040 if (!N01C || N01C->getZExtValue() != 0xFF00) 4041 return SDValue(); 4042 N0 = N0.getOperand(0); 4043 LookPassAnd0 = true; 4044 } 4045 4046 if (N1.getOpcode() == ISD::AND) { 4047 if (!N1.getNode()->hasOneUse()) 4048 return SDValue(); 4049 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4050 if (!N11C || N11C->getZExtValue() != 0xFF) 4051 return SDValue(); 4052 N1 = N1.getOperand(0); 4053 LookPassAnd1 = true; 4054 } 4055 4056 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 4057 std::swap(N0, N1); 4058 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 4059 return SDValue(); 4060 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4061 return SDValue(); 4062 4063 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4064 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4065 if (!N01C || !N11C) 4066 return SDValue(); 4067 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4068 return SDValue(); 4069 4070 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4071 SDValue N00 = N0->getOperand(0); 4072 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4073 if (!N00.getNode()->hasOneUse()) 4074 return SDValue(); 4075 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4076 if (!N001C || N001C->getZExtValue() != 0xFF) 4077 return SDValue(); 4078 N00 = N00.getOperand(0); 4079 LookPassAnd0 = true; 4080 } 4081 4082 SDValue N10 = N1->getOperand(0); 4083 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4084 if (!N10.getNode()->hasOneUse()) 4085 return SDValue(); 4086 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4087 if (!N101C || N101C->getZExtValue() != 0xFF00) 4088 return SDValue(); 4089 N10 = N10.getOperand(0); 4090 LookPassAnd1 = true; 4091 } 4092 4093 if (N00 != N10) 4094 return SDValue(); 4095 4096 // Make sure everything beyond the low halfword gets set to zero since the SRL 4097 // 16 will clear the top bits. 4098 unsigned OpSizeInBits = VT.getSizeInBits(); 4099 if (DemandHighBits && OpSizeInBits > 16) { 4100 // If the left-shift isn't masked out then the only way this is a bswap is 4101 // if all bits beyond the low 8 are 0. In that case the entire pattern 4102 // reduces to a left shift anyway: leave it for other parts of the combiner. 4103 if (!LookPassAnd0) 4104 return SDValue(); 4105 4106 // However, if the right shift isn't masked out then it might be because 4107 // it's not needed. See if we can spot that too. 4108 if (!LookPassAnd1 && 4109 !DAG.MaskedValueIsZero( 4110 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4111 return SDValue(); 4112 } 4113 4114 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4115 if (OpSizeInBits > 16) { 4116 SDLoc DL(N); 4117 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4118 DAG.getConstant(OpSizeInBits - 16, DL, 4119 getShiftAmountTy(VT))); 4120 } 4121 return Res; 4122 } 4123 4124 /// Return true if the specified node is an element that makes up a 32-bit 4125 /// packed halfword byteswap. 4126 /// ((x & 0x000000ff) << 8) | 4127 /// ((x & 0x0000ff00) >> 8) | 4128 /// ((x & 0x00ff0000) << 8) | 4129 /// ((x & 0xff000000) >> 8) 4130 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4131 if (!N.getNode()->hasOneUse()) 4132 return false; 4133 4134 unsigned Opc = N.getOpcode(); 4135 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4136 return false; 4137 4138 SDValue N0 = N.getOperand(0); 4139 unsigned Opc0 = N0.getOpcode(); 4140 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4141 return false; 4142 4143 ConstantSDNode *N1C = nullptr; 4144 // SHL or SRL: look upstream for AND mask operand 4145 if (Opc == ISD::AND) 4146 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4147 else if (Opc0 == ISD::AND) 4148 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4149 if (!N1C) 4150 return false; 4151 4152 unsigned MaskByteOffset; 4153 switch (N1C->getZExtValue()) { 4154 default: 4155 return false; 4156 case 0xFF: MaskByteOffset = 0; break; 4157 case 0xFF00: MaskByteOffset = 1; break; 4158 case 0xFF0000: MaskByteOffset = 2; break; 4159 case 0xFF000000: MaskByteOffset = 3; break; 4160 } 4161 4162 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4163 if (Opc == ISD::AND) { 4164 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4165 // (x >> 8) & 0xff 4166 // (x >> 8) & 0xff0000 4167 if (Opc0 != ISD::SRL) 4168 return false; 4169 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4170 if (!C || C->getZExtValue() != 8) 4171 return false; 4172 } else { 4173 // (x << 8) & 0xff00 4174 // (x << 8) & 0xff000000 4175 if (Opc0 != ISD::SHL) 4176 return false; 4177 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4178 if (!C || C->getZExtValue() != 8) 4179 return false; 4180 } 4181 } else if (Opc == ISD::SHL) { 4182 // (x & 0xff) << 8 4183 // (x & 0xff0000) << 8 4184 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4185 return false; 4186 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4187 if (!C || C->getZExtValue() != 8) 4188 return false; 4189 } else { // Opc == ISD::SRL 4190 // (x & 0xff00) >> 8 4191 // (x & 0xff000000) >> 8 4192 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4193 return false; 4194 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4195 if (!C || C->getZExtValue() != 8) 4196 return false; 4197 } 4198 4199 if (Parts[MaskByteOffset]) 4200 return false; 4201 4202 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4203 return true; 4204 } 4205 4206 /// Match a 32-bit packed halfword bswap. That is 4207 /// ((x & 0x000000ff) << 8) | 4208 /// ((x & 0x0000ff00) >> 8) | 4209 /// ((x & 0x00ff0000) << 8) | 4210 /// ((x & 0xff000000) >> 8) 4211 /// => (rotl (bswap x), 16) 4212 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4213 if (!LegalOperations) 4214 return SDValue(); 4215 4216 EVT VT = N->getValueType(0); 4217 if (VT != MVT::i32) 4218 return SDValue(); 4219 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4220 return SDValue(); 4221 4222 // Look for either 4223 // (or (or (and), (and)), (or (and), (and))) 4224 // (or (or (or (and), (and)), (and)), (and)) 4225 if (N0.getOpcode() != ISD::OR) 4226 return SDValue(); 4227 SDValue N00 = N0.getOperand(0); 4228 SDValue N01 = N0.getOperand(1); 4229 SDNode *Parts[4] = {}; 4230 4231 if (N1.getOpcode() == ISD::OR && 4232 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4233 // (or (or (and), (and)), (or (and), (and))) 4234 if (!isBSwapHWordElement(N00, Parts)) 4235 return SDValue(); 4236 4237 if (!isBSwapHWordElement(N01, Parts)) 4238 return SDValue(); 4239 SDValue N10 = N1.getOperand(0); 4240 if (!isBSwapHWordElement(N10, Parts)) 4241 return SDValue(); 4242 SDValue N11 = N1.getOperand(1); 4243 if (!isBSwapHWordElement(N11, Parts)) 4244 return SDValue(); 4245 } else { 4246 // (or (or (or (and), (and)), (and)), (and)) 4247 if (!isBSwapHWordElement(N1, Parts)) 4248 return SDValue(); 4249 if (!isBSwapHWordElement(N01, Parts)) 4250 return SDValue(); 4251 if (N00.getOpcode() != ISD::OR) 4252 return SDValue(); 4253 SDValue N000 = N00.getOperand(0); 4254 if (!isBSwapHWordElement(N000, Parts)) 4255 return SDValue(); 4256 SDValue N001 = N00.getOperand(1); 4257 if (!isBSwapHWordElement(N001, Parts)) 4258 return SDValue(); 4259 } 4260 4261 // Make sure the parts are all coming from the same node. 4262 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4263 return SDValue(); 4264 4265 SDLoc DL(N); 4266 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4267 SDValue(Parts[0], 0)); 4268 4269 // Result of the bswap should be rotated by 16. If it's not legal, then 4270 // do (x << 16) | (x >> 16). 4271 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4272 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4273 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4274 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4275 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4276 return DAG.getNode(ISD::OR, DL, VT, 4277 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4278 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4279 } 4280 4281 /// This contains all DAGCombine rules which reduce two values combined by 4282 /// an Or operation to a single value \see visitANDLike(). 4283 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4284 EVT VT = N1.getValueType(); 4285 SDLoc DL(N); 4286 4287 // fold (or x, undef) -> -1 4288 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4289 return DAG.getAllOnesConstant(DL, VT); 4290 4291 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4292 return V; 4293 4294 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4295 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4296 // Don't increase # computations. 4297 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4298 // We can only do this xform if we know that bits from X that are set in C2 4299 // but not in C1 are already zero. Likewise for Y. 4300 if (const ConstantSDNode *N0O1C = 4301 getAsNonOpaqueConstant(N0.getOperand(1))) { 4302 if (const ConstantSDNode *N1O1C = 4303 getAsNonOpaqueConstant(N1.getOperand(1))) { 4304 // We can only do this xform if we know that bits from X that are set in 4305 // C2 but not in C1 are already zero. Likewise for Y. 4306 const APInt &LHSMask = N0O1C->getAPIntValue(); 4307 const APInt &RHSMask = N1O1C->getAPIntValue(); 4308 4309 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4310 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4311 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4312 N0.getOperand(0), N1.getOperand(0)); 4313 return DAG.getNode(ISD::AND, DL, VT, X, 4314 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4315 } 4316 } 4317 } 4318 } 4319 4320 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4321 if (N0.getOpcode() == ISD::AND && 4322 N1.getOpcode() == ISD::AND && 4323 N0.getOperand(0) == N1.getOperand(0) && 4324 // Don't increase # computations. 4325 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4326 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4327 N0.getOperand(1), N1.getOperand(1)); 4328 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4329 } 4330 4331 return SDValue(); 4332 } 4333 4334 SDValue DAGCombiner::visitOR(SDNode *N) { 4335 SDValue N0 = N->getOperand(0); 4336 SDValue N1 = N->getOperand(1); 4337 EVT VT = N1.getValueType(); 4338 4339 // x | x --> x 4340 if (N0 == N1) 4341 return N0; 4342 4343 // fold vector ops 4344 if (VT.isVector()) { 4345 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4346 return FoldedVOp; 4347 4348 // fold (or x, 0) -> x, vector edition 4349 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4350 return N1; 4351 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4352 return N0; 4353 4354 // fold (or x, -1) -> -1, vector edition 4355 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4356 // do not return N0, because undef node may exist in N0 4357 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4358 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4359 // do not return N1, because undef node may exist in N1 4360 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4361 4362 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4363 // Do this only if the resulting shuffle is legal. 4364 if (isa<ShuffleVectorSDNode>(N0) && 4365 isa<ShuffleVectorSDNode>(N1) && 4366 // Avoid folding a node with illegal type. 4367 TLI.isTypeLegal(VT)) { 4368 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4369 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4370 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4371 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4372 // Ensure both shuffles have a zero input. 4373 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4374 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4375 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4376 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4377 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4378 bool CanFold = true; 4379 int NumElts = VT.getVectorNumElements(); 4380 SmallVector<int, 4> Mask(NumElts); 4381 4382 for (int i = 0; i != NumElts; ++i) { 4383 int M0 = SV0->getMaskElt(i); 4384 int M1 = SV1->getMaskElt(i); 4385 4386 // Determine if either index is pointing to a zero vector. 4387 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4388 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4389 4390 // If one element is zero and the otherside is undef, keep undef. 4391 // This also handles the case that both are undef. 4392 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4393 Mask[i] = -1; 4394 continue; 4395 } 4396 4397 // Make sure only one of the elements is zero. 4398 if (M0Zero == M1Zero) { 4399 CanFold = false; 4400 break; 4401 } 4402 4403 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4404 4405 // We have a zero and non-zero element. If the non-zero came from 4406 // SV0 make the index a LHS index. If it came from SV1, make it 4407 // a RHS index. We need to mod by NumElts because we don't care 4408 // which operand it came from in the original shuffles. 4409 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4410 } 4411 4412 if (CanFold) { 4413 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4414 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4415 4416 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4417 if (!LegalMask) { 4418 std::swap(NewLHS, NewRHS); 4419 ShuffleVectorSDNode::commuteMask(Mask); 4420 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4421 } 4422 4423 if (LegalMask) 4424 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4425 } 4426 } 4427 } 4428 } 4429 4430 // fold (or c1, c2) -> c1|c2 4431 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4432 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4433 if (N0C && N1C && !N1C->isOpaque()) 4434 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4435 // canonicalize constant to RHS 4436 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4437 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4438 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4439 // fold (or x, 0) -> x 4440 if (isNullConstant(N1)) 4441 return N0; 4442 // fold (or x, -1) -> -1 4443 if (isAllOnesConstant(N1)) 4444 return N1; 4445 4446 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4447 return NewSel; 4448 4449 // fold (or x, c) -> c iff (x & ~c) == 0 4450 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4451 return N1; 4452 4453 if (SDValue Combined = visitORLike(N0, N1, N)) 4454 return Combined; 4455 4456 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4457 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4458 return BSwap; 4459 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4460 return BSwap; 4461 4462 // reassociate or 4463 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4464 return ROR; 4465 4466 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4467 // iff (c1 & c2) != 0. 4468 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) { 4469 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4470 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) { 4471 if (SDValue COR = 4472 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1)) 4473 return DAG.getNode( 4474 ISD::AND, SDLoc(N), VT, 4475 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4476 return SDValue(); 4477 } 4478 } 4479 } 4480 4481 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4482 if (N0.getOpcode() == N1.getOpcode()) 4483 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4484 return Tmp; 4485 4486 // See if this is some rotate idiom. 4487 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4488 return SDValue(Rot, 0); 4489 4490 if (SDValue Load = MatchLoadCombine(N)) 4491 return Load; 4492 4493 // Simplify the operands using demanded-bits information. 4494 if (SimplifyDemandedBits(SDValue(N, 0))) 4495 return SDValue(N, 0); 4496 4497 return SDValue(); 4498 } 4499 4500 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4501 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4502 if (Op.getOpcode() == ISD::AND) { 4503 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4504 Mask = Op.getOperand(1); 4505 Op = Op.getOperand(0); 4506 } else { 4507 return false; 4508 } 4509 } 4510 4511 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4512 Shift = Op; 4513 return true; 4514 } 4515 4516 return false; 4517 } 4518 4519 // Return true if we can prove that, whenever Neg and Pos are both in the 4520 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4521 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4522 // 4523 // (or (shift1 X, Neg), (shift2 X, Pos)) 4524 // 4525 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4526 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4527 // to consider shift amounts with defined behavior. 4528 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4529 // If EltSize is a power of 2 then: 4530 // 4531 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4532 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4533 // 4534 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4535 // for the stronger condition: 4536 // 4537 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4538 // 4539 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4540 // we can just replace Neg with Neg' for the rest of the function. 4541 // 4542 // In other cases we check for the even stronger condition: 4543 // 4544 // Neg == EltSize - Pos [B] 4545 // 4546 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4547 // behavior if Pos == 0 (and consequently Neg == EltSize). 4548 // 4549 // We could actually use [A] whenever EltSize is a power of 2, but the 4550 // only extra cases that it would match are those uninteresting ones 4551 // where Neg and Pos are never in range at the same time. E.g. for 4552 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4553 // as well as (sub 32, Pos), but: 4554 // 4555 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4556 // 4557 // always invokes undefined behavior for 32-bit X. 4558 // 4559 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4560 unsigned MaskLoBits = 0; 4561 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4562 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4563 if (NegC->getAPIntValue() == EltSize - 1) { 4564 Neg = Neg.getOperand(0); 4565 MaskLoBits = Log2_64(EltSize); 4566 } 4567 } 4568 } 4569 4570 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4571 if (Neg.getOpcode() != ISD::SUB) 4572 return false; 4573 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4574 if (!NegC) 4575 return false; 4576 SDValue NegOp1 = Neg.getOperand(1); 4577 4578 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4579 // Pos'. The truncation is redundant for the purpose of the equality. 4580 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4581 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4582 if (PosC->getAPIntValue() == EltSize - 1) 4583 Pos = Pos.getOperand(0); 4584 4585 // The condition we need is now: 4586 // 4587 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4588 // 4589 // If NegOp1 == Pos then we need: 4590 // 4591 // EltSize & Mask == NegC & Mask 4592 // 4593 // (because "x & Mask" is a truncation and distributes through subtraction). 4594 APInt Width; 4595 if (Pos == NegOp1) 4596 Width = NegC->getAPIntValue(); 4597 4598 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4599 // Then the condition we want to prove becomes: 4600 // 4601 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4602 // 4603 // which, again because "x & Mask" is a truncation, becomes: 4604 // 4605 // NegC & Mask == (EltSize - PosC) & Mask 4606 // EltSize & Mask == (NegC + PosC) & Mask 4607 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4608 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4609 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4610 else 4611 return false; 4612 } else 4613 return false; 4614 4615 // Now we just need to check that EltSize & Mask == Width & Mask. 4616 if (MaskLoBits) 4617 // EltSize & Mask is 0 since Mask is EltSize - 1. 4618 return Width.getLoBits(MaskLoBits) == 0; 4619 return Width == EltSize; 4620 } 4621 4622 // A subroutine of MatchRotate used once we have found an OR of two opposite 4623 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4624 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4625 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4626 // Neg with outer conversions stripped away. 4627 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4628 SDValue Neg, SDValue InnerPos, 4629 SDValue InnerNeg, unsigned PosOpcode, 4630 unsigned NegOpcode, const SDLoc &DL) { 4631 // fold (or (shl x, (*ext y)), 4632 // (srl x, (*ext (sub 32, y)))) -> 4633 // (rotl x, y) or (rotr x, (sub 32, y)) 4634 // 4635 // fold (or (shl x, (*ext (sub 32, y))), 4636 // (srl x, (*ext y))) -> 4637 // (rotr x, y) or (rotl x, (sub 32, y)) 4638 EVT VT = Shifted.getValueType(); 4639 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4640 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4641 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4642 HasPos ? Pos : Neg).getNode(); 4643 } 4644 4645 return nullptr; 4646 } 4647 4648 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4649 // idioms for rotate, and if the target supports rotation instructions, generate 4650 // a rot[lr]. 4651 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4652 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4653 EVT VT = LHS.getValueType(); 4654 if (!TLI.isTypeLegal(VT)) return nullptr; 4655 4656 // The target must have at least one rotate flavor. 4657 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4658 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4659 if (!HasROTL && !HasROTR) return nullptr; 4660 4661 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4662 SDValue LHSShift; // The shift. 4663 SDValue LHSMask; // AND value if any. 4664 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4665 return nullptr; // Not part of a rotate. 4666 4667 SDValue RHSShift; // The shift. 4668 SDValue RHSMask; // AND value if any. 4669 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4670 return nullptr; // Not part of a rotate. 4671 4672 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4673 return nullptr; // Not shifting the same value. 4674 4675 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4676 return nullptr; // Shifts must disagree. 4677 4678 // Canonicalize shl to left side in a shl/srl pair. 4679 if (RHSShift.getOpcode() == ISD::SHL) { 4680 std::swap(LHS, RHS); 4681 std::swap(LHSShift, RHSShift); 4682 std::swap(LHSMask, RHSMask); 4683 } 4684 4685 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4686 SDValue LHSShiftArg = LHSShift.getOperand(0); 4687 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4688 SDValue RHSShiftArg = RHSShift.getOperand(0); 4689 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4690 4691 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4692 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4693 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 4694 ConstantSDNode *RHS) { 4695 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 4696 }; 4697 if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 4698 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4699 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4700 4701 // If there is an AND of either shifted operand, apply it to the result. 4702 if (LHSMask.getNode() || RHSMask.getNode()) { 4703 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4704 SDValue Mask = AllOnes; 4705 4706 if (LHSMask.getNode()) { 4707 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 4708 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4709 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 4710 } 4711 if (RHSMask.getNode()) { 4712 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 4713 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4714 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 4715 } 4716 4717 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4718 } 4719 4720 return Rot.getNode(); 4721 } 4722 4723 // If there is a mask here, and we have a variable shift, we can't be sure 4724 // that we're masking out the right stuff. 4725 if (LHSMask.getNode() || RHSMask.getNode()) 4726 return nullptr; 4727 4728 // If the shift amount is sign/zext/any-extended just peel it off. 4729 SDValue LExtOp0 = LHSShiftAmt; 4730 SDValue RExtOp0 = RHSShiftAmt; 4731 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4732 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4733 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4734 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4735 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4736 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4737 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4738 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4739 LExtOp0 = LHSShiftAmt.getOperand(0); 4740 RExtOp0 = RHSShiftAmt.getOperand(0); 4741 } 4742 4743 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4744 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4745 if (TryL) 4746 return TryL; 4747 4748 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4749 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4750 if (TryR) 4751 return TryR; 4752 4753 return nullptr; 4754 } 4755 4756 namespace { 4757 4758 /// Represents known origin of an individual byte in load combine pattern. The 4759 /// value of the byte is either constant zero or comes from memory. 4760 struct ByteProvider { 4761 // For constant zero providers Load is set to nullptr. For memory providers 4762 // Load represents the node which loads the byte from memory. 4763 // ByteOffset is the offset of the byte in the value produced by the load. 4764 LoadSDNode *Load = nullptr; 4765 unsigned ByteOffset = 0; 4766 4767 ByteProvider() = default; 4768 4769 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4770 return ByteProvider(Load, ByteOffset); 4771 } 4772 4773 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4774 4775 bool isConstantZero() const { return !Load; } 4776 bool isMemory() const { return Load; } 4777 4778 bool operator==(const ByteProvider &Other) const { 4779 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4780 } 4781 4782 private: 4783 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4784 : Load(Load), ByteOffset(ByteOffset) {} 4785 }; 4786 4787 } // end anonymous namespace 4788 4789 /// Recursively traverses the expression calculating the origin of the requested 4790 /// byte of the given value. Returns None if the provider can't be calculated. 4791 /// 4792 /// For all the values except the root of the expression verifies that the value 4793 /// has exactly one use and if it's not true return None. This way if the origin 4794 /// of the byte is returned it's guaranteed that the values which contribute to 4795 /// the byte are not used outside of this expression. 4796 /// 4797 /// Because the parts of the expression are not allowed to have more than one 4798 /// use this function iterates over trees, not DAGs. So it never visits the same 4799 /// node more than once. 4800 static const Optional<ByteProvider> 4801 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 4802 bool Root = false) { 4803 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4804 if (Depth == 10) 4805 return None; 4806 4807 if (!Root && !Op.hasOneUse()) 4808 return None; 4809 4810 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4811 unsigned BitWidth = Op.getValueSizeInBits(); 4812 if (BitWidth % 8 != 0) 4813 return None; 4814 unsigned ByteWidth = BitWidth / 8; 4815 assert(Index < ByteWidth && "invalid index requested"); 4816 (void) ByteWidth; 4817 4818 switch (Op.getOpcode()) { 4819 case ISD::OR: { 4820 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4821 if (!LHS) 4822 return None; 4823 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4824 if (!RHS) 4825 return None; 4826 4827 if (LHS->isConstantZero()) 4828 return RHS; 4829 if (RHS->isConstantZero()) 4830 return LHS; 4831 return None; 4832 } 4833 case ISD::SHL: { 4834 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4835 if (!ShiftOp) 4836 return None; 4837 4838 uint64_t BitShift = ShiftOp->getZExtValue(); 4839 if (BitShift % 8 != 0) 4840 return None; 4841 uint64_t ByteShift = BitShift / 8; 4842 4843 return Index < ByteShift 4844 ? ByteProvider::getConstantZero() 4845 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4846 Depth + 1); 4847 } 4848 case ISD::ANY_EXTEND: 4849 case ISD::SIGN_EXTEND: 4850 case ISD::ZERO_EXTEND: { 4851 SDValue NarrowOp = Op->getOperand(0); 4852 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4853 if (NarrowBitWidth % 8 != 0) 4854 return None; 4855 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4856 4857 if (Index >= NarrowByteWidth) 4858 return Op.getOpcode() == ISD::ZERO_EXTEND 4859 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4860 : None; 4861 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4862 } 4863 case ISD::BSWAP: 4864 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4865 Depth + 1); 4866 case ISD::LOAD: { 4867 auto L = cast<LoadSDNode>(Op.getNode()); 4868 if (L->isVolatile() || L->isIndexed()) 4869 return None; 4870 4871 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4872 if (NarrowBitWidth % 8 != 0) 4873 return None; 4874 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4875 4876 if (Index >= NarrowByteWidth) 4877 return L->getExtensionType() == ISD::ZEXTLOAD 4878 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4879 : None; 4880 return ByteProvider::getMemory(L, Index); 4881 } 4882 } 4883 4884 return None; 4885 } 4886 4887 /// Match a pattern where a wide type scalar value is loaded by several narrow 4888 /// loads and combined by shifts and ors. Fold it into a single load or a load 4889 /// and a BSWAP if the targets supports it. 4890 /// 4891 /// Assuming little endian target: 4892 /// i8 *a = ... 4893 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4894 /// => 4895 /// i32 val = *((i32)a) 4896 /// 4897 /// i8 *a = ... 4898 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4899 /// => 4900 /// i32 val = BSWAP(*((i32)a)) 4901 /// 4902 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4903 /// interact well with the worklist mechanism. When a part of the pattern is 4904 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4905 /// but the root node of the pattern which triggers the load combine is not 4906 /// necessarily a direct user of the changed node. For example, once the address 4907 /// of t28 load is reassociated load combine won't be triggered: 4908 /// t25: i32 = add t4, Constant:i32<2> 4909 /// t26: i64 = sign_extend t25 4910 /// t27: i64 = add t2, t26 4911 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4912 /// t29: i32 = zero_extend t28 4913 /// t32: i32 = shl t29, Constant:i8<8> 4914 /// t33: i32 = or t23, t32 4915 /// As a possible fix visitLoad can check if the load can be a part of a load 4916 /// combine pattern and add corresponding OR roots to the worklist. 4917 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4918 assert(N->getOpcode() == ISD::OR && 4919 "Can only match load combining against OR nodes"); 4920 4921 // Handles simple types only 4922 EVT VT = N->getValueType(0); 4923 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4924 return SDValue(); 4925 unsigned ByteWidth = VT.getSizeInBits() / 8; 4926 4927 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4928 // Before legalize we can introduce too wide illegal loads which will be later 4929 // split into legal sized loads. This enables us to combine i64 load by i8 4930 // patterns to a couple of i32 loads on 32 bit targets. 4931 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4932 return SDValue(); 4933 4934 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4935 unsigned BW, unsigned i) { return i; }; 4936 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4937 unsigned BW, unsigned i) { return BW - i - 1; }; 4938 4939 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4940 auto MemoryByteOffset = [&] (ByteProvider P) { 4941 assert(P.isMemory() && "Must be a memory byte provider"); 4942 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4943 assert(LoadBitWidth % 8 == 0 && 4944 "can only analyze providers for individual bytes not bit"); 4945 unsigned LoadByteWidth = LoadBitWidth / 8; 4946 return IsBigEndianTarget 4947 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4948 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4949 }; 4950 4951 Optional<BaseIndexOffset> Base; 4952 SDValue Chain; 4953 4954 SmallSet<LoadSDNode *, 8> Loads; 4955 Optional<ByteProvider> FirstByteProvider; 4956 int64_t FirstOffset = INT64_MAX; 4957 4958 // Check if all the bytes of the OR we are looking at are loaded from the same 4959 // base address. Collect bytes offsets from Base address in ByteOffsets. 4960 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4961 for (unsigned i = 0; i < ByteWidth; i++) { 4962 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4963 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4964 return SDValue(); 4965 4966 LoadSDNode *L = P->Load; 4967 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4968 "Must be enforced by calculateByteProvider"); 4969 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4970 4971 // All loads must share the same chain 4972 SDValue LChain = L->getChain(); 4973 if (!Chain) 4974 Chain = LChain; 4975 else if (Chain != LChain) 4976 return SDValue(); 4977 4978 // Loads must share the same base address 4979 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4980 int64_t ByteOffsetFromBase = 0; 4981 if (!Base) 4982 Base = Ptr; 4983 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 4984 return SDValue(); 4985 4986 // Calculate the offset of the current byte from the base address 4987 ByteOffsetFromBase += MemoryByteOffset(*P); 4988 ByteOffsets[i] = ByteOffsetFromBase; 4989 4990 // Remember the first byte load 4991 if (ByteOffsetFromBase < FirstOffset) { 4992 FirstByteProvider = P; 4993 FirstOffset = ByteOffsetFromBase; 4994 } 4995 4996 Loads.insert(L); 4997 } 4998 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 4999 "memory, so there must be at least one load which produces the value"); 5000 assert(Base && "Base address of the accessed memory location must be set"); 5001 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5002 5003 // Check if the bytes of the OR we are looking at match with either big or 5004 // little endian value load 5005 bool BigEndian = true, LittleEndian = true; 5006 for (unsigned i = 0; i < ByteWidth; i++) { 5007 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5008 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5009 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5010 if (!BigEndian && !LittleEndian) 5011 return SDValue(); 5012 } 5013 assert((BigEndian != LittleEndian) && "should be either or"); 5014 assert(FirstByteProvider && "must be set"); 5015 5016 // Ensure that the first byte is loaded from zero offset of the first load. 5017 // So the combined value can be loaded from the first load address. 5018 if (MemoryByteOffset(*FirstByteProvider) != 0) 5019 return SDValue(); 5020 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5021 5022 // The node we are looking at matches with the pattern, check if we can 5023 // replace it with a single load and bswap if needed. 5024 5025 // If the load needs byte swap check if the target supports it 5026 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5027 5028 // Before legalize we can introduce illegal bswaps which will be later 5029 // converted to an explicit bswap sequence. This way we end up with a single 5030 // load and byte shuffling instead of several loads and byte shuffling. 5031 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5032 return SDValue(); 5033 5034 // Check that a load of the wide type is both allowed and fast on the target 5035 bool Fast = false; 5036 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5037 VT, FirstLoad->getAddressSpace(), 5038 FirstLoad->getAlignment(), &Fast); 5039 if (!Allowed || !Fast) 5040 return SDValue(); 5041 5042 SDValue NewLoad = 5043 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5044 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5045 5046 // Transfer chain users from old loads to the new load. 5047 for (LoadSDNode *L : Loads) 5048 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5049 5050 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5051 } 5052 5053 SDValue DAGCombiner::visitXOR(SDNode *N) { 5054 SDValue N0 = N->getOperand(0); 5055 SDValue N1 = N->getOperand(1); 5056 EVT VT = N0.getValueType(); 5057 5058 // fold vector ops 5059 if (VT.isVector()) { 5060 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5061 return FoldedVOp; 5062 5063 // fold (xor x, 0) -> x, vector edition 5064 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5065 return N1; 5066 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5067 return N0; 5068 } 5069 5070 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5071 if (N0.isUndef() && N1.isUndef()) 5072 return DAG.getConstant(0, SDLoc(N), VT); 5073 // fold (xor x, undef) -> undef 5074 if (N0.isUndef()) 5075 return N0; 5076 if (N1.isUndef()) 5077 return N1; 5078 // fold (xor c1, c2) -> c1^c2 5079 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5080 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5081 if (N0C && N1C) 5082 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5083 // canonicalize constant to RHS 5084 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5085 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5086 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5087 // fold (xor x, 0) -> x 5088 if (isNullConstant(N1)) 5089 return N0; 5090 5091 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5092 return NewSel; 5093 5094 // reassociate xor 5095 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5096 return RXOR; 5097 5098 // fold !(x cc y) -> (x !cc y) 5099 SDValue LHS, RHS, CC; 5100 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5101 bool isInt = LHS.getValueType().isInteger(); 5102 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5103 isInt); 5104 5105 if (!LegalOperations || 5106 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5107 switch (N0.getOpcode()) { 5108 default: 5109 llvm_unreachable("Unhandled SetCC Equivalent!"); 5110 case ISD::SETCC: 5111 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5112 case ISD::SELECT_CC: 5113 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5114 N0.getOperand(3), NotCC); 5115 } 5116 } 5117 } 5118 5119 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5120 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5121 N0.getNode()->hasOneUse() && 5122 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5123 SDValue V = N0.getOperand(0); 5124 SDLoc DL(N0); 5125 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5126 DAG.getConstant(1, DL, V.getValueType())); 5127 AddToWorklist(V.getNode()); 5128 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5129 } 5130 5131 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5132 if (isOneConstant(N1) && VT == MVT::i1 && 5133 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5134 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5135 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5136 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5137 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5138 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5139 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5140 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5141 } 5142 } 5143 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5144 if (isAllOnesConstant(N1) && 5145 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5146 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5147 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5148 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5149 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5150 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5151 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5152 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5153 } 5154 } 5155 // fold (xor (and x, y), y) -> (and (not x), y) 5156 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5157 N0->getOperand(1) == N1) { 5158 SDValue X = N0->getOperand(0); 5159 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5160 AddToWorklist(NotX.getNode()); 5161 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5162 } 5163 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 5164 if (N1C && N0.getOpcode() == ISD::XOR) { 5165 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 5166 SDLoc DL(N); 5167 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 5168 DAG.getConstant(N1C->getAPIntValue() ^ 5169 N00C->getAPIntValue(), DL, VT)); 5170 } 5171 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 5172 SDLoc DL(N); 5173 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 5174 DAG.getConstant(N1C->getAPIntValue() ^ 5175 N01C->getAPIntValue(), DL, VT)); 5176 } 5177 } 5178 5179 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5180 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5181 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5182 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5183 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5184 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5185 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5186 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5187 } 5188 5189 // fold (xor x, x) -> 0 5190 if (N0 == N1) 5191 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5192 5193 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5194 // Here is a concrete example of this equivalence: 5195 // i16 x == 14 5196 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5197 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5198 // 5199 // => 5200 // 5201 // i16 ~1 == 0b1111111111111110 5202 // i16 rol(~1, 14) == 0b1011111111111111 5203 // 5204 // Some additional tips to help conceptualize this transform: 5205 // - Try to see the operation as placing a single zero in a value of all ones. 5206 // - There exists no value for x which would allow the result to contain zero. 5207 // - Values of x larger than the bitwidth are undefined and do not require a 5208 // consistent result. 5209 // - Pushing the zero left requires shifting one bits in from the right. 5210 // A rotate left of ~1 is a nice way of achieving the desired result. 5211 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5212 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5213 SDLoc DL(N); 5214 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5215 N0.getOperand(1)); 5216 } 5217 5218 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5219 if (N0.getOpcode() == N1.getOpcode()) 5220 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5221 return Tmp; 5222 5223 // Simplify the expression using non-local knowledge. 5224 if (SimplifyDemandedBits(SDValue(N, 0))) 5225 return SDValue(N, 0); 5226 5227 return SDValue(); 5228 } 5229 5230 /// Handle transforms common to the three shifts, when the shift amount is a 5231 /// constant. 5232 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5233 SDNode *LHS = N->getOperand(0).getNode(); 5234 if (!LHS->hasOneUse()) return SDValue(); 5235 5236 // We want to pull some binops through shifts, so that we have (and (shift)) 5237 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5238 // thing happens with address calculations, so it's important to canonicalize 5239 // it. 5240 bool HighBitSet = false; // Can we transform this if the high bit is set? 5241 5242 switch (LHS->getOpcode()) { 5243 default: return SDValue(); 5244 case ISD::OR: 5245 case ISD::XOR: 5246 HighBitSet = false; // We can only transform sra if the high bit is clear. 5247 break; 5248 case ISD::AND: 5249 HighBitSet = true; // We can only transform sra if the high bit is set. 5250 break; 5251 case ISD::ADD: 5252 if (N->getOpcode() != ISD::SHL) 5253 return SDValue(); // only shl(add) not sr[al](add). 5254 HighBitSet = false; // We can only transform sra if the high bit is clear. 5255 break; 5256 } 5257 5258 // We require the RHS of the binop to be a constant and not opaque as well. 5259 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5260 if (!BinOpCst) return SDValue(); 5261 5262 // FIXME: disable this unless the input to the binop is a shift by a constant 5263 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5264 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5265 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5266 BinOpLHSVal->getOpcode() == ISD::SRA || 5267 BinOpLHSVal->getOpcode() == ISD::SRL; 5268 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5269 BinOpLHSVal->getOpcode() == ISD::SELECT; 5270 5271 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5272 !isCopyOrSelect) 5273 return SDValue(); 5274 5275 if (isCopyOrSelect && N->hasOneUse()) 5276 return SDValue(); 5277 5278 EVT VT = N->getValueType(0); 5279 5280 // If this is a signed shift right, and the high bit is modified by the 5281 // logical operation, do not perform the transformation. The highBitSet 5282 // boolean indicates the value of the high bit of the constant which would 5283 // cause it to be modified for this operation. 5284 if (N->getOpcode() == ISD::SRA) { 5285 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5286 if (BinOpRHSSignSet != HighBitSet) 5287 return SDValue(); 5288 } 5289 5290 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5291 return SDValue(); 5292 5293 // Fold the constants, shifting the binop RHS by the shift amount. 5294 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5295 N->getValueType(0), 5296 LHS->getOperand(1), N->getOperand(1)); 5297 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5298 5299 // Create the new shift. 5300 SDValue NewShift = DAG.getNode(N->getOpcode(), 5301 SDLoc(LHS->getOperand(0)), 5302 VT, LHS->getOperand(0), N->getOperand(1)); 5303 5304 // Create the new binop. 5305 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5306 } 5307 5308 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5309 assert(N->getOpcode() == ISD::TRUNCATE); 5310 assert(N->getOperand(0).getOpcode() == ISD::AND); 5311 5312 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5313 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5314 SDValue N01 = N->getOperand(0).getOperand(1); 5315 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5316 SDLoc DL(N); 5317 EVT TruncVT = N->getValueType(0); 5318 SDValue N00 = N->getOperand(0).getOperand(0); 5319 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5320 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5321 AddToWorklist(Trunc00.getNode()); 5322 AddToWorklist(Trunc01.getNode()); 5323 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5324 } 5325 } 5326 5327 return SDValue(); 5328 } 5329 5330 SDValue DAGCombiner::visitRotate(SDNode *N) { 5331 SDLoc dl(N); 5332 SDValue N0 = N->getOperand(0); 5333 SDValue N1 = N->getOperand(1); 5334 EVT VT = N->getValueType(0); 5335 unsigned Bitsize = VT.getScalarSizeInBits(); 5336 5337 // fold (rot x, 0) -> x 5338 if (isNullConstantOrNullSplatConstant(N1)) 5339 return N0; 5340 5341 // fold (rot x, c) -> (rot x, c % BitSize) 5342 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 5343 if (Cst->getAPIntValue().uge(Bitsize)) { 5344 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 5345 return DAG.getNode(N->getOpcode(), dl, VT, N0, 5346 DAG.getConstant(RotAmt, dl, N1.getValueType())); 5347 } 5348 } 5349 5350 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5351 if (N1.getOpcode() == ISD::TRUNCATE && 5352 N1.getOperand(0).getOpcode() == ISD::AND) { 5353 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5354 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 5355 } 5356 5357 unsigned NextOp = N0.getOpcode(); 5358 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 5359 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 5360 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 5361 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 5362 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 5363 EVT ShiftVT = C1->getValueType(0); 5364 bool SameSide = (N->getOpcode() == NextOp); 5365 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 5366 if (SDValue CombinedShift = 5367 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 5368 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 5369 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 5370 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 5371 BitsizeC.getNode()); 5372 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 5373 CombinedShiftNorm); 5374 } 5375 } 5376 } 5377 return SDValue(); 5378 } 5379 5380 SDValue DAGCombiner::visitSHL(SDNode *N) { 5381 SDValue N0 = N->getOperand(0); 5382 SDValue N1 = N->getOperand(1); 5383 EVT VT = N0.getValueType(); 5384 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5385 5386 // fold vector ops 5387 if (VT.isVector()) { 5388 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5389 return FoldedVOp; 5390 5391 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5392 // If setcc produces all-one true value then: 5393 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5394 if (N1CV && N1CV->isConstant()) { 5395 if (N0.getOpcode() == ISD::AND) { 5396 SDValue N00 = N0->getOperand(0); 5397 SDValue N01 = N0->getOperand(1); 5398 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5399 5400 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5401 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5402 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5403 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5404 N01CV, N1CV)) 5405 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5406 } 5407 } 5408 } 5409 } 5410 5411 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5412 5413 // fold (shl c1, c2) -> c1<<c2 5414 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5415 if (N0C && N1C && !N1C->isOpaque()) 5416 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5417 // fold (shl 0, x) -> 0 5418 if (isNullConstantOrNullSplatConstant(N0)) 5419 return N0; 5420 // fold (shl x, c >= size(x)) -> undef 5421 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5422 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5423 return Val->getAPIntValue().uge(OpSizeInBits); 5424 }; 5425 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5426 return DAG.getUNDEF(VT); 5427 // fold (shl x, 0) -> x 5428 if (N1C && N1C->isNullValue()) 5429 return N0; 5430 // fold (shl undef, x) -> 0 5431 if (N0.isUndef()) 5432 return DAG.getConstant(0, SDLoc(N), VT); 5433 5434 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5435 return NewSel; 5436 5437 // if (shl x, c) is known to be zero, return 0 5438 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5439 APInt::getAllOnesValue(OpSizeInBits))) 5440 return DAG.getConstant(0, SDLoc(N), VT); 5441 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5442 if (N1.getOpcode() == ISD::TRUNCATE && 5443 N1.getOperand(0).getOpcode() == ISD::AND) { 5444 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5445 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5446 } 5447 5448 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5449 return SDValue(N, 0); 5450 5451 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5452 if (N0.getOpcode() == ISD::SHL) { 5453 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5454 ConstantSDNode *RHS) { 5455 APInt c1 = LHS->getAPIntValue(); 5456 APInt c2 = RHS->getAPIntValue(); 5457 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5458 return (c1 + c2).uge(OpSizeInBits); 5459 }; 5460 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5461 return DAG.getConstant(0, SDLoc(N), VT); 5462 5463 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5464 ConstantSDNode *RHS) { 5465 APInt c1 = LHS->getAPIntValue(); 5466 APInt c2 = RHS->getAPIntValue(); 5467 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5468 return (c1 + c2).ult(OpSizeInBits); 5469 }; 5470 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5471 SDLoc DL(N); 5472 EVT ShiftVT = N1.getValueType(); 5473 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5474 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 5475 } 5476 } 5477 5478 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5479 // For this to be valid, the second form must not preserve any of the bits 5480 // that are shifted out by the inner shift in the first form. This means 5481 // the outer shift size must be >= the number of bits added by the ext. 5482 // As a corollary, we don't care what kind of ext it is. 5483 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5484 N0.getOpcode() == ISD::ANY_EXTEND || 5485 N0.getOpcode() == ISD::SIGN_EXTEND) && 5486 N0.getOperand(0).getOpcode() == ISD::SHL) { 5487 SDValue N0Op0 = N0.getOperand(0); 5488 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5489 APInt c1 = N0Op0C1->getAPIntValue(); 5490 APInt c2 = N1C->getAPIntValue(); 5491 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5492 5493 EVT InnerShiftVT = N0Op0.getValueType(); 5494 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5495 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5496 SDLoc DL(N0); 5497 APInt Sum = c1 + c2; 5498 if (Sum.uge(OpSizeInBits)) 5499 return DAG.getConstant(0, DL, VT); 5500 5501 return DAG.getNode( 5502 ISD::SHL, DL, VT, 5503 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5504 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5505 } 5506 } 5507 } 5508 5509 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5510 // Only fold this if the inner zext has no other uses to avoid increasing 5511 // the total number of instructions. 5512 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5513 N0.getOperand(0).getOpcode() == ISD::SRL) { 5514 SDValue N0Op0 = N0.getOperand(0); 5515 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5516 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5517 uint64_t c1 = N0Op0C1->getZExtValue(); 5518 uint64_t c2 = N1C->getZExtValue(); 5519 if (c1 == c2) { 5520 SDValue NewOp0 = N0.getOperand(0); 5521 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5522 SDLoc DL(N); 5523 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5524 NewOp0, 5525 DAG.getConstant(c2, DL, CountVT)); 5526 AddToWorklist(NewSHL.getNode()); 5527 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5528 } 5529 } 5530 } 5531 } 5532 5533 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5534 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5535 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5536 N0->getFlags().hasExact()) { 5537 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5538 uint64_t C1 = N0C1->getZExtValue(); 5539 uint64_t C2 = N1C->getZExtValue(); 5540 SDLoc DL(N); 5541 if (C1 <= C2) 5542 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5543 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5544 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5545 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5546 } 5547 } 5548 5549 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5550 // (and (srl x, (sub c1, c2), MASK) 5551 // Only fold this if the inner shift has no other uses -- if it does, folding 5552 // this will increase the total number of instructions. 5553 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5554 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5555 uint64_t c1 = N0C1->getZExtValue(); 5556 if (c1 < OpSizeInBits) { 5557 uint64_t c2 = N1C->getZExtValue(); 5558 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5559 SDValue Shift; 5560 if (c2 > c1) { 5561 Mask <<= c2 - c1; 5562 SDLoc DL(N); 5563 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5564 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5565 } else { 5566 Mask.lshrInPlace(c1 - c2); 5567 SDLoc DL(N); 5568 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5569 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5570 } 5571 SDLoc DL(N0); 5572 return DAG.getNode(ISD::AND, DL, VT, Shift, 5573 DAG.getConstant(Mask, DL, VT)); 5574 } 5575 } 5576 } 5577 5578 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5579 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5580 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5581 SDLoc DL(N); 5582 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5583 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5584 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5585 } 5586 5587 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5588 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 5589 // Variant of version done on multiply, except mul by a power of 2 is turned 5590 // into a shift. 5591 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 5592 N0.getNode()->hasOneUse() && 5593 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5594 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5595 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5596 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5597 AddToWorklist(Shl0.getNode()); 5598 AddToWorklist(Shl1.getNode()); 5599 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 5600 } 5601 5602 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5603 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5604 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5605 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5606 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5607 if (isConstantOrConstantVector(Shl)) 5608 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5609 } 5610 5611 if (N1C && !N1C->isOpaque()) 5612 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5613 return NewSHL; 5614 5615 return SDValue(); 5616 } 5617 5618 SDValue DAGCombiner::visitSRA(SDNode *N) { 5619 SDValue N0 = N->getOperand(0); 5620 SDValue N1 = N->getOperand(1); 5621 EVT VT = N0.getValueType(); 5622 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5623 5624 // Arithmetic shifting an all-sign-bit value is a no-op. 5625 // fold (sra 0, x) -> 0 5626 // fold (sra -1, x) -> -1 5627 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5628 return N0; 5629 5630 // fold vector ops 5631 if (VT.isVector()) 5632 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5633 return FoldedVOp; 5634 5635 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5636 5637 // fold (sra c1, c2) -> (sra c1, c2) 5638 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5639 if (N0C && N1C && !N1C->isOpaque()) 5640 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5641 // fold (sra x, c >= size(x)) -> undef 5642 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5643 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5644 return Val->getAPIntValue().uge(OpSizeInBits); 5645 }; 5646 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5647 return DAG.getUNDEF(VT); 5648 // fold (sra x, 0) -> x 5649 if (N1C && N1C->isNullValue()) 5650 return N0; 5651 5652 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5653 return NewSel; 5654 5655 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5656 // sext_inreg. 5657 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5658 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5659 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5660 if (VT.isVector()) 5661 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5662 ExtVT, VT.getVectorNumElements()); 5663 if ((!LegalOperations || 5664 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5665 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5666 N0.getOperand(0), DAG.getValueType(ExtVT)); 5667 } 5668 5669 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5670 if (N0.getOpcode() == ISD::SRA) { 5671 SDLoc DL(N); 5672 EVT ShiftVT = N1.getValueType(); 5673 5674 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5675 ConstantSDNode *RHS) { 5676 APInt c1 = LHS->getAPIntValue(); 5677 APInt c2 = RHS->getAPIntValue(); 5678 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5679 return (c1 + c2).uge(OpSizeInBits); 5680 }; 5681 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5682 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 5683 DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT)); 5684 5685 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5686 ConstantSDNode *RHS) { 5687 APInt c1 = LHS->getAPIntValue(); 5688 APInt c2 = RHS->getAPIntValue(); 5689 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5690 return (c1 + c2).ult(OpSizeInBits); 5691 }; 5692 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5693 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5694 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum); 5695 } 5696 } 5697 5698 // fold (sra (shl X, m), (sub result_size, n)) 5699 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5700 // result_size - n != m. 5701 // If truncate is free for the target sext(shl) is likely to result in better 5702 // code. 5703 if (N0.getOpcode() == ISD::SHL && N1C) { 5704 // Get the two constanst of the shifts, CN0 = m, CN = n. 5705 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5706 if (N01C) { 5707 LLVMContext &Ctx = *DAG.getContext(); 5708 // Determine what the truncate's result bitsize and type would be. 5709 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5710 5711 if (VT.isVector()) 5712 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5713 5714 // Determine the residual right-shift amount. 5715 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5716 5717 // If the shift is not a no-op (in which case this should be just a sign 5718 // extend already), the truncated to type is legal, sign_extend is legal 5719 // on that type, and the truncate to that type is both legal and free, 5720 // perform the transform. 5721 if ((ShiftAmt > 0) && 5722 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5723 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5724 TLI.isTruncateFree(VT, TruncVT)) { 5725 SDLoc DL(N); 5726 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5727 getShiftAmountTy(N0.getOperand(0).getValueType())); 5728 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5729 N0.getOperand(0), Amt); 5730 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5731 Shift); 5732 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5733 N->getValueType(0), Trunc); 5734 } 5735 } 5736 } 5737 5738 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5739 if (N1.getOpcode() == ISD::TRUNCATE && 5740 N1.getOperand(0).getOpcode() == ISD::AND) { 5741 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5742 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5743 } 5744 5745 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5746 // if c1 is equal to the number of bits the trunc removes 5747 if (N0.getOpcode() == ISD::TRUNCATE && 5748 (N0.getOperand(0).getOpcode() == ISD::SRL || 5749 N0.getOperand(0).getOpcode() == ISD::SRA) && 5750 N0.getOperand(0).hasOneUse() && 5751 N0.getOperand(0).getOperand(1).hasOneUse() && 5752 N1C) { 5753 SDValue N0Op0 = N0.getOperand(0); 5754 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5755 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5756 EVT LargeVT = N0Op0.getValueType(); 5757 5758 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5759 SDLoc DL(N); 5760 SDValue Amt = 5761 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5762 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5763 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5764 N0Op0.getOperand(0), Amt); 5765 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5766 } 5767 } 5768 } 5769 5770 // Simplify, based on bits shifted out of the LHS. 5771 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5772 return SDValue(N, 0); 5773 5774 // If the sign bit is known to be zero, switch this to a SRL. 5775 if (DAG.SignBitIsZero(N0)) 5776 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5777 5778 if (N1C && !N1C->isOpaque()) 5779 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5780 return NewSRA; 5781 5782 return SDValue(); 5783 } 5784 5785 SDValue DAGCombiner::visitSRL(SDNode *N) { 5786 SDValue N0 = N->getOperand(0); 5787 SDValue N1 = N->getOperand(1); 5788 EVT VT = N0.getValueType(); 5789 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5790 5791 // fold vector ops 5792 if (VT.isVector()) 5793 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5794 return FoldedVOp; 5795 5796 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5797 5798 // fold (srl c1, c2) -> c1 >>u c2 5799 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5800 if (N0C && N1C && !N1C->isOpaque()) 5801 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5802 // fold (srl 0, x) -> 0 5803 if (isNullConstantOrNullSplatConstant(N0)) 5804 return N0; 5805 // fold (srl x, c >= size(x)) -> undef 5806 // NOTE: ALL vector elements must be too big to avoid partial UNDEFs. 5807 auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) { 5808 return Val->getAPIntValue().uge(OpSizeInBits); 5809 }; 5810 if (matchUnaryPredicate(N1, MatchShiftTooBig)) 5811 return DAG.getUNDEF(VT); 5812 // fold (srl x, 0) -> x 5813 if (N1C && N1C->isNullValue()) 5814 return N0; 5815 5816 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5817 return NewSel; 5818 5819 // if (srl x, c) is known to be zero, return 0 5820 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5821 APInt::getAllOnesValue(OpSizeInBits))) 5822 return DAG.getConstant(0, SDLoc(N), VT); 5823 5824 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5825 if (N0.getOpcode() == ISD::SRL) { 5826 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 5827 ConstantSDNode *RHS) { 5828 APInt c1 = LHS->getAPIntValue(); 5829 APInt c2 = RHS->getAPIntValue(); 5830 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5831 return (c1 + c2).uge(OpSizeInBits); 5832 }; 5833 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 5834 return DAG.getConstant(0, SDLoc(N), VT); 5835 5836 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 5837 ConstantSDNode *RHS) { 5838 APInt c1 = LHS->getAPIntValue(); 5839 APInt c2 = RHS->getAPIntValue(); 5840 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5841 return (c1 + c2).ult(OpSizeInBits); 5842 }; 5843 if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 5844 SDLoc DL(N); 5845 EVT ShiftVT = N1.getValueType(); 5846 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 5847 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 5848 } 5849 } 5850 5851 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5852 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5853 N0.getOperand(0).getOpcode() == ISD::SRL) { 5854 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 5855 uint64_t c1 = N001C->getZExtValue(); 5856 uint64_t c2 = N1C->getZExtValue(); 5857 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5858 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 5859 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5860 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5861 if (c1 + OpSizeInBits == InnerShiftSize) { 5862 SDLoc DL(N0); 5863 if (c1 + c2 >= InnerShiftSize) 5864 return DAG.getConstant(0, DL, VT); 5865 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5866 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5867 N0.getOperand(0).getOperand(0), 5868 DAG.getConstant(c1 + c2, DL, 5869 ShiftCountVT))); 5870 } 5871 } 5872 } 5873 5874 // fold (srl (shl x, c), c) -> (and x, cst2) 5875 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5876 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5877 SDLoc DL(N); 5878 SDValue Mask = 5879 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5880 AddToWorklist(Mask.getNode()); 5881 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5882 } 5883 5884 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5885 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5886 // Shifting in all undef bits? 5887 EVT SmallVT = N0.getOperand(0).getValueType(); 5888 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5889 if (N1C->getZExtValue() >= BitSize) 5890 return DAG.getUNDEF(VT); 5891 5892 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5893 uint64_t ShiftAmt = N1C->getZExtValue(); 5894 SDLoc DL0(N0); 5895 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5896 N0.getOperand(0), 5897 DAG.getConstant(ShiftAmt, DL0, 5898 getShiftAmountTy(SmallVT))); 5899 AddToWorklist(SmallShift.getNode()); 5900 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 5901 SDLoc DL(N); 5902 return DAG.getNode(ISD::AND, DL, VT, 5903 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5904 DAG.getConstant(Mask, DL, VT)); 5905 } 5906 } 5907 5908 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5909 // bit, which is unmodified by sra. 5910 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5911 if (N0.getOpcode() == ISD::SRA) 5912 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5913 } 5914 5915 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5916 if (N1C && N0.getOpcode() == ISD::CTLZ && 5917 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5918 KnownBits Known; 5919 DAG.computeKnownBits(N0.getOperand(0), Known); 5920 5921 // If any of the input bits are KnownOne, then the input couldn't be all 5922 // zeros, thus the result of the srl will always be zero. 5923 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5924 5925 // If all of the bits input the to ctlz node are known to be zero, then 5926 // the result of the ctlz is "32" and the result of the shift is one. 5927 APInt UnknownBits = ~Known.Zero; 5928 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5929 5930 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5931 if (UnknownBits.isPowerOf2()) { 5932 // Okay, we know that only that the single bit specified by UnknownBits 5933 // could be set on input to the CTLZ node. If this bit is set, the SRL 5934 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5935 // to an SRL/XOR pair, which is likely to simplify more. 5936 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5937 SDValue Op = N0.getOperand(0); 5938 5939 if (ShAmt) { 5940 SDLoc DL(N0); 5941 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5942 DAG.getConstant(ShAmt, DL, 5943 getShiftAmountTy(Op.getValueType()))); 5944 AddToWorklist(Op.getNode()); 5945 } 5946 5947 SDLoc DL(N); 5948 return DAG.getNode(ISD::XOR, DL, VT, 5949 Op, DAG.getConstant(1, DL, VT)); 5950 } 5951 } 5952 5953 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5954 if (N1.getOpcode() == ISD::TRUNCATE && 5955 N1.getOperand(0).getOpcode() == ISD::AND) { 5956 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5957 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5958 } 5959 5960 // fold operands of srl based on knowledge that the low bits are not 5961 // demanded. 5962 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5963 return SDValue(N, 0); 5964 5965 if (N1C && !N1C->isOpaque()) 5966 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5967 return NewSRL; 5968 5969 // Attempt to convert a srl of a load into a narrower zero-extending load. 5970 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5971 return NarrowLoad; 5972 5973 // Here is a common situation. We want to optimize: 5974 // 5975 // %a = ... 5976 // %b = and i32 %a, 2 5977 // %c = srl i32 %b, 1 5978 // brcond i32 %c ... 5979 // 5980 // into 5981 // 5982 // %a = ... 5983 // %b = and %a, 2 5984 // %c = setcc eq %b, 0 5985 // brcond %c ... 5986 // 5987 // However when after the source operand of SRL is optimized into AND, the SRL 5988 // itself may not be optimized further. Look for it and add the BRCOND into 5989 // the worklist. 5990 if (N->hasOneUse()) { 5991 SDNode *Use = *N->use_begin(); 5992 if (Use->getOpcode() == ISD::BRCOND) 5993 AddToWorklist(Use); 5994 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5995 // Also look pass the truncate. 5996 Use = *Use->use_begin(); 5997 if (Use->getOpcode() == ISD::BRCOND) 5998 AddToWorklist(Use); 5999 } 6000 } 6001 6002 return SDValue(); 6003 } 6004 6005 SDValue DAGCombiner::visitABS(SDNode *N) { 6006 SDValue N0 = N->getOperand(0); 6007 EVT VT = N->getValueType(0); 6008 6009 // fold (abs c1) -> c2 6010 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6011 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 6012 // fold (abs (abs x)) -> (abs x) 6013 if (N0.getOpcode() == ISD::ABS) 6014 return N0; 6015 // fold (abs x) -> x iff not-negative 6016 if (DAG.SignBitIsZero(N0)) 6017 return N0; 6018 return SDValue(); 6019 } 6020 6021 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 6022 SDValue N0 = N->getOperand(0); 6023 EVT VT = N->getValueType(0); 6024 6025 // fold (bswap c1) -> c2 6026 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6027 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 6028 // fold (bswap (bswap x)) -> x 6029 if (N0.getOpcode() == ISD::BSWAP) 6030 return N0->getOperand(0); 6031 return SDValue(); 6032 } 6033 6034 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 6035 SDValue N0 = N->getOperand(0); 6036 EVT VT = N->getValueType(0); 6037 6038 // fold (bitreverse c1) -> c2 6039 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6040 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6041 // fold (bitreverse (bitreverse x)) -> x 6042 if (N0.getOpcode() == ISD::BITREVERSE) 6043 return N0.getOperand(0); 6044 return SDValue(); 6045 } 6046 6047 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6048 SDValue N0 = N->getOperand(0); 6049 EVT VT = N->getValueType(0); 6050 6051 // fold (ctlz c1) -> c2 6052 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6053 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6054 return SDValue(); 6055 } 6056 6057 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6058 SDValue N0 = N->getOperand(0); 6059 EVT VT = N->getValueType(0); 6060 6061 // fold (ctlz_zero_undef c1) -> c2 6062 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6063 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6064 return SDValue(); 6065 } 6066 6067 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6068 SDValue N0 = N->getOperand(0); 6069 EVT VT = N->getValueType(0); 6070 6071 // fold (cttz c1) -> c2 6072 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6073 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6074 return SDValue(); 6075 } 6076 6077 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6078 SDValue N0 = N->getOperand(0); 6079 EVT VT = N->getValueType(0); 6080 6081 // fold (cttz_zero_undef c1) -> c2 6082 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6083 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6084 return SDValue(); 6085 } 6086 6087 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6088 SDValue N0 = N->getOperand(0); 6089 EVT VT = N->getValueType(0); 6090 6091 // fold (ctpop c1) -> c2 6092 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6093 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6094 return SDValue(); 6095 } 6096 6097 /// \brief Generate Min/Max node 6098 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6099 SDValue RHS, SDValue True, SDValue False, 6100 ISD::CondCode CC, const TargetLowering &TLI, 6101 SelectionDAG &DAG) { 6102 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6103 return SDValue(); 6104 6105 switch (CC) { 6106 case ISD::SETOLT: 6107 case ISD::SETOLE: 6108 case ISD::SETLT: 6109 case ISD::SETLE: 6110 case ISD::SETULT: 6111 case ISD::SETULE: { 6112 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6113 if (TLI.isOperationLegal(Opcode, VT)) 6114 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6115 return SDValue(); 6116 } 6117 case ISD::SETOGT: 6118 case ISD::SETOGE: 6119 case ISD::SETGT: 6120 case ISD::SETGE: 6121 case ISD::SETUGT: 6122 case ISD::SETUGE: { 6123 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6124 if (TLI.isOperationLegal(Opcode, VT)) 6125 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6126 return SDValue(); 6127 } 6128 default: 6129 return SDValue(); 6130 } 6131 } 6132 6133 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6134 SDValue Cond = N->getOperand(0); 6135 SDValue N1 = N->getOperand(1); 6136 SDValue N2 = N->getOperand(2); 6137 EVT VT = N->getValueType(0); 6138 EVT CondVT = Cond.getValueType(); 6139 SDLoc DL(N); 6140 6141 if (!VT.isInteger()) 6142 return SDValue(); 6143 6144 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6145 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6146 if (!C1 || !C2) 6147 return SDValue(); 6148 6149 // Only do this before legalization to avoid conflicting with target-specific 6150 // transforms in the other direction (create a select from a zext/sext). There 6151 // is also a target-independent combine here in DAGCombiner in the other 6152 // direction for (select Cond, -1, 0) when the condition is not i1. 6153 if (CondVT == MVT::i1 && !LegalOperations) { 6154 if (C1->isNullValue() && C2->isOne()) { 6155 // select Cond, 0, 1 --> zext (!Cond) 6156 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6157 if (VT != MVT::i1) 6158 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6159 return NotCond; 6160 } 6161 if (C1->isNullValue() && C2->isAllOnesValue()) { 6162 // select Cond, 0, -1 --> sext (!Cond) 6163 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6164 if (VT != MVT::i1) 6165 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6166 return NotCond; 6167 } 6168 if (C1->isOne() && C2->isNullValue()) { 6169 // select Cond, 1, 0 --> zext (Cond) 6170 if (VT != MVT::i1) 6171 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6172 return Cond; 6173 } 6174 if (C1->isAllOnesValue() && C2->isNullValue()) { 6175 // select Cond, -1, 0 --> sext (Cond) 6176 if (VT != MVT::i1) 6177 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6178 return Cond; 6179 } 6180 6181 // For any constants that differ by 1, we can transform the select into an 6182 // extend and add. Use a target hook because some targets may prefer to 6183 // transform in the other direction. 6184 if (TLI.convertSelectOfConstantsToMath(VT)) { 6185 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6186 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6187 if (VT != MVT::i1) 6188 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6189 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6190 } 6191 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6192 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6193 if (VT != MVT::i1) 6194 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6195 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6196 } 6197 } 6198 6199 return SDValue(); 6200 } 6201 6202 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6203 // We can't do this reliably if integer based booleans have different contents 6204 // to floating point based booleans. This is because we can't tell whether we 6205 // have an integer-based boolean or a floating-point-based boolean unless we 6206 // can find the SETCC that produced it and inspect its operands. This is 6207 // fairly easy if C is the SETCC node, but it can potentially be 6208 // undiscoverable (or not reasonably discoverable). For example, it could be 6209 // in another basic block or it could require searching a complicated 6210 // expression. 6211 if (CondVT.isInteger() && 6212 TLI.getBooleanContents(false, true) == 6213 TargetLowering::ZeroOrOneBooleanContent && 6214 TLI.getBooleanContents(false, false) == 6215 TargetLowering::ZeroOrOneBooleanContent && 6216 C1->isNullValue() && C2->isOne()) { 6217 SDValue NotCond = 6218 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6219 if (VT.bitsEq(CondVT)) 6220 return NotCond; 6221 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6222 } 6223 6224 return SDValue(); 6225 } 6226 6227 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6228 SDValue N0 = N->getOperand(0); 6229 SDValue N1 = N->getOperand(1); 6230 SDValue N2 = N->getOperand(2); 6231 EVT VT = N->getValueType(0); 6232 EVT VT0 = N0.getValueType(); 6233 SDLoc DL(N); 6234 6235 // fold (select C, X, X) -> X 6236 if (N1 == N2) 6237 return N1; 6238 6239 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6240 // fold (select true, X, Y) -> X 6241 // fold (select false, X, Y) -> Y 6242 return !N0C->isNullValue() ? N1 : N2; 6243 } 6244 6245 // fold (select X, X, Y) -> (or X, Y) 6246 // fold (select X, 1, Y) -> (or C, Y) 6247 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6248 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 6249 6250 if (SDValue V = foldSelectOfConstants(N)) 6251 return V; 6252 6253 // fold (select C, 0, X) -> (and (not C), X) 6254 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6255 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6256 AddToWorklist(NOTNode.getNode()); 6257 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 6258 } 6259 // fold (select C, X, 1) -> (or (not C), X) 6260 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6261 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6262 AddToWorklist(NOTNode.getNode()); 6263 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 6264 } 6265 // fold (select X, Y, X) -> (and X, Y) 6266 // fold (select X, Y, 0) -> (and X, Y) 6267 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6268 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 6269 6270 // If we can fold this based on the true/false value, do so. 6271 if (SimplifySelectOps(N, N1, N2)) 6272 return SDValue(N, 0); // Don't revisit N. 6273 6274 if (VT0 == MVT::i1) { 6275 // The code in this block deals with the following 2 equivalences: 6276 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6277 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6278 // The target can specify its preferred form with the 6279 // shouldNormalizeToSelectSequence() callback. However we always transform 6280 // to the right anyway if we find the inner select exists in the DAG anyway 6281 // and we always transform to the left side if we know that we can further 6282 // optimize the combination of the conditions. 6283 bool normalizeToSequence = 6284 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6285 // select (and Cond0, Cond1), X, Y 6286 // -> select Cond0, (select Cond1, X, Y), Y 6287 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6288 SDValue Cond0 = N0->getOperand(0); 6289 SDValue Cond1 = N0->getOperand(1); 6290 SDValue InnerSelect = 6291 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6292 if (normalizeToSequence || !InnerSelect.use_empty()) 6293 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 6294 InnerSelect, N2); 6295 } 6296 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6297 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6298 SDValue Cond0 = N0->getOperand(0); 6299 SDValue Cond1 = N0->getOperand(1); 6300 SDValue InnerSelect = 6301 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 6302 if (normalizeToSequence || !InnerSelect.use_empty()) 6303 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 6304 InnerSelect); 6305 } 6306 6307 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6308 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6309 SDValue N1_0 = N1->getOperand(0); 6310 SDValue N1_1 = N1->getOperand(1); 6311 SDValue N1_2 = N1->getOperand(2); 6312 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6313 // Create the actual and node if we can generate good code for it. 6314 if (!normalizeToSequence) { 6315 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 6316 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 6317 } 6318 // Otherwise see if we can optimize the "and" to a better pattern. 6319 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6320 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 6321 N2); 6322 } 6323 } 6324 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6325 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6326 SDValue N2_0 = N2->getOperand(0); 6327 SDValue N2_1 = N2->getOperand(1); 6328 SDValue N2_2 = N2->getOperand(2); 6329 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6330 // Create the actual or node if we can generate good code for it. 6331 if (!normalizeToSequence) { 6332 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 6333 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 6334 } 6335 // Otherwise see if we can optimize to a better pattern. 6336 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6337 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 6338 N2_2); 6339 } 6340 } 6341 } 6342 6343 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6344 if (VT0 == MVT::i1) { 6345 if (N0->getOpcode() == ISD::XOR) { 6346 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6347 SDValue Cond0 = N0->getOperand(0); 6348 if (C->isOne()) 6349 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1); 6350 } 6351 } 6352 } 6353 6354 // fold selects based on a setcc into other things, such as min/max/abs 6355 if (N0.getOpcode() == ISD::SETCC) { 6356 // select x, y (fcmp lt x, y) -> fminnum x, y 6357 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6358 // 6359 // This is OK if we don't care about what happens if either operand is a 6360 // NaN. 6361 // 6362 6363 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6364 // no signed zeros as well as no nans. 6365 const TargetOptions &Options = DAG.getTarget().Options; 6366 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() && 6367 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6368 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6369 6370 if (SDValue FMinMax = combineMinNumMaxNum( 6371 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 6372 return FMinMax; 6373 } 6374 6375 if ((!LegalOperations && 6376 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6377 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6378 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0), 6379 N0.getOperand(1), N1, N2, N0.getOperand(2)); 6380 return SimplifySelect(DL, N0, N1, N2); 6381 } 6382 6383 return SDValue(); 6384 } 6385 6386 static 6387 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6388 SDLoc DL(N); 6389 EVT LoVT, HiVT; 6390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6391 6392 // Split the inputs. 6393 SDValue Lo, Hi, LL, LH, RL, RH; 6394 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6395 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6396 6397 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6398 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6399 6400 return std::make_pair(Lo, Hi); 6401 } 6402 6403 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6404 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6405 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6406 SDLoc DL(N); 6407 SDValue Cond = N->getOperand(0); 6408 SDValue LHS = N->getOperand(1); 6409 SDValue RHS = N->getOperand(2); 6410 EVT VT = N->getValueType(0); 6411 int NumElems = VT.getVectorNumElements(); 6412 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6413 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6414 Cond.getOpcode() == ISD::BUILD_VECTOR); 6415 6416 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6417 // binary ones here. 6418 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6419 return SDValue(); 6420 6421 // We're sure we have an even number of elements due to the 6422 // concat_vectors we have as arguments to vselect. 6423 // Skip BV elements until we find one that's not an UNDEF 6424 // After we find an UNDEF element, keep looping until we get to half the 6425 // length of the BV and see if all the non-undef nodes are the same. 6426 ConstantSDNode *BottomHalf = nullptr; 6427 for (int i = 0; i < NumElems / 2; ++i) { 6428 if (Cond->getOperand(i)->isUndef()) 6429 continue; 6430 6431 if (BottomHalf == nullptr) 6432 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6433 else if (Cond->getOperand(i).getNode() != BottomHalf) 6434 return SDValue(); 6435 } 6436 6437 // Do the same for the second half of the BuildVector 6438 ConstantSDNode *TopHalf = nullptr; 6439 for (int i = NumElems / 2; i < NumElems; ++i) { 6440 if (Cond->getOperand(i)->isUndef()) 6441 continue; 6442 6443 if (TopHalf == nullptr) 6444 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6445 else if (Cond->getOperand(i).getNode() != TopHalf) 6446 return SDValue(); 6447 } 6448 6449 assert(TopHalf && BottomHalf && 6450 "One half of the selector was all UNDEFs and the other was all the " 6451 "same value. This should have been addressed before this function."); 6452 return DAG.getNode( 6453 ISD::CONCAT_VECTORS, DL, VT, 6454 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6455 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6456 } 6457 6458 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6459 if (Level >= AfterLegalizeTypes) 6460 return SDValue(); 6461 6462 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6463 SDValue Mask = MSC->getMask(); 6464 SDValue Data = MSC->getValue(); 6465 SDLoc DL(N); 6466 6467 // If the MSCATTER data type requires splitting and the mask is provided by a 6468 // SETCC, then split both nodes and its operands before legalization. This 6469 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6470 // and enables future optimizations (e.g. min/max pattern matching on X86). 6471 if (Mask.getOpcode() != ISD::SETCC) 6472 return SDValue(); 6473 6474 // Check if any splitting is required. 6475 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6476 TargetLowering::TypeSplitVector) 6477 return SDValue(); 6478 SDValue MaskLo, MaskHi, Lo, Hi; 6479 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6480 6481 EVT LoVT, HiVT; 6482 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6483 6484 SDValue Chain = MSC->getChain(); 6485 6486 EVT MemoryVT = MSC->getMemoryVT(); 6487 unsigned Alignment = MSC->getOriginalAlignment(); 6488 6489 EVT LoMemVT, HiMemVT; 6490 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6491 6492 SDValue DataLo, DataHi; 6493 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6494 6495 SDValue BasePtr = MSC->getBasePtr(); 6496 SDValue IndexLo, IndexHi; 6497 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6498 6499 MachineMemOperand *MMO = DAG.getMachineFunction(). 6500 getMachineMemOperand(MSC->getPointerInfo(), 6501 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6502 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6503 6504 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6505 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6506 DL, OpsLo, MMO); 6507 6508 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6509 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6510 DL, OpsHi, MMO); 6511 6512 AddToWorklist(Lo.getNode()); 6513 AddToWorklist(Hi.getNode()); 6514 6515 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6516 } 6517 6518 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6519 if (Level >= AfterLegalizeTypes) 6520 return SDValue(); 6521 6522 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6523 SDValue Mask = MST->getMask(); 6524 SDValue Data = MST->getValue(); 6525 EVT VT = Data.getValueType(); 6526 SDLoc DL(N); 6527 6528 // If the MSTORE data type requires splitting and the mask is provided by a 6529 // SETCC, then split both nodes and its operands before legalization. This 6530 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6531 // and enables future optimizations (e.g. min/max pattern matching on X86). 6532 if (Mask.getOpcode() == ISD::SETCC) { 6533 // Check if any splitting is required. 6534 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6535 TargetLowering::TypeSplitVector) 6536 return SDValue(); 6537 6538 SDValue MaskLo, MaskHi, Lo, Hi; 6539 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6540 6541 SDValue Chain = MST->getChain(); 6542 SDValue Ptr = MST->getBasePtr(); 6543 6544 EVT MemoryVT = MST->getMemoryVT(); 6545 unsigned Alignment = MST->getOriginalAlignment(); 6546 6547 // if Alignment is equal to the vector size, 6548 // take the half of it for the second part 6549 unsigned SecondHalfAlignment = 6550 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6551 6552 EVT LoMemVT, HiMemVT; 6553 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6554 6555 SDValue DataLo, DataHi; 6556 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6557 6558 MachineMemOperand *MMO = DAG.getMachineFunction(). 6559 getMachineMemOperand(MST->getPointerInfo(), 6560 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6561 Alignment, MST->getAAInfo(), MST->getRanges()); 6562 6563 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6564 MST->isTruncatingStore(), 6565 MST->isCompressingStore()); 6566 6567 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6568 MST->isCompressingStore()); 6569 6570 MMO = DAG.getMachineFunction(). 6571 getMachineMemOperand(MST->getPointerInfo(), 6572 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6573 SecondHalfAlignment, MST->getAAInfo(), 6574 MST->getRanges()); 6575 6576 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6577 MST->isTruncatingStore(), 6578 MST->isCompressingStore()); 6579 6580 AddToWorklist(Lo.getNode()); 6581 AddToWorklist(Hi.getNode()); 6582 6583 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6584 } 6585 return SDValue(); 6586 } 6587 6588 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6589 if (Level >= AfterLegalizeTypes) 6590 return SDValue(); 6591 6592 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 6593 SDValue Mask = MGT->getMask(); 6594 SDLoc DL(N); 6595 6596 // If the MGATHER result requires splitting and the mask is provided by a 6597 // SETCC, then split both nodes and its operands before legalization. This 6598 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6599 // and enables future optimizations (e.g. min/max pattern matching on X86). 6600 6601 if (Mask.getOpcode() != ISD::SETCC) 6602 return SDValue(); 6603 6604 EVT VT = N->getValueType(0); 6605 6606 // Check if any splitting is required. 6607 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6608 TargetLowering::TypeSplitVector) 6609 return SDValue(); 6610 6611 SDValue MaskLo, MaskHi, Lo, Hi; 6612 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6613 6614 SDValue Src0 = MGT->getValue(); 6615 SDValue Src0Lo, Src0Hi; 6616 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6617 6618 EVT LoVT, HiVT; 6619 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6620 6621 SDValue Chain = MGT->getChain(); 6622 EVT MemoryVT = MGT->getMemoryVT(); 6623 unsigned Alignment = MGT->getOriginalAlignment(); 6624 6625 EVT LoMemVT, HiMemVT; 6626 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6627 6628 SDValue BasePtr = MGT->getBasePtr(); 6629 SDValue Index = MGT->getIndex(); 6630 SDValue IndexLo, IndexHi; 6631 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6632 6633 MachineMemOperand *MMO = DAG.getMachineFunction(). 6634 getMachineMemOperand(MGT->getPointerInfo(), 6635 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6636 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6637 6638 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6639 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6640 MMO); 6641 6642 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6643 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6644 MMO); 6645 6646 AddToWorklist(Lo.getNode()); 6647 AddToWorklist(Hi.getNode()); 6648 6649 // Build a factor node to remember that this load is independent of the 6650 // other one. 6651 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6652 Hi.getValue(1)); 6653 6654 // Legalized the chain result - switch anything that used the old chain to 6655 // use the new one. 6656 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6657 6658 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6659 6660 SDValue RetOps[] = { GatherRes, Chain }; 6661 return DAG.getMergeValues(RetOps, DL); 6662 } 6663 6664 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6665 if (Level >= AfterLegalizeTypes) 6666 return SDValue(); 6667 6668 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6669 SDValue Mask = MLD->getMask(); 6670 SDLoc DL(N); 6671 6672 // If the MLOAD result requires splitting and the mask is provided by a 6673 // SETCC, then split both nodes and its operands before legalization. This 6674 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6675 // and enables future optimizations (e.g. min/max pattern matching on X86). 6676 if (Mask.getOpcode() == ISD::SETCC) { 6677 EVT VT = N->getValueType(0); 6678 6679 // Check if any splitting is required. 6680 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6681 TargetLowering::TypeSplitVector) 6682 return SDValue(); 6683 6684 SDValue MaskLo, MaskHi, Lo, Hi; 6685 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6686 6687 SDValue Src0 = MLD->getSrc0(); 6688 SDValue Src0Lo, Src0Hi; 6689 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6690 6691 EVT LoVT, HiVT; 6692 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6693 6694 SDValue Chain = MLD->getChain(); 6695 SDValue Ptr = MLD->getBasePtr(); 6696 EVT MemoryVT = MLD->getMemoryVT(); 6697 unsigned Alignment = MLD->getOriginalAlignment(); 6698 6699 // if Alignment is equal to the vector size, 6700 // take the half of it for the second part 6701 unsigned SecondHalfAlignment = 6702 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6703 Alignment/2 : Alignment; 6704 6705 EVT LoMemVT, HiMemVT; 6706 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6707 6708 MachineMemOperand *MMO = DAG.getMachineFunction(). 6709 getMachineMemOperand(MLD->getPointerInfo(), 6710 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6711 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6712 6713 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6714 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6715 6716 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6717 MLD->isExpandingLoad()); 6718 6719 MMO = DAG.getMachineFunction(). 6720 getMachineMemOperand(MLD->getPointerInfo(), 6721 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6722 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6723 6724 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6725 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6726 6727 AddToWorklist(Lo.getNode()); 6728 AddToWorklist(Hi.getNode()); 6729 6730 // Build a factor node to remember that this load is independent of the 6731 // other one. 6732 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6733 Hi.getValue(1)); 6734 6735 // Legalized the chain result - switch anything that used the old chain to 6736 // use the new one. 6737 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6738 6739 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6740 6741 SDValue RetOps[] = { LoadRes, Chain }; 6742 return DAG.getMergeValues(RetOps, DL); 6743 } 6744 return SDValue(); 6745 } 6746 6747 /// A vector select of 2 constant vectors can be simplified to math/logic to 6748 /// avoid a variable select instruction and possibly avoid constant loads. 6749 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 6750 SDValue Cond = N->getOperand(0); 6751 SDValue N1 = N->getOperand(1); 6752 SDValue N2 = N->getOperand(2); 6753 EVT VT = N->getValueType(0); 6754 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 6755 !TLI.convertSelectOfConstantsToMath(VT) || 6756 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 6757 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 6758 return SDValue(); 6759 6760 // Check if we can use the condition value to increment/decrement a single 6761 // constant value. This simplifies a select to an add and removes a constant 6762 // load/materialization from the general case. 6763 bool AllAddOne = true; 6764 bool AllSubOne = true; 6765 unsigned Elts = VT.getVectorNumElements(); 6766 for (unsigned i = 0; i != Elts; ++i) { 6767 SDValue N1Elt = N1.getOperand(i); 6768 SDValue N2Elt = N2.getOperand(i); 6769 if (N1Elt.isUndef() || N2Elt.isUndef()) 6770 continue; 6771 6772 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 6773 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 6774 if (C1 != C2 + 1) 6775 AllAddOne = false; 6776 if (C1 != C2 - 1) 6777 AllSubOne = false; 6778 } 6779 6780 // Further simplifications for the extra-special cases where the constants are 6781 // all 0 or all -1 should be implemented as folds of these patterns. 6782 SDLoc DL(N); 6783 if (AllAddOne || AllSubOne) { 6784 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 6785 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 6786 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 6787 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 6788 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 6789 } 6790 6791 // The general case for select-of-constants: 6792 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 6793 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 6794 // leave that to a machine-specific pass. 6795 return SDValue(); 6796 } 6797 6798 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6799 SDValue N0 = N->getOperand(0); 6800 SDValue N1 = N->getOperand(1); 6801 SDValue N2 = N->getOperand(2); 6802 SDLoc DL(N); 6803 6804 // fold (vselect C, X, X) -> X 6805 if (N1 == N2) 6806 return N1; 6807 6808 // Canonicalize integer abs. 6809 // vselect (setg[te] X, 0), X, -X -> 6810 // vselect (setgt X, -1), X, -X -> 6811 // vselect (setl[te] X, 0), -X, X -> 6812 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6813 if (N0.getOpcode() == ISD::SETCC) { 6814 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6815 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6816 bool isAbs = false; 6817 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6818 6819 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6820 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6821 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6822 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6823 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6824 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6825 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6826 6827 if (isAbs) { 6828 EVT VT = LHS.getValueType(); 6829 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 6830 return DAG.getNode(ISD::ABS, DL, VT, LHS); 6831 6832 SDValue Shift = DAG.getNode( 6833 ISD::SRA, DL, VT, LHS, 6834 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6835 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6836 AddToWorklist(Shift.getNode()); 6837 AddToWorklist(Add.getNode()); 6838 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6839 } 6840 } 6841 6842 if (SimplifySelectOps(N, N1, N2)) 6843 return SDValue(N, 0); // Don't revisit N. 6844 6845 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6846 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6847 return N1; 6848 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6849 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6850 return N2; 6851 6852 // The ConvertSelectToConcatVector function is assuming both the above 6853 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6854 // and addressed. 6855 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6856 N2.getOpcode() == ISD::CONCAT_VECTORS && 6857 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6858 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6859 return CV; 6860 } 6861 6862 if (SDValue V = foldVSelectOfConstants(N)) 6863 return V; 6864 6865 return SDValue(); 6866 } 6867 6868 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6869 SDValue N0 = N->getOperand(0); 6870 SDValue N1 = N->getOperand(1); 6871 SDValue N2 = N->getOperand(2); 6872 SDValue N3 = N->getOperand(3); 6873 SDValue N4 = N->getOperand(4); 6874 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6875 6876 // fold select_cc lhs, rhs, x, x, cc -> x 6877 if (N2 == N3) 6878 return N2; 6879 6880 // Determine if the condition we're dealing with is constant 6881 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6882 CC, SDLoc(N), false)) { 6883 AddToWorklist(SCC.getNode()); 6884 6885 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6886 if (!SCCC->isNullValue()) 6887 return N2; // cond always true -> true val 6888 else 6889 return N3; // cond always false -> false val 6890 } else if (SCC->isUndef()) { 6891 // When the condition is UNDEF, just return the first operand. This is 6892 // coherent the DAG creation, no setcc node is created in this case 6893 return N2; 6894 } else if (SCC.getOpcode() == ISD::SETCC) { 6895 // Fold to a simpler select_cc 6896 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6897 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6898 SCC.getOperand(2)); 6899 } 6900 } 6901 6902 // If we can fold this based on the true/false value, do so. 6903 if (SimplifySelectOps(N, N2, N3)) 6904 return SDValue(N, 0); // Don't revisit N. 6905 6906 // fold select_cc into other things, such as min/max/abs 6907 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6908 } 6909 6910 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6911 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6912 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6913 SDLoc(N)); 6914 } 6915 6916 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6917 SDValue LHS = N->getOperand(0); 6918 SDValue RHS = N->getOperand(1); 6919 SDValue Carry = N->getOperand(2); 6920 SDValue Cond = N->getOperand(3); 6921 6922 // If Carry is false, fold to a regular SETCC. 6923 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6924 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6925 6926 return SDValue(); 6927 } 6928 6929 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 6930 SDValue LHS = N->getOperand(0); 6931 SDValue RHS = N->getOperand(1); 6932 SDValue Carry = N->getOperand(2); 6933 SDValue Cond = N->getOperand(3); 6934 6935 // If Carry is false, fold to a regular SETCC. 6936 if (isNullConstant(Carry)) 6937 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6938 6939 return SDValue(); 6940 } 6941 6942 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6943 /// a build_vector of constants. 6944 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6945 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6946 /// Vector extends are not folded if operations are legal; this is to 6947 /// avoid introducing illegal build_vector dag nodes. 6948 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6949 SelectionDAG &DAG, bool LegalTypes, 6950 bool LegalOperations) { 6951 unsigned Opcode = N->getOpcode(); 6952 SDValue N0 = N->getOperand(0); 6953 EVT VT = N->getValueType(0); 6954 6955 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6956 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6957 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6958 && "Expected EXTEND dag node in input!"); 6959 6960 // fold (sext c1) -> c1 6961 // fold (zext c1) -> c1 6962 // fold (aext c1) -> c1 6963 if (isa<ConstantSDNode>(N0)) 6964 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6965 6966 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6967 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6968 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6969 EVT SVT = VT.getScalarType(); 6970 if (!(VT.isVector() && 6971 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6972 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6973 return nullptr; 6974 6975 // We can fold this node into a build_vector. 6976 unsigned VTBits = SVT.getSizeInBits(); 6977 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6978 SmallVector<SDValue, 8> Elts; 6979 unsigned NumElts = VT.getVectorNumElements(); 6980 SDLoc DL(N); 6981 6982 for (unsigned i=0; i != NumElts; ++i) { 6983 SDValue Op = N0->getOperand(i); 6984 if (Op->isUndef()) { 6985 Elts.push_back(DAG.getUNDEF(SVT)); 6986 continue; 6987 } 6988 6989 SDLoc DL(Op); 6990 // Get the constant value and if needed trunc it to the size of the type. 6991 // Nodes like build_vector might have constants wider than the scalar type. 6992 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6993 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6994 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6995 else 6996 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6997 } 6998 6999 return DAG.getBuildVector(VT, DL, Elts).getNode(); 7000 } 7001 7002 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 7003 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 7004 // transformation. Returns true if extension are possible and the above 7005 // mentioned transformation is profitable. 7006 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 7007 unsigned ExtOpc, 7008 SmallVectorImpl<SDNode *> &ExtendNodes, 7009 const TargetLowering &TLI) { 7010 bool HasCopyToRegUses = false; 7011 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 7012 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 7013 UE = N0.getNode()->use_end(); 7014 UI != UE; ++UI) { 7015 SDNode *User = *UI; 7016 if (User == N) 7017 continue; 7018 if (UI.getUse().getResNo() != N0.getResNo()) 7019 continue; 7020 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 7021 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 7022 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 7023 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 7024 // Sign bits will be lost after a zext. 7025 return false; 7026 bool Add = false; 7027 for (unsigned i = 0; i != 2; ++i) { 7028 SDValue UseOp = User->getOperand(i); 7029 if (UseOp == N0) 7030 continue; 7031 if (!isa<ConstantSDNode>(UseOp)) 7032 return false; 7033 Add = true; 7034 } 7035 if (Add) 7036 ExtendNodes.push_back(User); 7037 continue; 7038 } 7039 // If truncates aren't free and there are users we can't 7040 // extend, it isn't worthwhile. 7041 if (!isTruncFree) 7042 return false; 7043 // Remember if this value is live-out. 7044 if (User->getOpcode() == ISD::CopyToReg) 7045 HasCopyToRegUses = true; 7046 } 7047 7048 if (HasCopyToRegUses) { 7049 bool BothLiveOut = false; 7050 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 7051 UI != UE; ++UI) { 7052 SDUse &Use = UI.getUse(); 7053 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 7054 BothLiveOut = true; 7055 break; 7056 } 7057 } 7058 if (BothLiveOut) 7059 // Both unextended and extended values are live out. There had better be 7060 // a good reason for the transformation. 7061 return ExtendNodes.size(); 7062 } 7063 return true; 7064 } 7065 7066 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 7067 SDValue Trunc, SDValue ExtLoad, 7068 const SDLoc &DL, ISD::NodeType ExtType) { 7069 // Extend SetCC uses if necessary. 7070 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 7071 SDNode *SetCC = SetCCs[i]; 7072 SmallVector<SDValue, 4> Ops; 7073 7074 for (unsigned j = 0; j != 2; ++j) { 7075 SDValue SOp = SetCC->getOperand(j); 7076 if (SOp == Trunc) 7077 Ops.push_back(ExtLoad); 7078 else 7079 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 7080 } 7081 7082 Ops.push_back(SetCC->getOperand(2)); 7083 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7084 } 7085 } 7086 7087 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7088 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7089 SDValue N0 = N->getOperand(0); 7090 EVT DstVT = N->getValueType(0); 7091 EVT SrcVT = N0.getValueType(); 7092 7093 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7094 N->getOpcode() == ISD::ZERO_EXTEND) && 7095 "Unexpected node type (not an extend)!"); 7096 7097 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7098 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7099 // (v8i32 (sext (v8i16 (load x)))) 7100 // into: 7101 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7102 // (v4i32 (sextload (x + 16))))) 7103 // Where uses of the original load, i.e.: 7104 // (v8i16 (load x)) 7105 // are replaced with: 7106 // (v8i16 (truncate 7107 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7108 // (v4i32 (sextload (x + 16))))))) 7109 // 7110 // This combine is only applicable to illegal, but splittable, vectors. 7111 // All legal types, and illegal non-vector types, are handled elsewhere. 7112 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7113 // 7114 if (N0->getOpcode() != ISD::LOAD) 7115 return SDValue(); 7116 7117 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7118 7119 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7120 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7121 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7122 return SDValue(); 7123 7124 SmallVector<SDNode *, 4> SetCCs; 7125 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 7126 return SDValue(); 7127 7128 ISD::LoadExtType ExtType = 7129 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7130 7131 // Try to split the vector types to get down to legal types. 7132 EVT SplitSrcVT = SrcVT; 7133 EVT SplitDstVT = DstVT; 7134 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7135 SplitSrcVT.getVectorNumElements() > 1) { 7136 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7137 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7138 } 7139 7140 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7141 return SDValue(); 7142 7143 SDLoc DL(N); 7144 const unsigned NumSplits = 7145 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7146 const unsigned Stride = SplitSrcVT.getStoreSize(); 7147 SmallVector<SDValue, 4> Loads; 7148 SmallVector<SDValue, 4> Chains; 7149 7150 SDValue BasePtr = LN0->getBasePtr(); 7151 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7152 const unsigned Offset = Idx * Stride; 7153 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7154 7155 SDValue SplitLoad = DAG.getExtLoad( 7156 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7157 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7158 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7159 7160 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7161 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7162 7163 Loads.push_back(SplitLoad.getValue(0)); 7164 Chains.push_back(SplitLoad.getValue(1)); 7165 } 7166 7167 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7168 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7169 7170 // Simplify TF. 7171 AddToWorklist(NewChain.getNode()); 7172 7173 CombineTo(N, NewValue); 7174 7175 // Replace uses of the original load (before extension) 7176 // with a truncate of the concatenated sextloaded vectors. 7177 SDValue Trunc = 7178 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7179 CombineTo(N0.getNode(), Trunc, NewChain); 7180 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7181 (ISD::NodeType)N->getOpcode()); 7182 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7183 } 7184 7185 /// If we're narrowing or widening the result of a vector select and the final 7186 /// size is the same size as a setcc (compare) feeding the select, then try to 7187 /// apply the cast operation to the select's operands because matching vector 7188 /// sizes for a select condition and other operands should be more efficient. 7189 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7190 unsigned CastOpcode = Cast->getOpcode(); 7191 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7192 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7193 CastOpcode == ISD::FP_ROUND) && 7194 "Unexpected opcode for vector select narrowing/widening"); 7195 7196 // We only do this transform before legal ops because the pattern may be 7197 // obfuscated by target-specific operations after legalization. Do not create 7198 // an illegal select op, however, because that may be difficult to lower. 7199 EVT VT = Cast->getValueType(0); 7200 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7201 return SDValue(); 7202 7203 SDValue VSel = Cast->getOperand(0); 7204 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7205 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7206 return SDValue(); 7207 7208 // Does the setcc have the same vector size as the casted select? 7209 SDValue SetCC = VSel.getOperand(0); 7210 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7211 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7212 return SDValue(); 7213 7214 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7215 SDValue A = VSel.getOperand(1); 7216 SDValue B = VSel.getOperand(2); 7217 SDValue CastA, CastB; 7218 SDLoc DL(Cast); 7219 if (CastOpcode == ISD::FP_ROUND) { 7220 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7221 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7222 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7223 } else { 7224 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7225 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7226 } 7227 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7228 } 7229 7230 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7231 SDValue N0 = N->getOperand(0); 7232 EVT VT = N->getValueType(0); 7233 SDLoc DL(N); 7234 7235 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7236 LegalOperations)) 7237 return SDValue(Res, 0); 7238 7239 // fold (sext (sext x)) -> (sext x) 7240 // fold (sext (aext x)) -> (sext x) 7241 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7242 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7243 7244 if (N0.getOpcode() == ISD::TRUNCATE) { 7245 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7246 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7247 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7248 SDNode *oye = N0.getOperand(0).getNode(); 7249 if (NarrowLoad.getNode() != N0.getNode()) { 7250 CombineTo(N0.getNode(), NarrowLoad); 7251 // CombineTo deleted the truncate, if needed, but not what's under it. 7252 AddToWorklist(oye); 7253 } 7254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7255 } 7256 7257 // See if the value being truncated is already sign extended. If so, just 7258 // eliminate the trunc/sext pair. 7259 SDValue Op = N0.getOperand(0); 7260 unsigned OpBits = Op.getScalarValueSizeInBits(); 7261 unsigned MidBits = N0.getScalarValueSizeInBits(); 7262 unsigned DestBits = VT.getScalarSizeInBits(); 7263 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7264 7265 if (OpBits == DestBits) { 7266 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7267 // bits, it is already ready. 7268 if (NumSignBits > DestBits-MidBits) 7269 return Op; 7270 } else if (OpBits < DestBits) { 7271 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7272 // bits, just sext from i32. 7273 if (NumSignBits > OpBits-MidBits) 7274 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7275 } else { 7276 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7277 // bits, just truncate to i32. 7278 if (NumSignBits > OpBits-MidBits) 7279 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7280 } 7281 7282 // fold (sext (truncate x)) -> (sextinreg x). 7283 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7284 N0.getValueType())) { 7285 if (OpBits < DestBits) 7286 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7287 else if (OpBits > DestBits) 7288 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7289 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7290 DAG.getValueType(N0.getValueType())); 7291 } 7292 } 7293 7294 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7295 // Only generate vector extloads when 1) they're legal, and 2) they are 7296 // deemed desirable by the target. 7297 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7298 ((!LegalOperations && !VT.isVector() && 7299 !cast<LoadSDNode>(N0)->isVolatile()) || 7300 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7301 bool DoXform = true; 7302 SmallVector<SDNode*, 4> SetCCs; 7303 if (!N0.hasOneUse()) 7304 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7305 if (VT.isVector()) 7306 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7307 if (DoXform) { 7308 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7309 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7310 LN0->getBasePtr(), N0.getValueType(), 7311 LN0->getMemOperand()); 7312 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7313 N0.getValueType(), ExtLoad); 7314 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7315 // If the load value is used only by N, replace it via CombineTo N. 7316 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7317 CombineTo(N, ExtLoad); 7318 if (NoReplaceTrunc) 7319 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7320 else 7321 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7322 return SDValue(N, 0); 7323 } 7324 } 7325 7326 // fold (sext (load x)) to multiple smaller sextloads. 7327 // Only on illegal but splittable vectors. 7328 if (SDValue ExtLoad = CombineExtLoad(N)) 7329 return ExtLoad; 7330 7331 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7332 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7333 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7334 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7335 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7336 EVT MemVT = LN0->getMemoryVT(); 7337 if ((!LegalOperations && !LN0->isVolatile()) || 7338 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7339 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7340 LN0->getBasePtr(), MemVT, 7341 LN0->getMemOperand()); 7342 CombineTo(N, ExtLoad); 7343 CombineTo(N0.getNode(), 7344 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7345 N0.getValueType(), ExtLoad), 7346 ExtLoad.getValue(1)); 7347 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7348 } 7349 } 7350 7351 // fold (sext (and/or/xor (load x), cst)) -> 7352 // (and/or/xor (sextload x), (sext cst)) 7353 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7354 N0.getOpcode() == ISD::XOR) && 7355 isa<LoadSDNode>(N0.getOperand(0)) && 7356 N0.getOperand(1).getOpcode() == ISD::Constant && 7357 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7358 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7359 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7360 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7361 bool DoXform = true; 7362 SmallVector<SDNode*, 4> SetCCs; 7363 if (!N0.hasOneUse()) 7364 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7365 SetCCs, TLI); 7366 if (DoXform) { 7367 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7368 LN0->getChain(), LN0->getBasePtr(), 7369 LN0->getMemoryVT(), 7370 LN0->getMemOperand()); 7371 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7372 Mask = Mask.sext(VT.getSizeInBits()); 7373 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7374 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7375 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7376 SDLoc(N0.getOperand(0)), 7377 N0.getOperand(0).getValueType(), ExtLoad); 7378 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7379 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7380 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7381 CombineTo(N, And); 7382 // If N0 has multiple uses, change other uses as well. 7383 if (NoReplaceTruncAnd) { 7384 SDValue TruncAnd = 7385 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7386 CombineTo(N0.getNode(), TruncAnd); 7387 } 7388 if (NoReplaceTrunc) 7389 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7390 else 7391 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7392 return SDValue(N,0); // Return N so it doesn't get rechecked! 7393 } 7394 } 7395 } 7396 7397 if (N0.getOpcode() == ISD::SETCC) { 7398 SDValue N00 = N0.getOperand(0); 7399 SDValue N01 = N0.getOperand(1); 7400 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7401 EVT N00VT = N0.getOperand(0).getValueType(); 7402 7403 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7404 // Only do this before legalize for now. 7405 if (VT.isVector() && !LegalOperations && 7406 TLI.getBooleanContents(N00VT) == 7407 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7408 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7409 // of the same size as the compared operands. Only optimize sext(setcc()) 7410 // if this is the case. 7411 EVT SVT = getSetCCResultType(N00VT); 7412 7413 // We know that the # elements of the results is the same as the 7414 // # elements of the compare (and the # elements of the compare result 7415 // for that matter). Check to see that they are the same size. If so, 7416 // we know that the element size of the sext'd result matches the 7417 // element size of the compare operands. 7418 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7419 return DAG.getSetCC(DL, VT, N00, N01, CC); 7420 7421 // If the desired elements are smaller or larger than the source 7422 // elements, we can use a matching integer vector type and then 7423 // truncate/sign extend. 7424 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7425 if (SVT == MatchingVecType) { 7426 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7427 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7428 } 7429 } 7430 7431 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7432 // Here, T can be 1 or -1, depending on the type of the setcc and 7433 // getBooleanContents(). 7434 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7435 7436 // To determine the "true" side of the select, we need to know the high bit 7437 // of the value returned by the setcc if it evaluates to true. 7438 // If the type of the setcc is i1, then the true case of the select is just 7439 // sext(i1 1), that is, -1. 7440 // If the type of the setcc is larger (say, i8) then the value of the high 7441 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7442 // of the appropriate width. 7443 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7444 : TLI.getConstTrueVal(DAG, VT, DL); 7445 SDValue Zero = DAG.getConstant(0, DL, VT); 7446 if (SDValue SCC = 7447 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7448 return SCC; 7449 7450 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 7451 EVT SetCCVT = getSetCCResultType(N00VT); 7452 // Don't do this transform for i1 because there's a select transform 7453 // that would reverse it. 7454 // TODO: We should not do this transform at all without a target hook 7455 // because a sext is likely cheaper than a select? 7456 if (SetCCVT.getScalarSizeInBits() != 1 && 7457 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7458 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7459 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7460 } 7461 } 7462 } 7463 7464 // fold (sext x) -> (zext x) if the sign bit is known zero. 7465 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7466 DAG.SignBitIsZero(N0)) 7467 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7468 7469 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7470 return NewVSel; 7471 7472 return SDValue(); 7473 } 7474 7475 // isTruncateOf - If N is a truncate of some other value, return true, record 7476 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7477 // This function computes KnownBits to avoid a duplicated call to 7478 // computeKnownBits in the caller. 7479 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7480 KnownBits &Known) { 7481 if (N->getOpcode() == ISD::TRUNCATE) { 7482 Op = N->getOperand(0); 7483 DAG.computeKnownBits(Op, Known); 7484 return true; 7485 } 7486 7487 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7488 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7489 return false; 7490 7491 SDValue Op0 = N->getOperand(0); 7492 SDValue Op1 = N->getOperand(1); 7493 assert(Op0.getValueType() == Op1.getValueType()); 7494 7495 if (isNullConstant(Op0)) 7496 Op = Op1; 7497 else if (isNullConstant(Op1)) 7498 Op = Op0; 7499 else 7500 return false; 7501 7502 DAG.computeKnownBits(Op, Known); 7503 7504 if (!(Known.Zero | 1).isAllOnesValue()) 7505 return false; 7506 7507 return true; 7508 } 7509 7510 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7511 SDValue N0 = N->getOperand(0); 7512 EVT VT = N->getValueType(0); 7513 7514 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7515 LegalOperations)) 7516 return SDValue(Res, 0); 7517 7518 // fold (zext (zext x)) -> (zext x) 7519 // fold (zext (aext x)) -> (zext x) 7520 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7521 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7522 N0.getOperand(0)); 7523 7524 // fold (zext (truncate x)) -> (zext x) or 7525 // (zext (truncate x)) -> (truncate x) 7526 // This is valid when the truncated bits of x are already zero. 7527 // FIXME: We should extend this to work for vectors too. 7528 SDValue Op; 7529 KnownBits Known; 7530 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7531 APInt TruncatedBits = 7532 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7533 APInt(Op.getValueSizeInBits(), 0) : 7534 APInt::getBitsSet(Op.getValueSizeInBits(), 7535 N0.getValueSizeInBits(), 7536 std::min(Op.getValueSizeInBits(), 7537 VT.getSizeInBits())); 7538 if (TruncatedBits.isSubsetOf(Known.Zero)) 7539 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7540 } 7541 7542 // fold (zext (truncate x)) -> (and x, mask) 7543 if (N0.getOpcode() == ISD::TRUNCATE) { 7544 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7545 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7546 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7547 SDNode *oye = N0.getOperand(0).getNode(); 7548 if (NarrowLoad.getNode() != N0.getNode()) { 7549 CombineTo(N0.getNode(), NarrowLoad); 7550 // CombineTo deleted the truncate, if needed, but not what's under it. 7551 AddToWorklist(oye); 7552 } 7553 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7554 } 7555 7556 EVT SrcVT = N0.getOperand(0).getValueType(); 7557 EVT MinVT = N0.getValueType(); 7558 7559 // Try to mask before the extension to avoid having to generate a larger mask, 7560 // possibly over several sub-vectors. 7561 if (SrcVT.bitsLT(VT)) { 7562 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7563 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7564 SDValue Op = N0.getOperand(0); 7565 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7566 AddToWorklist(Op.getNode()); 7567 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7568 } 7569 } 7570 7571 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7572 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7573 AddToWorklist(Op.getNode()); 7574 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7575 // We may safely transfer the debug info describing the truncate node over 7576 // to the equivalent and operation. 7577 DAG.transferDbgValues(N0, And); 7578 return And; 7579 } 7580 } 7581 7582 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7583 // if either of the casts is not free. 7584 if (N0.getOpcode() == ISD::AND && 7585 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7586 N0.getOperand(1).getOpcode() == ISD::Constant && 7587 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7588 N0.getValueType()) || 7589 !TLI.isZExtFree(N0.getValueType(), VT))) { 7590 SDValue X = N0.getOperand(0).getOperand(0); 7591 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7593 Mask = Mask.zext(VT.getSizeInBits()); 7594 SDLoc DL(N); 7595 return DAG.getNode(ISD::AND, DL, VT, 7596 X, DAG.getConstant(Mask, DL, VT)); 7597 } 7598 7599 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7600 // Only generate vector extloads when 1) they're legal, and 2) they are 7601 // deemed desirable by the target. 7602 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7603 ((!LegalOperations && !VT.isVector() && 7604 !cast<LoadSDNode>(N0)->isVolatile()) || 7605 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7606 bool DoXform = true; 7607 SmallVector<SDNode*, 4> SetCCs; 7608 if (!N0.hasOneUse()) 7609 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7610 if (VT.isVector()) 7611 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7612 if (DoXform) { 7613 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7614 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7615 LN0->getChain(), 7616 LN0->getBasePtr(), N0.getValueType(), 7617 LN0->getMemOperand()); 7618 7619 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7620 N0.getValueType(), ExtLoad); 7621 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7622 // If the load value is used only by N, replace it via CombineTo N. 7623 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7624 CombineTo(N, ExtLoad); 7625 if (NoReplaceTrunc) 7626 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7627 else 7628 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7629 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7630 } 7631 } 7632 7633 // fold (zext (load x)) to multiple smaller zextloads. 7634 // Only on illegal but splittable vectors. 7635 if (SDValue ExtLoad = CombineExtLoad(N)) 7636 return ExtLoad; 7637 7638 // fold (zext (and/or/xor (load x), cst)) -> 7639 // (and/or/xor (zextload x), (zext cst)) 7640 // Unless (and (load x) cst) will match as a zextload already and has 7641 // additional users. 7642 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7643 N0.getOpcode() == ISD::XOR) && 7644 isa<LoadSDNode>(N0.getOperand(0)) && 7645 N0.getOperand(1).getOpcode() == ISD::Constant && 7646 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7647 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7648 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7649 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7650 bool DoXform = true; 7651 SmallVector<SDNode*, 4> SetCCs; 7652 if (!N0.hasOneUse()) { 7653 if (N0.getOpcode() == ISD::AND) { 7654 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7655 auto NarrowLoad = false; 7656 EVT LoadResultTy = AndC->getValueType(0); 7657 EVT ExtVT, LoadedVT; 7658 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7659 NarrowLoad)) 7660 DoXform = false; 7661 } 7662 if (DoXform) 7663 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7664 ISD::ZERO_EXTEND, SetCCs, TLI); 7665 } 7666 if (DoXform) { 7667 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7668 LN0->getChain(), LN0->getBasePtr(), 7669 LN0->getMemoryVT(), 7670 LN0->getMemOperand()); 7671 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7672 Mask = Mask.zext(VT.getSizeInBits()); 7673 SDLoc DL(N); 7674 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7675 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7677 SDLoc(N0.getOperand(0)), 7678 N0.getOperand(0).getValueType(), ExtLoad); 7679 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND); 7680 bool NoReplaceTruncAnd = !N0.hasOneUse(); 7681 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 7682 CombineTo(N, And); 7683 // If N0 has multiple uses, change other uses as well. 7684 if (NoReplaceTruncAnd) { 7685 SDValue TruncAnd = 7686 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 7687 CombineTo(N0.getNode(), TruncAnd); 7688 } 7689 if (NoReplaceTrunc) 7690 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7691 else 7692 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7693 return SDValue(N,0); // Return N so it doesn't get rechecked! 7694 } 7695 } 7696 } 7697 7698 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7699 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7700 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7701 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7702 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7703 EVT MemVT = LN0->getMemoryVT(); 7704 if ((!LegalOperations && !LN0->isVolatile()) || 7705 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7706 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7707 LN0->getChain(), 7708 LN0->getBasePtr(), MemVT, 7709 LN0->getMemOperand()); 7710 CombineTo(N, ExtLoad); 7711 CombineTo(N0.getNode(), 7712 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7713 ExtLoad), 7714 ExtLoad.getValue(1)); 7715 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7716 } 7717 } 7718 7719 if (N0.getOpcode() == ISD::SETCC) { 7720 // Only do this before legalize for now. 7721 if (!LegalOperations && VT.isVector() && 7722 N0.getValueType().getVectorElementType() == MVT::i1) { 7723 EVT N00VT = N0.getOperand(0).getValueType(); 7724 if (getSetCCResultType(N00VT) == N0.getValueType()) 7725 return SDValue(); 7726 7727 // We know that the # elements of the results is the same as the # 7728 // elements of the compare (and the # elements of the compare result for 7729 // that matter). Check to see that they are the same size. If so, we know 7730 // that the element size of the sext'd result matches the element size of 7731 // the compare operands. 7732 SDLoc DL(N); 7733 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7734 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7735 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7736 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7737 N0.getOperand(1), N0.getOperand(2)); 7738 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7739 } 7740 7741 // If the desired elements are smaller or larger than the source 7742 // elements we can use a matching integer vector type and then 7743 // truncate/sign extend. 7744 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 7745 SDValue VsetCC = 7746 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7747 N0.getOperand(1), N0.getOperand(2)); 7748 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7749 VecOnes); 7750 } 7751 7752 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7753 SDLoc DL(N); 7754 if (SDValue SCC = SimplifySelectCC( 7755 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7756 DAG.getConstant(0, DL, VT), 7757 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7758 return SCC; 7759 } 7760 7761 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7762 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7763 isa<ConstantSDNode>(N0.getOperand(1)) && 7764 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7765 N0.hasOneUse()) { 7766 SDValue ShAmt = N0.getOperand(1); 7767 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7768 if (N0.getOpcode() == ISD::SHL) { 7769 SDValue InnerZExt = N0.getOperand(0); 7770 // If the original shl may be shifting out bits, do not perform this 7771 // transformation. 7772 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7773 InnerZExt.getOperand(0).getValueSizeInBits(); 7774 if (ShAmtVal > KnownZeroBits) 7775 return SDValue(); 7776 } 7777 7778 SDLoc DL(N); 7779 7780 // Ensure that the shift amount is wide enough for the shifted value. 7781 if (VT.getSizeInBits() >= 256) 7782 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7783 7784 return DAG.getNode(N0.getOpcode(), DL, VT, 7785 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7786 ShAmt); 7787 } 7788 7789 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7790 return NewVSel; 7791 7792 return SDValue(); 7793 } 7794 7795 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7796 SDValue N0 = N->getOperand(0); 7797 EVT VT = N->getValueType(0); 7798 7799 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7800 LegalOperations)) 7801 return SDValue(Res, 0); 7802 7803 // fold (aext (aext x)) -> (aext x) 7804 // fold (aext (zext x)) -> (zext x) 7805 // fold (aext (sext x)) -> (sext x) 7806 if (N0.getOpcode() == ISD::ANY_EXTEND || 7807 N0.getOpcode() == ISD::ZERO_EXTEND || 7808 N0.getOpcode() == ISD::SIGN_EXTEND) 7809 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7810 7811 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7812 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7813 if (N0.getOpcode() == ISD::TRUNCATE) { 7814 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7815 SDNode *oye = N0.getOperand(0).getNode(); 7816 if (NarrowLoad.getNode() != N0.getNode()) { 7817 CombineTo(N0.getNode(), NarrowLoad); 7818 // CombineTo deleted the truncate, if needed, but not what's under it. 7819 AddToWorklist(oye); 7820 } 7821 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7822 } 7823 } 7824 7825 // fold (aext (truncate x)) 7826 if (N0.getOpcode() == ISD::TRUNCATE) 7827 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7828 7829 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7830 // if the trunc is not free. 7831 if (N0.getOpcode() == ISD::AND && 7832 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7833 N0.getOperand(1).getOpcode() == ISD::Constant && 7834 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7835 N0.getValueType())) { 7836 SDLoc DL(N); 7837 SDValue X = N0.getOperand(0).getOperand(0); 7838 X = DAG.getAnyExtOrTrunc(X, DL, VT); 7839 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7840 Mask = Mask.zext(VT.getSizeInBits()); 7841 return DAG.getNode(ISD::AND, DL, VT, 7842 X, DAG.getConstant(Mask, DL, VT)); 7843 } 7844 7845 // fold (aext (load x)) -> (aext (truncate (extload x))) 7846 // None of the supported targets knows how to perform load and any_ext 7847 // on vectors in one instruction. We only perform this transformation on 7848 // scalars. 7849 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7850 ISD::isUNINDEXEDLoad(N0.getNode()) && 7851 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7852 bool DoXform = true; 7853 SmallVector<SDNode*, 4> SetCCs; 7854 if (!N0.hasOneUse()) 7855 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7856 if (DoXform) { 7857 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7858 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7859 LN0->getChain(), 7860 LN0->getBasePtr(), N0.getValueType(), 7861 LN0->getMemOperand()); 7862 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7863 N0.getValueType(), ExtLoad); 7864 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7865 ISD::ANY_EXTEND); 7866 // If the load value is used only by N, replace it via CombineTo N. 7867 bool NoReplaceTrunc = N0.hasOneUse(); 7868 CombineTo(N, ExtLoad); 7869 if (NoReplaceTrunc) 7870 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 7871 else 7872 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 7873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7874 } 7875 } 7876 7877 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7878 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7879 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7880 if (N0.getOpcode() == ISD::LOAD && 7881 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7882 N0.hasOneUse()) { 7883 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7884 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7885 EVT MemVT = LN0->getMemoryVT(); 7886 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7887 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7888 VT, LN0->getChain(), LN0->getBasePtr(), 7889 MemVT, LN0->getMemOperand()); 7890 CombineTo(N, ExtLoad); 7891 CombineTo(N0.getNode(), 7892 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7893 N0.getValueType(), ExtLoad), 7894 ExtLoad.getValue(1)); 7895 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7896 } 7897 } 7898 7899 if (N0.getOpcode() == ISD::SETCC) { 7900 // For vectors: 7901 // aext(setcc) -> vsetcc 7902 // aext(setcc) -> truncate(vsetcc) 7903 // aext(setcc) -> aext(vsetcc) 7904 // Only do this before legalize for now. 7905 if (VT.isVector() && !LegalOperations) { 7906 EVT N00VT = N0.getOperand(0).getValueType(); 7907 if (getSetCCResultType(N00VT) == N0.getValueType()) 7908 return SDValue(); 7909 7910 // We know that the # elements of the results is the same as the 7911 // # elements of the compare (and the # elements of the compare result 7912 // for that matter). Check to see that they are the same size. If so, 7913 // we know that the element size of the sext'd result matches the 7914 // element size of the compare operands. 7915 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 7916 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7917 N0.getOperand(1), 7918 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7919 // If the desired elements are smaller or larger than the source 7920 // elements we can use a matching integer vector type and then 7921 // truncate/any extend 7922 else { 7923 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 7924 SDValue VsetCC = 7925 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7926 N0.getOperand(1), 7927 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7928 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7929 } 7930 } 7931 7932 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7933 SDLoc DL(N); 7934 if (SDValue SCC = SimplifySelectCC( 7935 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7936 DAG.getConstant(0, DL, VT), 7937 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7938 return SCC; 7939 } 7940 7941 return SDValue(); 7942 } 7943 7944 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 7945 unsigned Opcode = N->getOpcode(); 7946 SDValue N0 = N->getOperand(0); 7947 SDValue N1 = N->getOperand(1); 7948 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 7949 7950 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 7951 if (N0.getOpcode() == Opcode && 7952 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7953 return N0; 7954 7955 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 7956 N0.getOperand(0).getOpcode() == Opcode) { 7957 // We have an assert, truncate, assert sandwich. Make one stronger assert 7958 // by asserting on the smallest asserted type to the larger source type. 7959 // This eliminates the later assert: 7960 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 7961 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 7962 SDValue BigA = N0.getOperand(0); 7963 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 7964 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 7965 "Asserting zero/sign-extended bits to a type larger than the " 7966 "truncated destination does not provide information"); 7967 7968 SDLoc DL(N); 7969 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 7970 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 7971 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 7972 BigA.getOperand(0), MinAssertVTVal); 7973 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 7974 } 7975 7976 return SDValue(); 7977 } 7978 7979 /// If the result of a wider load is shifted to right of N bits and then 7980 /// truncated to a narrower type and where N is a multiple of number of bits of 7981 /// the narrower type, transform it to a narrower load from address + N / num of 7982 /// bits of new type. Also narrow the load if the result is masked with an AND 7983 /// to effectively produce a smaller type. If the result is to be extended, also 7984 /// fold the extension to form a extending load. 7985 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7986 unsigned Opc = N->getOpcode(); 7987 7988 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7989 SDValue N0 = N->getOperand(0); 7990 EVT VT = N->getValueType(0); 7991 EVT ExtVT = VT; 7992 7993 // This transformation isn't valid for vector loads. 7994 if (VT.isVector()) 7995 return SDValue(); 7996 7997 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7998 // extended to VT. 7999 if (Opc == ISD::SIGN_EXTEND_INREG) { 8000 ExtType = ISD::SEXTLOAD; 8001 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8002 } else if (Opc == ISD::SRL) { 8003 // Another special-case: SRL is basically zero-extending a narrower value, 8004 // or it maybe shifting a higher subword, half or byte into the lowest 8005 // bits. 8006 ExtType = ISD::ZEXTLOAD; 8007 N0 = SDValue(N, 0); 8008 8009 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 8010 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8011 if (!N01 || !LN0) 8012 return SDValue(); 8013 8014 uint64_t ShiftAmt = N01->getZExtValue(); 8015 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 8016 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 8017 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 8018 else 8019 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 8020 VT.getSizeInBits() - ShiftAmt); 8021 } else if (Opc == ISD::AND) { 8022 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 8023 LoadSDNode *LN0 = 8024 HasAnyExt ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 8025 8026 if (LN0->getExtensionType() == ISD::SEXTLOAD || 8027 !LN0->isUnindexed() || !N0.hasOneUse() || !SDValue(LN0, 0).hasOneUse()) 8028 return SDValue(); 8029 8030 auto N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8031 if (!N1C) 8032 return SDValue(); 8033 8034 EVT LoadedVT; 8035 bool NarrowLoad = false; 8036 ExtType = ISD::ZEXTLOAD; 8037 VT = HasAnyExt ? LN0->getValueType(0) : VT; 8038 if (!isAndLoadExtLoad(N1C, LN0, VT, ExtVT, LoadedVT, NarrowLoad)) 8039 return SDValue(); 8040 8041 if (!NarrowLoad) 8042 return DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 8043 LN0->getChain(), LN0->getBasePtr(), ExtVT, 8044 LN0->getMemOperand()); 8045 } 8046 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 8047 return SDValue(); 8048 8049 unsigned EVTBits = ExtVT.getSizeInBits(); 8050 8051 // Do not generate loads of non-round integer types since these can 8052 // be expensive (and would be wrong if the type is not byte sized). 8053 if (!ExtVT.isRound()) 8054 return SDValue(); 8055 8056 unsigned ShAmt = 0; 8057 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 8058 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8059 ShAmt = N01->getZExtValue(); 8060 // Is the shift amount a multiple of size of VT? 8061 if ((ShAmt & (EVTBits-1)) == 0) { 8062 N0 = N0.getOperand(0); 8063 // Is the load width a multiple of size of VT? 8064 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 8065 return SDValue(); 8066 } 8067 8068 // At this point, we must have a load or else we can't do the transform. 8069 if (!isa<LoadSDNode>(N0)) return SDValue(); 8070 8071 // Because a SRL must be assumed to *need* to zero-extend the high bits 8072 // (as opposed to anyext the high bits), we can't combine the zextload 8073 // lowering of SRL and an sextload. 8074 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 8075 return SDValue(); 8076 8077 // If the shift amount is larger than the input type then we're not 8078 // accessing any of the loaded bytes. If the load was a zextload/extload 8079 // then the result of the shift+trunc is zero/undef (handled elsewhere). 8080 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 8081 return SDValue(); 8082 } 8083 } 8084 8085 // If the load is shifted left (and the result isn't shifted back right), 8086 // we can fold the truncate through the shift. 8087 unsigned ShLeftAmt = 0; 8088 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8089 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 8090 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 8091 ShLeftAmt = N01->getZExtValue(); 8092 N0 = N0.getOperand(0); 8093 } 8094 } 8095 8096 // If we haven't found a load, we can't narrow it. Don't transform one with 8097 // multiple uses, this would require adding a new load. 8098 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 8099 return SDValue(); 8100 8101 // Don't change the width of a volatile load. 8102 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8103 if (LN0->isVolatile()) 8104 return SDValue(); 8105 8106 // Verify that we are actually reducing a load width here. 8107 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 8108 return SDValue(); 8109 8110 // For the transform to be legal, the load must produce only two values 8111 // (the value loaded and the chain). Don't transform a pre-increment 8112 // load, for example, which produces an extra value. Otherwise the 8113 // transformation is not equivalent, and the downstream logic to replace 8114 // uses gets things wrong. 8115 if (LN0->getNumValues() > 2) 8116 return SDValue(); 8117 8118 // If the load that we're shrinking is an extload and we're not just 8119 // discarding the extension we can't simply shrink the load. Bail. 8120 // TODO: It would be possible to merge the extensions in some cases. 8121 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 8122 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 8123 return SDValue(); 8124 8125 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 8126 return SDValue(); 8127 8128 EVT PtrType = N0.getOperand(1).getValueType(); 8129 8130 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8131 // It's not possible to generate a constant of extended or untyped type. 8132 return SDValue(); 8133 8134 // For big endian targets, we need to adjust the offset to the pointer to 8135 // load the correct bytes. 8136 if (DAG.getDataLayout().isBigEndian()) { 8137 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8138 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8139 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8140 } 8141 8142 uint64_t PtrOff = ShAmt / 8; 8143 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8144 SDLoc DL(LN0); 8145 // The original load itself didn't wrap, so an offset within it doesn't. 8146 SDNodeFlags Flags; 8147 Flags.setNoUnsignedWrap(true); 8148 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8149 PtrType, LN0->getBasePtr(), 8150 DAG.getConstant(PtrOff, DL, PtrType), 8151 Flags); 8152 AddToWorklist(NewPtr.getNode()); 8153 8154 SDValue Load; 8155 if (ExtType == ISD::NON_EXTLOAD) 8156 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8157 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8158 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8159 else 8160 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8161 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8162 NewAlign, LN0->getMemOperand()->getFlags(), 8163 LN0->getAAInfo()); 8164 8165 // Replace the old load's chain with the new load's chain. 8166 WorklistRemover DeadNodes(*this); 8167 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8168 8169 // Shift the result left, if we've swallowed a left shift. 8170 SDValue Result = Load; 8171 if (ShLeftAmt != 0) { 8172 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8173 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8174 ShImmTy = VT; 8175 // If the shift amount is as large as the result size (but, presumably, 8176 // no larger than the source) then the useful bits of the result are 8177 // zero; we can't simply return the shortened shift, because the result 8178 // of that operation is undefined. 8179 SDLoc DL(N0); 8180 if (ShLeftAmt >= VT.getSizeInBits()) 8181 Result = DAG.getConstant(0, DL, VT); 8182 else 8183 Result = DAG.getNode(ISD::SHL, DL, VT, 8184 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8185 } 8186 8187 // Return the new loaded value. 8188 return Result; 8189 } 8190 8191 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8192 SDValue N0 = N->getOperand(0); 8193 SDValue N1 = N->getOperand(1); 8194 EVT VT = N->getValueType(0); 8195 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8196 unsigned VTBits = VT.getScalarSizeInBits(); 8197 unsigned EVTBits = EVT.getScalarSizeInBits(); 8198 8199 if (N0.isUndef()) 8200 return DAG.getUNDEF(VT); 8201 8202 // fold (sext_in_reg c1) -> c1 8203 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8204 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8205 8206 // If the input is already sign extended, just drop the extension. 8207 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8208 return N0; 8209 8210 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8211 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8212 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8213 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8214 N0.getOperand(0), N1); 8215 8216 // fold (sext_in_reg (sext x)) -> (sext x) 8217 // fold (sext_in_reg (aext x)) -> (sext x) 8218 // if x is small enough. 8219 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8220 SDValue N00 = N0.getOperand(0); 8221 if (N00.getScalarValueSizeInBits() <= EVTBits && 8222 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8223 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8224 } 8225 8226 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8227 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8228 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8229 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8230 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8231 if (!LegalOperations || 8232 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8233 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8234 } 8235 8236 // fold (sext_in_reg (zext x)) -> (sext x) 8237 // iff we are extending the source sign bit. 8238 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8239 SDValue N00 = N0.getOperand(0); 8240 if (N00.getScalarValueSizeInBits() == EVTBits && 8241 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8242 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8243 } 8244 8245 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8246 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8247 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8248 8249 // fold operands of sext_in_reg based on knowledge that the top bits are not 8250 // demanded. 8251 if (SimplifyDemandedBits(SDValue(N, 0))) 8252 return SDValue(N, 0); 8253 8254 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8255 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8256 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8257 return NarrowLoad; 8258 8259 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8260 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8261 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8262 if (N0.getOpcode() == ISD::SRL) { 8263 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8264 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8265 // We can turn this into an SRA iff the input to the SRL is already sign 8266 // extended enough. 8267 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8268 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8269 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8270 N0.getOperand(0), N0.getOperand(1)); 8271 } 8272 } 8273 8274 // fold (sext_inreg (extload x)) -> (sextload x) 8275 // If sextload is not supported by target, we can only do the combine when 8276 // load has one use. Doing otherwise can block folding the extload with other 8277 // extends that the target does support. 8278 if (ISD::isEXTLoad(N0.getNode()) && 8279 ISD::isUNINDEXEDLoad(N0.getNode()) && 8280 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8281 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 8282 N0.hasOneUse()) || 8283 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8284 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8285 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8286 LN0->getChain(), 8287 LN0->getBasePtr(), EVT, 8288 LN0->getMemOperand()); 8289 CombineTo(N, ExtLoad); 8290 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8291 AddToWorklist(ExtLoad.getNode()); 8292 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8293 } 8294 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8295 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8296 N0.hasOneUse() && 8297 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8298 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8299 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8300 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8301 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8302 LN0->getChain(), 8303 LN0->getBasePtr(), EVT, 8304 LN0->getMemOperand()); 8305 CombineTo(N, ExtLoad); 8306 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8307 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8308 } 8309 8310 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8311 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8312 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8313 N0.getOperand(1), false)) 8314 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8315 BSwap, N1); 8316 } 8317 8318 return SDValue(); 8319 } 8320 8321 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8322 SDValue N0 = N->getOperand(0); 8323 EVT VT = N->getValueType(0); 8324 8325 if (N0.isUndef()) 8326 return DAG.getUNDEF(VT); 8327 8328 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8329 LegalOperations)) 8330 return SDValue(Res, 0); 8331 8332 return SDValue(); 8333 } 8334 8335 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8336 SDValue N0 = N->getOperand(0); 8337 EVT VT = N->getValueType(0); 8338 8339 if (N0.isUndef()) 8340 return DAG.getUNDEF(VT); 8341 8342 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8343 LegalOperations)) 8344 return SDValue(Res, 0); 8345 8346 return SDValue(); 8347 } 8348 8349 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8350 SDValue N0 = N->getOperand(0); 8351 EVT VT = N->getValueType(0); 8352 bool isLE = DAG.getDataLayout().isLittleEndian(); 8353 8354 // noop truncate 8355 if (N0.getValueType() == N->getValueType(0)) 8356 return N0; 8357 8358 // fold (truncate (truncate x)) -> (truncate x) 8359 if (N0.getOpcode() == ISD::TRUNCATE) 8360 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8361 8362 // fold (truncate c1) -> c1 8363 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 8364 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8365 if (C.getNode() != N) 8366 return C; 8367 } 8368 8369 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8370 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8371 N0.getOpcode() == ISD::SIGN_EXTEND || 8372 N0.getOpcode() == ISD::ANY_EXTEND) { 8373 // if the source is smaller than the dest, we still need an extend. 8374 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8375 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8376 // if the source is larger than the dest, than we just need the truncate. 8377 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8378 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8379 // if the source and dest are the same type, we can drop both the extend 8380 // and the truncate. 8381 return N0.getOperand(0); 8382 } 8383 8384 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8385 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8386 return SDValue(); 8387 8388 // Fold extract-and-trunc into a narrow extract. For example: 8389 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8390 // i32 y = TRUNCATE(i64 x) 8391 // -- becomes -- 8392 // v16i8 b = BITCAST (v2i64 val) 8393 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8394 // 8395 // Note: We only run this optimization after type legalization (which often 8396 // creates this pattern) and before operation legalization after which 8397 // we need to be more careful about the vector instructions that we generate. 8398 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8399 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8400 EVT VecTy = N0.getOperand(0).getValueType(); 8401 EVT ExTy = N0.getValueType(); 8402 EVT TrTy = N->getValueType(0); 8403 8404 unsigned NumElem = VecTy.getVectorNumElements(); 8405 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8406 8407 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8408 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8409 8410 SDValue EltNo = N0->getOperand(1); 8411 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8412 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8413 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8414 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8415 8416 SDLoc DL(N); 8417 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8418 DAG.getBitcast(NVT, N0.getOperand(0)), 8419 DAG.getConstant(Index, DL, IndexTy)); 8420 } 8421 } 8422 8423 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8424 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8425 EVT SrcVT = N0.getValueType(); 8426 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8427 TLI.isTruncateFree(SrcVT, VT)) { 8428 SDLoc SL(N0); 8429 SDValue Cond = N0.getOperand(0); 8430 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8431 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8432 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8433 } 8434 } 8435 8436 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8437 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8438 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8439 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8440 SDValue Amt = N0.getOperand(1); 8441 KnownBits Known; 8442 DAG.computeKnownBits(Amt, Known); 8443 unsigned Size = VT.getScalarSizeInBits(); 8444 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 8445 SDLoc SL(N); 8446 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8447 8448 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8449 if (AmtVT != Amt.getValueType()) { 8450 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 8451 AddToWorklist(Amt.getNode()); 8452 } 8453 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 8454 } 8455 } 8456 8457 // Fold a series of buildvector, bitcast, and truncate if possible. 8458 // For example fold 8459 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8460 // (2xi32 (buildvector x, y)). 8461 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8462 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8463 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8464 N0.getOperand(0).hasOneUse()) { 8465 SDValue BuildVect = N0.getOperand(0); 8466 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8467 EVT TruncVecEltTy = VT.getVectorElementType(); 8468 8469 // Check that the element types match. 8470 if (BuildVectEltTy == TruncVecEltTy) { 8471 // Now we only need to compute the offset of the truncated elements. 8472 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8473 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8474 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8475 8476 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8477 "Invalid number of elements"); 8478 8479 SmallVector<SDValue, 8> Opnds; 8480 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8481 Opnds.push_back(BuildVect.getOperand(i)); 8482 8483 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8484 } 8485 } 8486 8487 // See if we can simplify the input to this truncate through knowledge that 8488 // only the low bits are being used. 8489 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8490 // Currently we only perform this optimization on scalars because vectors 8491 // may have different active low bits. 8492 if (!VT.isVector()) { 8493 APInt Mask = 8494 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 8495 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 8496 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8497 } 8498 8499 // fold (truncate (load x)) -> (smaller load x) 8500 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8501 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8502 if (SDValue Reduced = ReduceLoadWidth(N)) 8503 return Reduced; 8504 8505 // Handle the case where the load remains an extending load even 8506 // after truncation. 8507 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8508 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8509 if (!LN0->isVolatile() && 8510 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8511 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8512 VT, LN0->getChain(), LN0->getBasePtr(), 8513 LN0->getMemoryVT(), 8514 LN0->getMemOperand()); 8515 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8516 return NewLoad; 8517 } 8518 } 8519 } 8520 8521 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8522 // where ... are all 'undef'. 8523 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8524 SmallVector<EVT, 8> VTs; 8525 SDValue V; 8526 unsigned Idx = 0; 8527 unsigned NumDefs = 0; 8528 8529 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8530 SDValue X = N0.getOperand(i); 8531 if (!X.isUndef()) { 8532 V = X; 8533 Idx = i; 8534 NumDefs++; 8535 } 8536 // Stop if more than one members are non-undef. 8537 if (NumDefs > 1) 8538 break; 8539 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8540 VT.getVectorElementType(), 8541 X.getValueType().getVectorNumElements())); 8542 } 8543 8544 if (NumDefs == 0) 8545 return DAG.getUNDEF(VT); 8546 8547 if (NumDefs == 1) { 8548 assert(V.getNode() && "The single defined operand is empty!"); 8549 SmallVector<SDValue, 8> Opnds; 8550 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8551 if (i != Idx) { 8552 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8553 continue; 8554 } 8555 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8556 AddToWorklist(NV.getNode()); 8557 Opnds.push_back(NV); 8558 } 8559 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8560 } 8561 } 8562 8563 // Fold truncate of a bitcast of a vector to an extract of the low vector 8564 // element. 8565 // 8566 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 8567 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8568 SDValue VecSrc = N0.getOperand(0); 8569 EVT SrcVT = VecSrc.getValueType(); 8570 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8571 (!LegalOperations || 8572 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8573 SDLoc SL(N); 8574 8575 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8576 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 8577 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8578 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 8579 } 8580 } 8581 8582 // Simplify the operands using demanded-bits information. 8583 if (!VT.isVector() && 8584 SimplifyDemandedBits(SDValue(N, 0))) 8585 return SDValue(N, 0); 8586 8587 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8588 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8589 // When the adde's carry is not used. 8590 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8591 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8592 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8593 SDLoc SL(N); 8594 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8595 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8596 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8597 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8598 } 8599 8600 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8601 return NewVSel; 8602 8603 return SDValue(); 8604 } 8605 8606 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8607 SDValue Elt = N->getOperand(i); 8608 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8609 return Elt.getNode(); 8610 return Elt.getOperand(Elt.getResNo()).getNode(); 8611 } 8612 8613 /// build_pair (load, load) -> load 8614 /// if load locations are consecutive. 8615 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8616 assert(N->getOpcode() == ISD::BUILD_PAIR); 8617 8618 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8619 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8620 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8621 LD1->getAddressSpace() != LD2->getAddressSpace()) 8622 return SDValue(); 8623 EVT LD1VT = LD1->getValueType(0); 8624 unsigned LD1Bytes = LD1VT.getStoreSize(); 8625 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8626 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8627 unsigned Align = LD1->getAlignment(); 8628 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8629 VT.getTypeForEVT(*DAG.getContext())); 8630 8631 if (NewAlign <= Align && 8632 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8633 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8634 LD1->getPointerInfo(), Align); 8635 } 8636 8637 return SDValue(); 8638 } 8639 8640 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8641 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8642 // and Lo parts; on big-endian machines it doesn't. 8643 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8644 } 8645 8646 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8647 const TargetLowering &TLI) { 8648 // If this is not a bitcast to an FP type or if the target doesn't have 8649 // IEEE754-compliant FP logic, we're done. 8650 EVT VT = N->getValueType(0); 8651 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8652 return SDValue(); 8653 8654 // TODO: Use splat values for the constant-checking below and remove this 8655 // restriction. 8656 SDValue N0 = N->getOperand(0); 8657 EVT SourceVT = N0.getValueType(); 8658 if (SourceVT.isVector()) 8659 return SDValue(); 8660 8661 unsigned FPOpcode; 8662 APInt SignMask; 8663 switch (N0.getOpcode()) { 8664 case ISD::AND: 8665 FPOpcode = ISD::FABS; 8666 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8667 break; 8668 case ISD::XOR: 8669 FPOpcode = ISD::FNEG; 8670 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8671 break; 8672 // TODO: ISD::OR --> ISD::FNABS? 8673 default: 8674 return SDValue(); 8675 } 8676 8677 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8678 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8679 SDValue LogicOp0 = N0.getOperand(0); 8680 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8681 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8682 LogicOp0.getOpcode() == ISD::BITCAST && 8683 LogicOp0->getOperand(0).getValueType() == VT) 8684 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8685 8686 return SDValue(); 8687 } 8688 8689 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8690 SDValue N0 = N->getOperand(0); 8691 EVT VT = N->getValueType(0); 8692 8693 if (N0.isUndef()) 8694 return DAG.getUNDEF(VT); 8695 8696 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8697 // Only do this before legalize, since afterward the target may be depending 8698 // on the bitconvert. 8699 // First check to see if this is all constant. 8700 if (!LegalTypes && 8701 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8702 VT.isVector()) { 8703 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8704 8705 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8706 assert(!DestEltVT.isVector() && 8707 "Element type of vector ValueType must not be vector!"); 8708 if (isSimple) 8709 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8710 } 8711 8712 // If the input is a constant, let getNode fold it. 8713 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8714 // If we can't allow illegal operations, we need to check that this is just 8715 // a fp -> int or int -> conversion and that the resulting operation will 8716 // be legal. 8717 if (!LegalOperations || 8718 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8719 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8720 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8721 TLI.isOperationLegal(ISD::Constant, VT))) 8722 return DAG.getBitcast(VT, N0); 8723 } 8724 8725 // (conv (conv x, t1), t2) -> (conv x, t2) 8726 if (N0.getOpcode() == ISD::BITCAST) 8727 return DAG.getBitcast(VT, N0.getOperand(0)); 8728 8729 // fold (conv (load x)) -> (load (conv*)x) 8730 // If the resultant load doesn't need a higher alignment than the original! 8731 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8732 // Do not change the width of a volatile load. 8733 !cast<LoadSDNode>(N0)->isVolatile() && 8734 // Do not remove the cast if the types differ in endian layout. 8735 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8736 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8737 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8738 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8739 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8740 unsigned OrigAlign = LN0->getAlignment(); 8741 8742 bool Fast = false; 8743 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8744 LN0->getAddressSpace(), OrigAlign, &Fast) && 8745 Fast) { 8746 SDValue Load = 8747 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8748 LN0->getPointerInfo(), OrigAlign, 8749 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8750 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8751 return Load; 8752 } 8753 } 8754 8755 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8756 return V; 8757 8758 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8759 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8760 // 8761 // For ppc_fp128: 8762 // fold (bitcast (fneg x)) -> 8763 // flipbit = signbit 8764 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8765 // 8766 // fold (bitcast (fabs x)) -> 8767 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8768 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8769 // This often reduces constant pool loads. 8770 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8771 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8772 N0.getNode()->hasOneUse() && VT.isInteger() && 8773 !VT.isVector() && !N0.getValueType().isVector()) { 8774 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8775 AddToWorklist(NewConv.getNode()); 8776 8777 SDLoc DL(N); 8778 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8779 assert(VT.getSizeInBits() == 128); 8780 SDValue SignBit = DAG.getConstant( 8781 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8782 SDValue FlipBit; 8783 if (N0.getOpcode() == ISD::FNEG) { 8784 FlipBit = SignBit; 8785 AddToWorklist(FlipBit.getNode()); 8786 } else { 8787 assert(N0.getOpcode() == ISD::FABS); 8788 SDValue Hi = 8789 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8790 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8791 SDLoc(NewConv))); 8792 AddToWorklist(Hi.getNode()); 8793 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8794 AddToWorklist(FlipBit.getNode()); 8795 } 8796 SDValue FlipBits = 8797 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8798 AddToWorklist(FlipBits.getNode()); 8799 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8800 } 8801 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8802 if (N0.getOpcode() == ISD::FNEG) 8803 return DAG.getNode(ISD::XOR, DL, VT, 8804 NewConv, DAG.getConstant(SignBit, DL, VT)); 8805 assert(N0.getOpcode() == ISD::FABS); 8806 return DAG.getNode(ISD::AND, DL, VT, 8807 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8808 } 8809 8810 // fold (bitconvert (fcopysign cst, x)) -> 8811 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8812 // Note that we don't handle (copysign x, cst) because this can always be 8813 // folded to an fneg or fabs. 8814 // 8815 // For ppc_fp128: 8816 // fold (bitcast (fcopysign cst, x)) -> 8817 // flipbit = (and (extract_element 8818 // (xor (bitcast cst), (bitcast x)), 0), 8819 // signbit) 8820 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8821 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8822 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8823 VT.isInteger() && !VT.isVector()) { 8824 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8825 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8826 if (isTypeLegal(IntXVT)) { 8827 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8828 AddToWorklist(X.getNode()); 8829 8830 // If X has a different width than the result/lhs, sext it or truncate it. 8831 unsigned VTWidth = VT.getSizeInBits(); 8832 if (OrigXWidth < VTWidth) { 8833 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8834 AddToWorklist(X.getNode()); 8835 } else if (OrigXWidth > VTWidth) { 8836 // To get the sign bit in the right place, we have to shift it right 8837 // before truncating. 8838 SDLoc DL(X); 8839 X = DAG.getNode(ISD::SRL, DL, 8840 X.getValueType(), X, 8841 DAG.getConstant(OrigXWidth-VTWidth, DL, 8842 X.getValueType())); 8843 AddToWorklist(X.getNode()); 8844 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8845 AddToWorklist(X.getNode()); 8846 } 8847 8848 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8849 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 8850 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8851 AddToWorklist(Cst.getNode()); 8852 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8853 AddToWorklist(X.getNode()); 8854 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8855 AddToWorklist(XorResult.getNode()); 8856 SDValue XorResult64 = DAG.getNode( 8857 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8858 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8859 SDLoc(XorResult))); 8860 AddToWorklist(XorResult64.getNode()); 8861 SDValue FlipBit = 8862 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8863 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8864 AddToWorklist(FlipBit.getNode()); 8865 SDValue FlipBits = 8866 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8867 AddToWorklist(FlipBits.getNode()); 8868 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8869 } 8870 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8871 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8872 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8873 AddToWorklist(X.getNode()); 8874 8875 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8876 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8877 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8878 AddToWorklist(Cst.getNode()); 8879 8880 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8881 } 8882 } 8883 8884 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8885 if (N0.getOpcode() == ISD::BUILD_PAIR) 8886 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8887 return CombineLD; 8888 8889 // Remove double bitcasts from shuffles - this is often a legacy of 8890 // XformToShuffleWithZero being used to combine bitmaskings (of 8891 // float vectors bitcast to integer vectors) into shuffles. 8892 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8893 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8894 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8895 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8896 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8897 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8898 8899 // If operands are a bitcast, peek through if it casts the original VT. 8900 // If operands are a constant, just bitcast back to original VT. 8901 auto PeekThroughBitcast = [&](SDValue Op) { 8902 if (Op.getOpcode() == ISD::BITCAST && 8903 Op.getOperand(0).getValueType() == VT) 8904 return SDValue(Op.getOperand(0)); 8905 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8906 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8907 return DAG.getBitcast(VT, Op); 8908 return SDValue(); 8909 }; 8910 8911 // FIXME: If either input vector is bitcast, try to convert the shuffle to 8912 // the result type of this bitcast. This would eliminate at least one 8913 // bitcast. See the transform in InstCombine. 8914 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8915 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8916 if (!(SV0 && SV1)) 8917 return SDValue(); 8918 8919 int MaskScale = 8920 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8921 SmallVector<int, 8> NewMask; 8922 for (int M : SVN->getMask()) 8923 for (int i = 0; i != MaskScale; ++i) 8924 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8925 8926 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8927 if (!LegalMask) { 8928 std::swap(SV0, SV1); 8929 ShuffleVectorSDNode::commuteMask(NewMask); 8930 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8931 } 8932 8933 if (LegalMask) 8934 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8935 } 8936 8937 return SDValue(); 8938 } 8939 8940 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8941 EVT VT = N->getValueType(0); 8942 return CombineConsecutiveLoads(N, VT); 8943 } 8944 8945 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8946 /// operands. DstEltVT indicates the destination element value type. 8947 SDValue DAGCombiner:: 8948 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8949 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8950 8951 // If this is already the right type, we're done. 8952 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8953 8954 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8955 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8956 8957 // If this is a conversion of N elements of one type to N elements of another 8958 // type, convert each element. This handles FP<->INT cases. 8959 if (SrcBitSize == DstBitSize) { 8960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8961 BV->getValueType(0).getVectorNumElements()); 8962 8963 // Due to the FP element handling below calling this routine recursively, 8964 // we can end up with a scalar-to-vector node here. 8965 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8966 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8967 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8968 8969 SmallVector<SDValue, 8> Ops; 8970 for (SDValue Op : BV->op_values()) { 8971 // If the vector element type is not legal, the BUILD_VECTOR operands 8972 // are promoted and implicitly truncated. Make that explicit here. 8973 if (Op.getValueType() != SrcEltVT) 8974 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8975 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8976 AddToWorklist(Ops.back().getNode()); 8977 } 8978 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8979 } 8980 8981 // Otherwise, we're growing or shrinking the elements. To avoid having to 8982 // handle annoying details of growing/shrinking FP values, we convert them to 8983 // int first. 8984 if (SrcEltVT.isFloatingPoint()) { 8985 // Convert the input float vector to a int vector where the elements are the 8986 // same sizes. 8987 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8988 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8989 SrcEltVT = IntVT; 8990 } 8991 8992 // Now we know the input is an integer vector. If the output is a FP type, 8993 // convert to integer first, then to FP of the right size. 8994 if (DstEltVT.isFloatingPoint()) { 8995 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8996 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8997 8998 // Next, convert to FP elements of the same size. 8999 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 9000 } 9001 9002 SDLoc DL(BV); 9003 9004 // Okay, we know the src/dst types are both integers of differing types. 9005 // Handling growing first. 9006 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 9007 if (SrcBitSize < DstBitSize) { 9008 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 9009 9010 SmallVector<SDValue, 8> Ops; 9011 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 9012 i += NumInputsPerOutput) { 9013 bool isLE = DAG.getDataLayout().isLittleEndian(); 9014 APInt NewBits = APInt(DstBitSize, 0); 9015 bool EltIsUndef = true; 9016 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 9017 // Shift the previously computed bits over. 9018 NewBits <<= SrcBitSize; 9019 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 9020 if (Op.isUndef()) continue; 9021 EltIsUndef = false; 9022 9023 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 9024 zextOrTrunc(SrcBitSize).zext(DstBitSize); 9025 } 9026 9027 if (EltIsUndef) 9028 Ops.push_back(DAG.getUNDEF(DstEltVT)); 9029 else 9030 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 9031 } 9032 9033 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 9034 return DAG.getBuildVector(VT, DL, Ops); 9035 } 9036 9037 // Finally, this must be the case where we are shrinking elements: each input 9038 // turns into multiple outputs. 9039 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 9040 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 9041 NumOutputsPerInput*BV->getNumOperands()); 9042 SmallVector<SDValue, 8> Ops; 9043 9044 for (const SDValue &Op : BV->op_values()) { 9045 if (Op.isUndef()) { 9046 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 9047 continue; 9048 } 9049 9050 APInt OpVal = cast<ConstantSDNode>(Op)-> 9051 getAPIntValue().zextOrTrunc(SrcBitSize); 9052 9053 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 9054 APInt ThisVal = OpVal.trunc(DstBitSize); 9055 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 9056 OpVal.lshrInPlace(DstBitSize); 9057 } 9058 9059 // For big endian targets, swap the order of the pieces of each element. 9060 if (DAG.getDataLayout().isBigEndian()) 9061 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 9062 } 9063 9064 return DAG.getBuildVector(VT, DL, Ops); 9065 } 9066 9067 static bool isContractable(SDNode *N) { 9068 SDNodeFlags F = N->getFlags(); 9069 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 9070 } 9071 9072 /// Try to perform FMA combining on a given FADD node. 9073 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 9074 SDValue N0 = N->getOperand(0); 9075 SDValue N1 = N->getOperand(1); 9076 EVT VT = N->getValueType(0); 9077 SDLoc SL(N); 9078 9079 const TargetOptions &Options = DAG.getTarget().Options; 9080 9081 // Floating-point multiply-add with intermediate rounding. 9082 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9083 9084 // Floating-point multiply-add without intermediate rounding. 9085 bool HasFMA = 9086 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9087 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9088 9089 // No valid opcode, do not combine. 9090 if (!HasFMAD && !HasFMA) 9091 return SDValue(); 9092 9093 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9094 Options.UnsafeFPMath || HasFMAD); 9095 // If the addition is not contractable, do not combine. 9096 if (!AllowFusionGlobally && !isContractable(N)) 9097 return SDValue(); 9098 9099 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9100 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9101 return SDValue(); 9102 9103 // Always prefer FMAD to FMA for precision. 9104 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9105 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9106 9107 // Is the node an FMUL and contractable either due to global flags or 9108 // SDNodeFlags. 9109 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9110 if (N.getOpcode() != ISD::FMUL) 9111 return false; 9112 return AllowFusionGlobally || isContractable(N.getNode()); 9113 }; 9114 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 9115 // prefer to fold the multiply with fewer uses. 9116 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 9117 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 9118 std::swap(N0, N1); 9119 } 9120 9121 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 9122 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9123 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9124 N0.getOperand(0), N0.getOperand(1), N1); 9125 } 9126 9127 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 9128 // Note: Commutes FADD operands. 9129 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 9130 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9131 N1.getOperand(0), N1.getOperand(1), N0); 9132 } 9133 9134 // Look through FP_EXTEND nodes to do more combining. 9135 9136 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9137 if (N0.getOpcode() == ISD::FP_EXTEND) { 9138 SDValue N00 = N0.getOperand(0); 9139 if (isContractableFMUL(N00) && 9140 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9141 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9142 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9143 N00.getOperand(0)), 9144 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9145 N00.getOperand(1)), N1); 9146 } 9147 } 9148 9149 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9150 // Note: Commutes FADD operands. 9151 if (N1.getOpcode() == ISD::FP_EXTEND) { 9152 SDValue N10 = N1.getOperand(0); 9153 if (isContractableFMUL(N10) && 9154 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9155 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9156 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9157 N10.getOperand(0)), 9158 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9159 N10.getOperand(1)), N0); 9160 } 9161 } 9162 9163 // More folding opportunities when target permits. 9164 if (Aggressive) { 9165 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9166 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9167 // are currently only supported on binary nodes. 9168 if (Options.UnsafeFPMath && 9169 N0.getOpcode() == PreferredFusedOpcode && 9170 N0.getOperand(2).getOpcode() == ISD::FMUL && 9171 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9172 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9173 N0.getOperand(0), N0.getOperand(1), 9174 DAG.getNode(PreferredFusedOpcode, SL, VT, 9175 N0.getOperand(2).getOperand(0), 9176 N0.getOperand(2).getOperand(1), 9177 N1)); 9178 } 9179 9180 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9181 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9182 // are currently only supported on binary nodes. 9183 if (Options.UnsafeFPMath && 9184 N1->getOpcode() == PreferredFusedOpcode && 9185 N1.getOperand(2).getOpcode() == ISD::FMUL && 9186 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9187 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9188 N1.getOperand(0), N1.getOperand(1), 9189 DAG.getNode(PreferredFusedOpcode, SL, VT, 9190 N1.getOperand(2).getOperand(0), 9191 N1.getOperand(2).getOperand(1), 9192 N0)); 9193 } 9194 9195 9196 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9197 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9198 auto FoldFAddFMAFPExtFMul = [&] ( 9199 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9200 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9201 DAG.getNode(PreferredFusedOpcode, SL, VT, 9202 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9203 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9204 Z)); 9205 }; 9206 if (N0.getOpcode() == PreferredFusedOpcode) { 9207 SDValue N02 = N0.getOperand(2); 9208 if (N02.getOpcode() == ISD::FP_EXTEND) { 9209 SDValue N020 = N02.getOperand(0); 9210 if (isContractableFMUL(N020) && 9211 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9212 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9213 N020.getOperand(0), N020.getOperand(1), 9214 N1); 9215 } 9216 } 9217 } 9218 9219 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9220 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9221 // FIXME: This turns two single-precision and one double-precision 9222 // operation into two double-precision operations, which might not be 9223 // interesting for all targets, especially GPUs. 9224 auto FoldFAddFPExtFMAFMul = [&] ( 9225 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9226 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9227 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9228 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9229 DAG.getNode(PreferredFusedOpcode, SL, VT, 9230 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9231 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9232 Z)); 9233 }; 9234 if (N0.getOpcode() == ISD::FP_EXTEND) { 9235 SDValue N00 = N0.getOperand(0); 9236 if (N00.getOpcode() == PreferredFusedOpcode) { 9237 SDValue N002 = N00.getOperand(2); 9238 if (isContractableFMUL(N002) && 9239 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9240 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9241 N002.getOperand(0), N002.getOperand(1), 9242 N1); 9243 } 9244 } 9245 } 9246 9247 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9248 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9249 if (N1.getOpcode() == PreferredFusedOpcode) { 9250 SDValue N12 = N1.getOperand(2); 9251 if (N12.getOpcode() == ISD::FP_EXTEND) { 9252 SDValue N120 = N12.getOperand(0); 9253 if (isContractableFMUL(N120) && 9254 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9255 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9256 N120.getOperand(0), N120.getOperand(1), 9257 N0); 9258 } 9259 } 9260 } 9261 9262 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9263 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9264 // FIXME: This turns two single-precision and one double-precision 9265 // operation into two double-precision operations, which might not be 9266 // interesting for all targets, especially GPUs. 9267 if (N1.getOpcode() == ISD::FP_EXTEND) { 9268 SDValue N10 = N1.getOperand(0); 9269 if (N10.getOpcode() == PreferredFusedOpcode) { 9270 SDValue N102 = N10.getOperand(2); 9271 if (isContractableFMUL(N102) && 9272 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9273 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9274 N102.getOperand(0), N102.getOperand(1), 9275 N0); 9276 } 9277 } 9278 } 9279 } 9280 9281 return SDValue(); 9282 } 9283 9284 /// Try to perform FMA combining on a given FSUB node. 9285 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9286 SDValue N0 = N->getOperand(0); 9287 SDValue N1 = N->getOperand(1); 9288 EVT VT = N->getValueType(0); 9289 SDLoc SL(N); 9290 9291 const TargetOptions &Options = DAG.getTarget().Options; 9292 // Floating-point multiply-add with intermediate rounding. 9293 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9294 9295 // Floating-point multiply-add without intermediate rounding. 9296 bool HasFMA = 9297 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9298 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9299 9300 // No valid opcode, do not combine. 9301 if (!HasFMAD && !HasFMA) 9302 return SDValue(); 9303 9304 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9305 Options.UnsafeFPMath || HasFMAD); 9306 // If the subtraction is not contractable, do not combine. 9307 if (!AllowFusionGlobally && !isContractable(N)) 9308 return SDValue(); 9309 9310 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9311 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9312 return SDValue(); 9313 9314 // Always prefer FMAD to FMA for precision. 9315 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9316 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9317 9318 // Is the node an FMUL and contractable either due to global flags or 9319 // SDNodeFlags. 9320 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9321 if (N.getOpcode() != ISD::FMUL) 9322 return false; 9323 return AllowFusionGlobally || isContractable(N.getNode()); 9324 }; 9325 9326 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9327 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9328 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9329 N0.getOperand(0), N0.getOperand(1), 9330 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9331 } 9332 9333 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9334 // Note: Commutes FSUB operands. 9335 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9336 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9337 DAG.getNode(ISD::FNEG, SL, VT, 9338 N1.getOperand(0)), 9339 N1.getOperand(1), N0); 9340 9341 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9342 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9343 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9344 SDValue N00 = N0.getOperand(0).getOperand(0); 9345 SDValue N01 = N0.getOperand(0).getOperand(1); 9346 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9347 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9348 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9349 } 9350 9351 // Look through FP_EXTEND nodes to do more combining. 9352 9353 // fold (fsub (fpext (fmul x, y)), z) 9354 // -> (fma (fpext x), (fpext y), (fneg z)) 9355 if (N0.getOpcode() == ISD::FP_EXTEND) { 9356 SDValue N00 = N0.getOperand(0); 9357 if (isContractableFMUL(N00) && 9358 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9359 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9360 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9361 N00.getOperand(0)), 9362 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9363 N00.getOperand(1)), 9364 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9365 } 9366 } 9367 9368 // fold (fsub x, (fpext (fmul y, z))) 9369 // -> (fma (fneg (fpext y)), (fpext z), x) 9370 // Note: Commutes FSUB operands. 9371 if (N1.getOpcode() == ISD::FP_EXTEND) { 9372 SDValue N10 = N1.getOperand(0); 9373 if (isContractableFMUL(N10) && 9374 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 9375 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9376 DAG.getNode(ISD::FNEG, SL, VT, 9377 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9378 N10.getOperand(0))), 9379 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9380 N10.getOperand(1)), 9381 N0); 9382 } 9383 } 9384 9385 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9386 // -> (fneg (fma (fpext x), (fpext y), z)) 9387 // Note: This could be removed with appropriate canonicalization of the 9388 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9389 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9390 // from implementing the canonicalization in visitFSUB. 9391 if (N0.getOpcode() == ISD::FP_EXTEND) { 9392 SDValue N00 = N0.getOperand(0); 9393 if (N00.getOpcode() == ISD::FNEG) { 9394 SDValue N000 = N00.getOperand(0); 9395 if (isContractableFMUL(N000) && 9396 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9397 return DAG.getNode(ISD::FNEG, SL, VT, 9398 DAG.getNode(PreferredFusedOpcode, SL, VT, 9399 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9400 N000.getOperand(0)), 9401 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9402 N000.getOperand(1)), 9403 N1)); 9404 } 9405 } 9406 } 9407 9408 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9409 // -> (fneg (fma (fpext x)), (fpext y), z) 9410 // Note: This could be removed with appropriate canonicalization of the 9411 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9412 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9413 // from implementing the canonicalization in visitFSUB. 9414 if (N0.getOpcode() == ISD::FNEG) { 9415 SDValue N00 = N0.getOperand(0); 9416 if (N00.getOpcode() == ISD::FP_EXTEND) { 9417 SDValue N000 = N00.getOperand(0); 9418 if (isContractableFMUL(N000) && 9419 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 9420 return DAG.getNode(ISD::FNEG, SL, VT, 9421 DAG.getNode(PreferredFusedOpcode, SL, VT, 9422 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9423 N000.getOperand(0)), 9424 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9425 N000.getOperand(1)), 9426 N1)); 9427 } 9428 } 9429 } 9430 9431 // More folding opportunities when target permits. 9432 if (Aggressive) { 9433 // fold (fsub (fma x, y, (fmul u, v)), z) 9434 // -> (fma x, y (fma u, v, (fneg z))) 9435 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9436 // are currently only supported on binary nodes. 9437 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9438 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9439 N0.getOperand(2)->hasOneUse()) { 9440 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9441 N0.getOperand(0), N0.getOperand(1), 9442 DAG.getNode(PreferredFusedOpcode, SL, VT, 9443 N0.getOperand(2).getOperand(0), 9444 N0.getOperand(2).getOperand(1), 9445 DAG.getNode(ISD::FNEG, SL, VT, 9446 N1))); 9447 } 9448 9449 // fold (fsub x, (fma y, z, (fmul u, v))) 9450 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9451 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9452 // are currently only supported on binary nodes. 9453 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9454 isContractableFMUL(N1.getOperand(2))) { 9455 SDValue N20 = N1.getOperand(2).getOperand(0); 9456 SDValue N21 = N1.getOperand(2).getOperand(1); 9457 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9458 DAG.getNode(ISD::FNEG, SL, VT, 9459 N1.getOperand(0)), 9460 N1.getOperand(1), 9461 DAG.getNode(PreferredFusedOpcode, SL, VT, 9462 DAG.getNode(ISD::FNEG, SL, VT, N20), 9463 9464 N21, N0)); 9465 } 9466 9467 9468 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9469 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9470 if (N0.getOpcode() == PreferredFusedOpcode) { 9471 SDValue N02 = N0.getOperand(2); 9472 if (N02.getOpcode() == ISD::FP_EXTEND) { 9473 SDValue N020 = N02.getOperand(0); 9474 if (isContractableFMUL(N020) && 9475 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 9476 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9477 N0.getOperand(0), N0.getOperand(1), 9478 DAG.getNode(PreferredFusedOpcode, SL, VT, 9479 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9480 N020.getOperand(0)), 9481 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9482 N020.getOperand(1)), 9483 DAG.getNode(ISD::FNEG, SL, VT, 9484 N1))); 9485 } 9486 } 9487 } 9488 9489 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9490 // -> (fma (fpext x), (fpext y), 9491 // (fma (fpext u), (fpext v), (fneg z))) 9492 // FIXME: This turns two single-precision and one double-precision 9493 // operation into two double-precision operations, which might not be 9494 // interesting for all targets, especially GPUs. 9495 if (N0.getOpcode() == ISD::FP_EXTEND) { 9496 SDValue N00 = N0.getOperand(0); 9497 if (N00.getOpcode() == PreferredFusedOpcode) { 9498 SDValue N002 = N00.getOperand(2); 9499 if (isContractableFMUL(N002) && 9500 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 9501 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9502 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9503 N00.getOperand(0)), 9504 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9505 N00.getOperand(1)), 9506 DAG.getNode(PreferredFusedOpcode, SL, VT, 9507 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9508 N002.getOperand(0)), 9509 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9510 N002.getOperand(1)), 9511 DAG.getNode(ISD::FNEG, SL, VT, 9512 N1))); 9513 } 9514 } 9515 } 9516 9517 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9518 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9519 if (N1.getOpcode() == PreferredFusedOpcode && 9520 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9521 SDValue N120 = N1.getOperand(2).getOperand(0); 9522 if (isContractableFMUL(N120) && 9523 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 9524 SDValue N1200 = N120.getOperand(0); 9525 SDValue N1201 = N120.getOperand(1); 9526 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9527 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9528 N1.getOperand(1), 9529 DAG.getNode(PreferredFusedOpcode, SL, VT, 9530 DAG.getNode(ISD::FNEG, SL, VT, 9531 DAG.getNode(ISD::FP_EXTEND, SL, 9532 VT, N1200)), 9533 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9534 N1201), 9535 N0)); 9536 } 9537 } 9538 9539 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9540 // -> (fma (fneg (fpext y)), (fpext z), 9541 // (fma (fneg (fpext u)), (fpext v), x)) 9542 // FIXME: This turns two single-precision and one double-precision 9543 // operation into two double-precision operations, which might not be 9544 // interesting for all targets, especially GPUs. 9545 if (N1.getOpcode() == ISD::FP_EXTEND && 9546 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9547 SDValue CvtSrc = N1.getOperand(0); 9548 SDValue N100 = CvtSrc.getOperand(0); 9549 SDValue N101 = CvtSrc.getOperand(1); 9550 SDValue N102 = CvtSrc.getOperand(2); 9551 if (isContractableFMUL(N102) && 9552 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 9553 SDValue N1020 = N102.getOperand(0); 9554 SDValue N1021 = N102.getOperand(1); 9555 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9556 DAG.getNode(ISD::FNEG, SL, VT, 9557 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9558 N100)), 9559 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9560 DAG.getNode(PreferredFusedOpcode, SL, VT, 9561 DAG.getNode(ISD::FNEG, SL, VT, 9562 DAG.getNode(ISD::FP_EXTEND, SL, 9563 VT, N1020)), 9564 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9565 N1021), 9566 N0)); 9567 } 9568 } 9569 } 9570 9571 return SDValue(); 9572 } 9573 9574 /// Try to perform FMA combining on a given FMUL node based on the distributive 9575 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9576 /// subtraction instead of addition). 9577 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9578 SDValue N0 = N->getOperand(0); 9579 SDValue N1 = N->getOperand(1); 9580 EVT VT = N->getValueType(0); 9581 SDLoc SL(N); 9582 9583 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9584 9585 const TargetOptions &Options = DAG.getTarget().Options; 9586 9587 // The transforms below are incorrect when x == 0 and y == inf, because the 9588 // intermediate multiplication produces a nan. 9589 if (!Options.NoInfsFPMath) 9590 return SDValue(); 9591 9592 // Floating-point multiply-add without intermediate rounding. 9593 bool HasFMA = 9594 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9595 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9596 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9597 9598 // Floating-point multiply-add with intermediate rounding. This can result 9599 // in a less precise result due to the changed rounding order. 9600 bool HasFMAD = Options.UnsafeFPMath && 9601 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9602 9603 // No valid opcode, do not combine. 9604 if (!HasFMAD && !HasFMA) 9605 return SDValue(); 9606 9607 // Always prefer FMAD to FMA for precision. 9608 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9609 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9610 9611 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9612 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9613 auto FuseFADD = [&](SDValue X, SDValue Y) { 9614 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9615 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9616 if (XC1 && XC1->isExactlyValue(+1.0)) 9617 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9618 if (XC1 && XC1->isExactlyValue(-1.0)) 9619 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9620 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9621 } 9622 return SDValue(); 9623 }; 9624 9625 if (SDValue FMA = FuseFADD(N0, N1)) 9626 return FMA; 9627 if (SDValue FMA = FuseFADD(N1, N0)) 9628 return FMA; 9629 9630 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9631 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9632 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9633 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9634 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9635 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9636 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9637 if (XC0 && XC0->isExactlyValue(+1.0)) 9638 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9639 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9640 Y); 9641 if (XC0 && XC0->isExactlyValue(-1.0)) 9642 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9643 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9644 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9645 9646 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9647 if (XC1 && XC1->isExactlyValue(+1.0)) 9648 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9649 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9650 if (XC1 && XC1->isExactlyValue(-1.0)) 9651 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9652 } 9653 return SDValue(); 9654 }; 9655 9656 if (SDValue FMA = FuseFSUB(N0, N1)) 9657 return FMA; 9658 if (SDValue FMA = FuseFSUB(N1, N0)) 9659 return FMA; 9660 9661 return SDValue(); 9662 } 9663 9664 static bool isFMulNegTwo(SDValue &N) { 9665 if (N.getOpcode() != ISD::FMUL) 9666 return false; 9667 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9668 return CFP->isExactlyValue(-2.0); 9669 return false; 9670 } 9671 9672 SDValue DAGCombiner::visitFADD(SDNode *N) { 9673 SDValue N0 = N->getOperand(0); 9674 SDValue N1 = N->getOperand(1); 9675 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9676 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9677 EVT VT = N->getValueType(0); 9678 SDLoc DL(N); 9679 const TargetOptions &Options = DAG.getTarget().Options; 9680 const SDNodeFlags Flags = N->getFlags(); 9681 9682 // fold vector ops 9683 if (VT.isVector()) 9684 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9685 return FoldedVOp; 9686 9687 // fold (fadd c1, c2) -> c1 + c2 9688 if (N0CFP && N1CFP) 9689 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9690 9691 // canonicalize constant to RHS 9692 if (N0CFP && !N1CFP) 9693 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9694 9695 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9696 return NewSel; 9697 9698 // fold (fadd A, (fneg B)) -> (fsub A, B) 9699 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9700 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9701 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9702 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9703 9704 // fold (fadd (fneg A), B) -> (fsub B, A) 9705 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9706 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9707 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9708 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9709 9710 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9711 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9712 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9713 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9714 bool N1IsFMul = isFMulNegTwo(N1); 9715 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9716 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9717 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9718 } 9719 9720 // FIXME: Auto-upgrade the target/function-level option. 9721 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9722 // fold (fadd A, 0) -> A 9723 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9724 if (N1C->isZero()) 9725 return N0; 9726 } 9727 9728 // If 'unsafe math' is enabled, fold lots of things. 9729 if (Options.UnsafeFPMath) { 9730 // No FP constant should be created after legalization as Instruction 9731 // Selection pass has a hard time dealing with FP constants. 9732 bool AllowNewConst = (Level < AfterLegalizeDAG); 9733 9734 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9735 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9736 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9737 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9738 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9739 Flags), 9740 Flags); 9741 9742 // If allowed, fold (fadd (fneg x), x) -> 0.0 9743 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9744 return DAG.getConstantFP(0.0, DL, VT); 9745 9746 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9747 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9748 return DAG.getConstantFP(0.0, DL, VT); 9749 9750 // We can fold chains of FADD's of the same value into multiplications. 9751 // This transform is not safe in general because we are reducing the number 9752 // of rounding steps. 9753 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9754 if (N0.getOpcode() == ISD::FMUL) { 9755 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9756 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9757 9758 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9759 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9760 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9761 DAG.getConstantFP(1.0, DL, VT), Flags); 9762 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9763 } 9764 9765 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9766 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9767 N1.getOperand(0) == N1.getOperand(1) && 9768 N0.getOperand(0) == N1.getOperand(0)) { 9769 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9770 DAG.getConstantFP(2.0, DL, VT), Flags); 9771 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9772 } 9773 } 9774 9775 if (N1.getOpcode() == ISD::FMUL) { 9776 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9777 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9778 9779 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9780 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9781 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9782 DAG.getConstantFP(1.0, DL, VT), Flags); 9783 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9784 } 9785 9786 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9787 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9788 N0.getOperand(0) == N0.getOperand(1) && 9789 N1.getOperand(0) == N0.getOperand(0)) { 9790 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9791 DAG.getConstantFP(2.0, DL, VT), Flags); 9792 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9793 } 9794 } 9795 9796 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9797 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9798 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9799 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9800 (N0.getOperand(0) == N1)) { 9801 return DAG.getNode(ISD::FMUL, DL, VT, 9802 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9803 } 9804 } 9805 9806 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9807 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9808 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9809 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9810 N1.getOperand(0) == N0) { 9811 return DAG.getNode(ISD::FMUL, DL, VT, 9812 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9813 } 9814 } 9815 9816 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9817 if (AllowNewConst && 9818 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9819 N0.getOperand(0) == N0.getOperand(1) && 9820 N1.getOperand(0) == N1.getOperand(1) && 9821 N0.getOperand(0) == N1.getOperand(0)) { 9822 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9823 DAG.getConstantFP(4.0, DL, VT), Flags); 9824 } 9825 } 9826 } // enable-unsafe-fp-math 9827 9828 // FADD -> FMA combines: 9829 if (SDValue Fused = visitFADDForFMACombine(N)) { 9830 AddToWorklist(Fused.getNode()); 9831 return Fused; 9832 } 9833 return SDValue(); 9834 } 9835 9836 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9837 SDValue N0 = N->getOperand(0); 9838 SDValue N1 = N->getOperand(1); 9839 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9840 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9841 EVT VT = N->getValueType(0); 9842 SDLoc DL(N); 9843 const TargetOptions &Options = DAG.getTarget().Options; 9844 const SDNodeFlags Flags = N->getFlags(); 9845 9846 // fold vector ops 9847 if (VT.isVector()) 9848 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9849 return FoldedVOp; 9850 9851 // fold (fsub c1, c2) -> c1-c2 9852 if (N0CFP && N1CFP) 9853 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9854 9855 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9856 return NewSel; 9857 9858 // fold (fsub A, (fneg B)) -> (fadd A, B) 9859 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9860 return DAG.getNode(ISD::FADD, DL, VT, N0, 9861 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9862 9863 // FIXME: Auto-upgrade the target/function-level option. 9864 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9865 // (fsub 0, B) -> -B 9866 if (N0CFP && N0CFP->isZero()) { 9867 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9868 return GetNegatedExpression(N1, DAG, LegalOperations); 9869 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9870 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9871 } 9872 } 9873 9874 // If 'unsafe math' is enabled, fold lots of things. 9875 if (Options.UnsafeFPMath) { 9876 // (fsub A, 0) -> A 9877 if (N1CFP && N1CFP->isZero()) 9878 return N0; 9879 9880 // (fsub x, x) -> 0.0 9881 if (N0 == N1) 9882 return DAG.getConstantFP(0.0f, DL, VT); 9883 9884 // (fsub x, (fadd x, y)) -> (fneg y) 9885 // (fsub x, (fadd y, x)) -> (fneg y) 9886 if (N1.getOpcode() == ISD::FADD) { 9887 SDValue N10 = N1->getOperand(0); 9888 SDValue N11 = N1->getOperand(1); 9889 9890 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9891 return GetNegatedExpression(N11, DAG, LegalOperations); 9892 9893 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9894 return GetNegatedExpression(N10, DAG, LegalOperations); 9895 } 9896 } 9897 9898 // FSUB -> FMA combines: 9899 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9900 AddToWorklist(Fused.getNode()); 9901 return Fused; 9902 } 9903 9904 return SDValue(); 9905 } 9906 9907 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9908 SDValue N0 = N->getOperand(0); 9909 SDValue N1 = N->getOperand(1); 9910 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9911 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9912 EVT VT = N->getValueType(0); 9913 SDLoc DL(N); 9914 const TargetOptions &Options = DAG.getTarget().Options; 9915 const SDNodeFlags Flags = N->getFlags(); 9916 9917 // fold vector ops 9918 if (VT.isVector()) { 9919 // This just handles C1 * C2 for vectors. Other vector folds are below. 9920 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9921 return FoldedVOp; 9922 } 9923 9924 // fold (fmul c1, c2) -> c1*c2 9925 if (N0CFP && N1CFP) 9926 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9927 9928 // canonicalize constant to RHS 9929 if (isConstantFPBuildVectorOrConstantFP(N0) && 9930 !isConstantFPBuildVectorOrConstantFP(N1)) 9931 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9932 9933 // fold (fmul A, 1.0) -> A 9934 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9935 return N0; 9936 9937 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9938 return NewSel; 9939 9940 if (Options.UnsafeFPMath) { 9941 // fold (fmul A, 0) -> 0 9942 if (N1CFP && N1CFP->isZero()) 9943 return N1; 9944 9945 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9946 if (N0.getOpcode() == ISD::FMUL) { 9947 // Fold scalars or any vector constants (not just splats). 9948 // This fold is done in general by InstCombine, but extra fmul insts 9949 // may have been generated during lowering. 9950 SDValue N00 = N0.getOperand(0); 9951 SDValue N01 = N0.getOperand(1); 9952 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9953 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9954 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9955 9956 // Check 1: Make sure that the first operand of the inner multiply is NOT 9957 // a constant. Otherwise, we may induce infinite looping. 9958 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9959 // Check 2: Make sure that the second operand of the inner multiply and 9960 // the second operand of the outer multiply are constants. 9961 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9962 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9963 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9964 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9965 } 9966 } 9967 } 9968 9969 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9970 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9971 // during an early run of DAGCombiner can prevent folding with fmuls 9972 // inserted during lowering. 9973 if (N0.getOpcode() == ISD::FADD && 9974 (N0.getOperand(0) == N0.getOperand(1)) && 9975 N0.hasOneUse()) { 9976 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9977 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9978 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9979 } 9980 } 9981 9982 // fold (fmul X, 2.0) -> (fadd X, X) 9983 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9984 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9985 9986 // fold (fmul X, -1.0) -> (fneg X) 9987 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9988 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9989 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9990 9991 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9992 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9993 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9994 // Both can be negated for free, check to see if at least one is cheaper 9995 // negated. 9996 if (LHSNeg == 2 || RHSNeg == 2) 9997 return DAG.getNode(ISD::FMUL, DL, VT, 9998 GetNegatedExpression(N0, DAG, LegalOperations), 9999 GetNegatedExpression(N1, DAG, LegalOperations), 10000 Flags); 10001 } 10002 } 10003 10004 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 10005 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 10006 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 10007 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 10008 TLI.isOperationLegal(ISD::FABS, VT)) { 10009 SDValue Select = N0, X = N1; 10010 if (Select.getOpcode() != ISD::SELECT) 10011 std::swap(Select, X); 10012 10013 SDValue Cond = Select.getOperand(0); 10014 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 10015 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 10016 10017 if (TrueOpnd && FalseOpnd && 10018 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 10019 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 10020 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 10021 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10022 switch (CC) { 10023 default: break; 10024 case ISD::SETOLT: 10025 case ISD::SETULT: 10026 case ISD::SETOLE: 10027 case ISD::SETULE: 10028 case ISD::SETLT: 10029 case ISD::SETLE: 10030 std::swap(TrueOpnd, FalseOpnd); 10031 // Fall through 10032 case ISD::SETOGT: 10033 case ISD::SETUGT: 10034 case ISD::SETOGE: 10035 case ISD::SETUGE: 10036 case ISD::SETGT: 10037 case ISD::SETGE: 10038 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 10039 TLI.isOperationLegal(ISD::FNEG, VT)) 10040 return DAG.getNode(ISD::FNEG, DL, VT, 10041 DAG.getNode(ISD::FABS, DL, VT, X)); 10042 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 10043 return DAG.getNode(ISD::FABS, DL, VT, X); 10044 10045 break; 10046 } 10047 } 10048 } 10049 10050 // FMUL -> FMA combines: 10051 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 10052 AddToWorklist(Fused.getNode()); 10053 return Fused; 10054 } 10055 10056 return SDValue(); 10057 } 10058 10059 SDValue DAGCombiner::visitFMA(SDNode *N) { 10060 SDValue N0 = N->getOperand(0); 10061 SDValue N1 = N->getOperand(1); 10062 SDValue N2 = N->getOperand(2); 10063 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10064 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10065 EVT VT = N->getValueType(0); 10066 SDLoc DL(N); 10067 const TargetOptions &Options = DAG.getTarget().Options; 10068 10069 // Constant fold FMA. 10070 if (isa<ConstantFPSDNode>(N0) && 10071 isa<ConstantFPSDNode>(N1) && 10072 isa<ConstantFPSDNode>(N2)) { 10073 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 10074 } 10075 10076 if (Options.UnsafeFPMath) { 10077 if (N0CFP && N0CFP->isZero()) 10078 return N2; 10079 if (N1CFP && N1CFP->isZero()) 10080 return N2; 10081 } 10082 // TODO: The FMA node should have flags that propagate to these nodes. 10083 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10084 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 10085 if (N1CFP && N1CFP->isExactlyValue(1.0)) 10086 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 10087 10088 // Canonicalize (fma c, x, y) -> (fma x, c, y) 10089 if (isConstantFPBuildVectorOrConstantFP(N0) && 10090 !isConstantFPBuildVectorOrConstantFP(N1)) 10091 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 10092 10093 // TODO: FMA nodes should have flags that propagate to the created nodes. 10094 // For now, create a Flags object for use with all unsafe math transforms. 10095 SDNodeFlags Flags; 10096 Flags.setUnsafeAlgebra(true); 10097 10098 if (Options.UnsafeFPMath) { 10099 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 10100 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 10101 isConstantFPBuildVectorOrConstantFP(N1) && 10102 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 10103 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10104 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 10105 Flags), Flags); 10106 } 10107 10108 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 10109 if (N0.getOpcode() == ISD::FMUL && 10110 isConstantFPBuildVectorOrConstantFP(N1) && 10111 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 10112 return DAG.getNode(ISD::FMA, DL, VT, 10113 N0.getOperand(0), 10114 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 10115 Flags), 10116 N2); 10117 } 10118 } 10119 10120 // (fma x, 1, y) -> (fadd x, y) 10121 // (fma x, -1, y) -> (fadd (fneg x), y) 10122 if (N1CFP) { 10123 if (N1CFP->isExactlyValue(1.0)) 10124 // TODO: The FMA node should have flags that propagate to this node. 10125 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 10126 10127 if (N1CFP->isExactlyValue(-1.0) && 10128 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 10129 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 10130 AddToWorklist(RHSNeg.getNode()); 10131 // TODO: The FMA node should have flags that propagate to this node. 10132 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 10133 } 10134 10135 // fma (fneg x), K, y -> fma x -K, y 10136 if (N0.getOpcode() == ISD::FNEG && 10137 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 10138 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) { 10139 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 10140 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 10141 } 10142 } 10143 10144 if (Options.UnsafeFPMath) { 10145 // (fma x, c, x) -> (fmul x, (c+1)) 10146 if (N1CFP && N0 == N2) { 10147 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10148 DAG.getNode(ISD::FADD, DL, VT, N1, 10149 DAG.getConstantFP(1.0, DL, VT), Flags), 10150 Flags); 10151 } 10152 10153 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 10154 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 10155 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10156 DAG.getNode(ISD::FADD, DL, VT, N1, 10157 DAG.getConstantFP(-1.0, DL, VT), Flags), 10158 Flags); 10159 } 10160 } 10161 10162 return SDValue(); 10163 } 10164 10165 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10166 // reciprocal. 10167 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 10168 // Notice that this is not always beneficial. One reason is different targets 10169 // may have different costs for FDIV and FMUL, so sometimes the cost of two 10170 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 10171 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 10172 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 10173 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 10174 const SDNodeFlags Flags = N->getFlags(); 10175 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 10176 return SDValue(); 10177 10178 // Skip if current node is a reciprocal. 10179 SDValue N0 = N->getOperand(0); 10180 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10181 if (N0CFP && N0CFP->isExactlyValue(1.0)) 10182 return SDValue(); 10183 10184 // Exit early if the target does not want this transform or if there can't 10185 // possibly be enough uses of the divisor to make the transform worthwhile. 10186 SDValue N1 = N->getOperand(1); 10187 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 10188 if (!MinUses || N1->use_size() < MinUses) 10189 return SDValue(); 10190 10191 // Find all FDIV users of the same divisor. 10192 // Use a set because duplicates may be present in the user list. 10193 SetVector<SDNode *> Users; 10194 for (auto *U : N1->uses()) { 10195 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 10196 // This division is eligible for optimization only if global unsafe math 10197 // is enabled or if this division allows reciprocal formation. 10198 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 10199 Users.insert(U); 10200 } 10201 } 10202 10203 // Now that we have the actual number of divisor uses, make sure it meets 10204 // the minimum threshold specified by the target. 10205 if (Users.size() < MinUses) 10206 return SDValue(); 10207 10208 EVT VT = N->getValueType(0); 10209 SDLoc DL(N); 10210 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10211 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10212 10213 // Dividend / Divisor -> Dividend * Reciprocal 10214 for (auto *U : Users) { 10215 SDValue Dividend = U->getOperand(0); 10216 if (Dividend != FPOne) { 10217 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10218 Reciprocal, Flags); 10219 CombineTo(U, NewNode); 10220 } else if (U != Reciprocal.getNode()) { 10221 // In the absence of fast-math-flags, this user node is always the 10222 // same node as Reciprocal, but with FMF they may be different nodes. 10223 CombineTo(U, Reciprocal); 10224 } 10225 } 10226 return SDValue(N, 0); // N was replaced. 10227 } 10228 10229 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10230 SDValue N0 = N->getOperand(0); 10231 SDValue N1 = N->getOperand(1); 10232 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10233 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10234 EVT VT = N->getValueType(0); 10235 SDLoc DL(N); 10236 const TargetOptions &Options = DAG.getTarget().Options; 10237 SDNodeFlags Flags = N->getFlags(); 10238 10239 // fold vector ops 10240 if (VT.isVector()) 10241 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10242 return FoldedVOp; 10243 10244 // fold (fdiv c1, c2) -> c1/c2 10245 if (N0CFP && N1CFP) 10246 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10247 10248 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10249 return NewSel; 10250 10251 if (Options.UnsafeFPMath) { 10252 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10253 if (N1CFP) { 10254 // Compute the reciprocal 1.0 / c2. 10255 const APFloat &N1APF = N1CFP->getValueAPF(); 10256 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10257 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10258 // Only do the transform if the reciprocal is a legal fp immediate that 10259 // isn't too nasty (eg NaN, denormal, ...). 10260 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10261 (!LegalOperations || 10262 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10263 // backend)... we should handle this gracefully after Legalize. 10264 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 10265 TLI.isOperationLegal(ISD::ConstantFP, VT) || 10266 TLI.isFPImmLegal(Recip, VT))) 10267 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10268 DAG.getConstantFP(Recip, DL, VT), Flags); 10269 } 10270 10271 // If this FDIV is part of a reciprocal square root, it may be folded 10272 // into a target-specific square root estimate instruction. 10273 if (N1.getOpcode() == ISD::FSQRT) { 10274 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10275 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10276 } 10277 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10278 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10279 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10280 Flags)) { 10281 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10282 AddToWorklist(RV.getNode()); 10283 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10284 } 10285 } else if (N1.getOpcode() == ISD::FP_ROUND && 10286 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10287 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10288 Flags)) { 10289 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10290 AddToWorklist(RV.getNode()); 10291 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10292 } 10293 } else if (N1.getOpcode() == ISD::FMUL) { 10294 // Look through an FMUL. Even though this won't remove the FDIV directly, 10295 // it's still worthwhile to get rid of the FSQRT if possible. 10296 SDValue SqrtOp; 10297 SDValue OtherOp; 10298 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10299 SqrtOp = N1.getOperand(0); 10300 OtherOp = N1.getOperand(1); 10301 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10302 SqrtOp = N1.getOperand(1); 10303 OtherOp = N1.getOperand(0); 10304 } 10305 if (SqrtOp.getNode()) { 10306 // We found a FSQRT, so try to make this fold: 10307 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10308 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10309 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10310 AddToWorklist(RV.getNode()); 10311 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10312 } 10313 } 10314 } 10315 10316 // Fold into a reciprocal estimate and multiply instead of a real divide. 10317 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10318 AddToWorklist(RV.getNode()); 10319 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10320 } 10321 } 10322 10323 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10324 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10325 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10326 // Both can be negated for free, check to see if at least one is cheaper 10327 // negated. 10328 if (LHSNeg == 2 || RHSNeg == 2) 10329 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10330 GetNegatedExpression(N0, DAG, LegalOperations), 10331 GetNegatedExpression(N1, DAG, LegalOperations), 10332 Flags); 10333 } 10334 } 10335 10336 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10337 return CombineRepeatedDivisors; 10338 10339 return SDValue(); 10340 } 10341 10342 SDValue DAGCombiner::visitFREM(SDNode *N) { 10343 SDValue N0 = N->getOperand(0); 10344 SDValue N1 = N->getOperand(1); 10345 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10346 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10347 EVT VT = N->getValueType(0); 10348 10349 // fold (frem c1, c2) -> fmod(c1,c2) 10350 if (N0CFP && N1CFP) 10351 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10352 10353 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10354 return NewSel; 10355 10356 return SDValue(); 10357 } 10358 10359 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10360 if (!DAG.getTarget().Options.UnsafeFPMath) 10361 return SDValue(); 10362 10363 SDValue N0 = N->getOperand(0); 10364 if (TLI.isFsqrtCheap(N0, DAG)) 10365 return SDValue(); 10366 10367 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10368 // For now, create a Flags object for use with all unsafe math transforms. 10369 SDNodeFlags Flags; 10370 Flags.setUnsafeAlgebra(true); 10371 return buildSqrtEstimate(N0, Flags); 10372 } 10373 10374 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10375 /// copysign(x, fp_round(y)) -> copysign(x, y) 10376 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10377 SDValue N1 = N->getOperand(1); 10378 if ((N1.getOpcode() == ISD::FP_EXTEND || 10379 N1.getOpcode() == ISD::FP_ROUND)) { 10380 // Do not optimize out type conversion of f128 type yet. 10381 // For some targets like x86_64, configuration is changed to keep one f128 10382 // value in one SSE register, but instruction selection cannot handle 10383 // FCOPYSIGN on SSE registers yet. 10384 EVT N1VT = N1->getValueType(0); 10385 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 10386 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10387 } 10388 return false; 10389 } 10390 10391 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10392 SDValue N0 = N->getOperand(0); 10393 SDValue N1 = N->getOperand(1); 10394 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10395 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10396 EVT VT = N->getValueType(0); 10397 10398 if (N0CFP && N1CFP) // Constant fold 10399 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10400 10401 if (N1CFP) { 10402 const APFloat &V = N1CFP->getValueAPF(); 10403 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10404 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10405 if (!V.isNegative()) { 10406 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10407 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10408 } else { 10409 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10410 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10411 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10412 } 10413 } 10414 10415 // copysign(fabs(x), y) -> copysign(x, y) 10416 // copysign(fneg(x), y) -> copysign(x, y) 10417 // copysign(copysign(x,z), y) -> copysign(x, y) 10418 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10419 N0.getOpcode() == ISD::FCOPYSIGN) 10420 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10421 10422 // copysign(x, abs(y)) -> abs(x) 10423 if (N1.getOpcode() == ISD::FABS) 10424 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10425 10426 // copysign(x, copysign(y,z)) -> copysign(x, z) 10427 if (N1.getOpcode() == ISD::FCOPYSIGN) 10428 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10429 10430 // copysign(x, fp_extend(y)) -> copysign(x, y) 10431 // copysign(x, fp_round(y)) -> copysign(x, y) 10432 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10433 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10434 10435 return SDValue(); 10436 } 10437 10438 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10439 SDValue N0 = N->getOperand(0); 10440 EVT VT = N->getValueType(0); 10441 EVT OpVT = N0.getValueType(); 10442 10443 // fold (sint_to_fp c1) -> c1fp 10444 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10445 // ...but only if the target supports immediate floating-point values 10446 (!LegalOperations || 10447 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10448 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10449 10450 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10451 // but UINT_TO_FP is legal on this target, try to convert. 10452 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10453 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10454 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10455 if (DAG.SignBitIsZero(N0)) 10456 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10457 } 10458 10459 // The next optimizations are desirable only if SELECT_CC can be lowered. 10460 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10461 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10462 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10463 !VT.isVector() && 10464 (!LegalOperations || 10465 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10466 SDLoc DL(N); 10467 SDValue Ops[] = 10468 { N0.getOperand(0), N0.getOperand(1), 10469 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10470 N0.getOperand(2) }; 10471 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10472 } 10473 10474 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10475 // (select_cc x, y, 1.0, 0.0,, cc) 10476 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10477 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10478 (!LegalOperations || 10479 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10480 SDLoc DL(N); 10481 SDValue Ops[] = 10482 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10483 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10484 N0.getOperand(0).getOperand(2) }; 10485 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10486 } 10487 } 10488 10489 return SDValue(); 10490 } 10491 10492 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10493 SDValue N0 = N->getOperand(0); 10494 EVT VT = N->getValueType(0); 10495 EVT OpVT = N0.getValueType(); 10496 10497 // fold (uint_to_fp c1) -> c1fp 10498 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10499 // ...but only if the target supports immediate floating-point values 10500 (!LegalOperations || 10501 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 10502 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10503 10504 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10505 // but SINT_TO_FP is legal on this target, try to convert. 10506 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10507 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10508 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10509 if (DAG.SignBitIsZero(N0)) 10510 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10511 } 10512 10513 // The next optimizations are desirable only if SELECT_CC can be lowered. 10514 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10515 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10516 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10517 (!LegalOperations || 10518 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 10519 SDLoc DL(N); 10520 SDValue Ops[] = 10521 { N0.getOperand(0), N0.getOperand(1), 10522 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10523 N0.getOperand(2) }; 10524 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10525 } 10526 } 10527 10528 return SDValue(); 10529 } 10530 10531 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10532 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10533 SDValue N0 = N->getOperand(0); 10534 EVT VT = N->getValueType(0); 10535 10536 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10537 return SDValue(); 10538 10539 SDValue Src = N0.getOperand(0); 10540 EVT SrcVT = Src.getValueType(); 10541 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10542 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10543 10544 // We can safely assume the conversion won't overflow the output range, 10545 // because (for example) (uint8_t)18293.f is undefined behavior. 10546 10547 // Since we can assume the conversion won't overflow, our decision as to 10548 // whether the input will fit in the float should depend on the minimum 10549 // of the input range and output range. 10550 10551 // This means this is also safe for a signed input and unsigned output, since 10552 // a negative input would lead to undefined behavior. 10553 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10554 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10555 unsigned ActualSize = std::min(InputSize, OutputSize); 10556 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10557 10558 // We can only fold away the float conversion if the input range can be 10559 // represented exactly in the float range. 10560 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10561 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10562 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10563 : ISD::ZERO_EXTEND; 10564 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10565 } 10566 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10567 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10568 return DAG.getBitcast(VT, Src); 10569 } 10570 return SDValue(); 10571 } 10572 10573 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10574 SDValue N0 = N->getOperand(0); 10575 EVT VT = N->getValueType(0); 10576 10577 // fold (fp_to_sint c1fp) -> c1 10578 if (isConstantFPBuildVectorOrConstantFP(N0)) 10579 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10580 10581 return FoldIntToFPToInt(N, DAG); 10582 } 10583 10584 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10585 SDValue N0 = N->getOperand(0); 10586 EVT VT = N->getValueType(0); 10587 10588 // fold (fp_to_uint c1fp) -> c1 10589 if (isConstantFPBuildVectorOrConstantFP(N0)) 10590 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10591 10592 return FoldIntToFPToInt(N, DAG); 10593 } 10594 10595 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10596 SDValue N0 = N->getOperand(0); 10597 SDValue N1 = N->getOperand(1); 10598 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10599 EVT VT = N->getValueType(0); 10600 10601 // fold (fp_round c1fp) -> c1fp 10602 if (N0CFP) 10603 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10604 10605 // fold (fp_round (fp_extend x)) -> x 10606 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10607 return N0.getOperand(0); 10608 10609 // fold (fp_round (fp_round x)) -> (fp_round x) 10610 if (N0.getOpcode() == ISD::FP_ROUND) { 10611 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10612 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10613 10614 // Skip this folding if it results in an fp_round from f80 to f16. 10615 // 10616 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10617 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10618 // instructions from f32 or f64. Moreover, the first (value-preserving) 10619 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10620 // x86. 10621 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10622 return SDValue(); 10623 10624 // If the first fp_round isn't a value preserving truncation, it might 10625 // introduce a tie in the second fp_round, that wouldn't occur in the 10626 // single-step fp_round we want to fold to. 10627 // In other words, double rounding isn't the same as rounding. 10628 // Also, this is a value preserving truncation iff both fp_round's are. 10629 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10630 SDLoc DL(N); 10631 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10632 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10633 } 10634 } 10635 10636 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10637 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10638 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10639 N0.getOperand(0), N1); 10640 AddToWorklist(Tmp.getNode()); 10641 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10642 Tmp, N0.getOperand(1)); 10643 } 10644 10645 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10646 return NewVSel; 10647 10648 return SDValue(); 10649 } 10650 10651 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10652 SDValue N0 = N->getOperand(0); 10653 EVT VT = N->getValueType(0); 10654 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10655 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10656 10657 // fold (fp_round_inreg c1fp) -> c1fp 10658 if (N0CFP && isTypeLegal(EVT)) { 10659 SDLoc DL(N); 10660 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10661 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10662 } 10663 10664 return SDValue(); 10665 } 10666 10667 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10668 SDValue N0 = N->getOperand(0); 10669 EVT VT = N->getValueType(0); 10670 10671 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10672 if (N->hasOneUse() && 10673 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10674 return SDValue(); 10675 10676 // fold (fp_extend c1fp) -> c1fp 10677 if (isConstantFPBuildVectorOrConstantFP(N0)) 10678 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10679 10680 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10681 if (N0.getOpcode() == ISD::FP16_TO_FP && 10682 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10683 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10684 10685 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10686 // value of X. 10687 if (N0.getOpcode() == ISD::FP_ROUND 10688 && N0.getConstantOperandVal(1) == 1) { 10689 SDValue In = N0.getOperand(0); 10690 if (In.getValueType() == VT) return In; 10691 if (VT.bitsLT(In.getValueType())) 10692 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10693 In, N0.getOperand(1)); 10694 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10695 } 10696 10697 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10698 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10699 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10700 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10701 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10702 LN0->getChain(), 10703 LN0->getBasePtr(), N0.getValueType(), 10704 LN0->getMemOperand()); 10705 CombineTo(N, ExtLoad); 10706 CombineTo(N0.getNode(), 10707 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10708 N0.getValueType(), ExtLoad, 10709 DAG.getIntPtrConstant(1, SDLoc(N0))), 10710 ExtLoad.getValue(1)); 10711 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10712 } 10713 10714 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10715 return NewVSel; 10716 10717 return SDValue(); 10718 } 10719 10720 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10721 SDValue N0 = N->getOperand(0); 10722 EVT VT = N->getValueType(0); 10723 10724 // fold (fceil c1) -> fceil(c1) 10725 if (isConstantFPBuildVectorOrConstantFP(N0)) 10726 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10727 10728 return SDValue(); 10729 } 10730 10731 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10732 SDValue N0 = N->getOperand(0); 10733 EVT VT = N->getValueType(0); 10734 10735 // fold (ftrunc c1) -> ftrunc(c1) 10736 if (isConstantFPBuildVectorOrConstantFP(N0)) 10737 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10738 10739 // fold ftrunc (known rounded int x) -> x 10740 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 10741 // likely to be generated to extract integer from a rounded floating value. 10742 switch (N0.getOpcode()) { 10743 default: break; 10744 case ISD::FRINT: 10745 case ISD::FTRUNC: 10746 case ISD::FNEARBYINT: 10747 case ISD::FFLOOR: 10748 case ISD::FCEIL: 10749 return N0; 10750 } 10751 10752 return SDValue(); 10753 } 10754 10755 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10756 SDValue N0 = N->getOperand(0); 10757 EVT VT = N->getValueType(0); 10758 10759 // fold (ffloor c1) -> ffloor(c1) 10760 if (isConstantFPBuildVectorOrConstantFP(N0)) 10761 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10762 10763 return SDValue(); 10764 } 10765 10766 // FIXME: FNEG and FABS have a lot in common; refactor. 10767 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10768 SDValue N0 = N->getOperand(0); 10769 EVT VT = N->getValueType(0); 10770 10771 // Constant fold FNEG. 10772 if (isConstantFPBuildVectorOrConstantFP(N0)) 10773 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10774 10775 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10776 &DAG.getTarget().Options)) 10777 return GetNegatedExpression(N0, DAG, LegalOperations); 10778 10779 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10780 // constant pool values. 10781 if (!TLI.isFNegFree(VT) && 10782 N0.getOpcode() == ISD::BITCAST && 10783 N0.getNode()->hasOneUse()) { 10784 SDValue Int = N0.getOperand(0); 10785 EVT IntVT = Int.getValueType(); 10786 if (IntVT.isInteger() && !IntVT.isVector()) { 10787 APInt SignMask; 10788 if (N0.getValueType().isVector()) { 10789 // For a vector, get a mask such as 0x80... per scalar element 10790 // and splat it. 10791 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10792 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10793 } else { 10794 // For a scalar, just generate 0x80... 10795 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10796 } 10797 SDLoc DL0(N0); 10798 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10799 DAG.getConstant(SignMask, DL0, IntVT)); 10800 AddToWorklist(Int.getNode()); 10801 return DAG.getBitcast(VT, Int); 10802 } 10803 } 10804 10805 // (fneg (fmul c, x)) -> (fmul -c, x) 10806 if (N0.getOpcode() == ISD::FMUL && 10807 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10808 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10809 if (CFP1) { 10810 APFloat CVal = CFP1->getValueAPF(); 10811 CVal.changeSign(); 10812 if (Level >= AfterLegalizeDAG && 10813 (TLI.isFPImmLegal(CVal, VT) || 10814 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10815 return DAG.getNode( 10816 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10817 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10818 N0->getFlags()); 10819 } 10820 } 10821 10822 return SDValue(); 10823 } 10824 10825 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10826 SDValue N0 = N->getOperand(0); 10827 SDValue N1 = N->getOperand(1); 10828 EVT VT = N->getValueType(0); 10829 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10830 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10831 10832 if (N0CFP && N1CFP) { 10833 const APFloat &C0 = N0CFP->getValueAPF(); 10834 const APFloat &C1 = N1CFP->getValueAPF(); 10835 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10836 } 10837 10838 // Canonicalize to constant on RHS. 10839 if (isConstantFPBuildVectorOrConstantFP(N0) && 10840 !isConstantFPBuildVectorOrConstantFP(N1)) 10841 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10842 10843 return SDValue(); 10844 } 10845 10846 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10847 SDValue N0 = N->getOperand(0); 10848 SDValue N1 = N->getOperand(1); 10849 EVT VT = N->getValueType(0); 10850 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10851 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10852 10853 if (N0CFP && N1CFP) { 10854 const APFloat &C0 = N0CFP->getValueAPF(); 10855 const APFloat &C1 = N1CFP->getValueAPF(); 10856 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10857 } 10858 10859 // Canonicalize to constant on RHS. 10860 if (isConstantFPBuildVectorOrConstantFP(N0) && 10861 !isConstantFPBuildVectorOrConstantFP(N1)) 10862 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10863 10864 return SDValue(); 10865 } 10866 10867 SDValue DAGCombiner::visitFABS(SDNode *N) { 10868 SDValue N0 = N->getOperand(0); 10869 EVT VT = N->getValueType(0); 10870 10871 // fold (fabs c1) -> fabs(c1) 10872 if (isConstantFPBuildVectorOrConstantFP(N0)) 10873 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10874 10875 // fold (fabs (fabs x)) -> (fabs x) 10876 if (N0.getOpcode() == ISD::FABS) 10877 return N->getOperand(0); 10878 10879 // fold (fabs (fneg x)) -> (fabs x) 10880 // fold (fabs (fcopysign x, y)) -> (fabs x) 10881 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10882 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10883 10884 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10885 // constant pool values. 10886 if (!TLI.isFAbsFree(VT) && 10887 N0.getOpcode() == ISD::BITCAST && 10888 N0.getNode()->hasOneUse()) { 10889 SDValue Int = N0.getOperand(0); 10890 EVT IntVT = Int.getValueType(); 10891 if (IntVT.isInteger() && !IntVT.isVector()) { 10892 APInt SignMask; 10893 if (N0.getValueType().isVector()) { 10894 // For a vector, get a mask such as 0x7f... per scalar element 10895 // and splat it. 10896 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 10897 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10898 } else { 10899 // For a scalar, just generate 0x7f... 10900 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 10901 } 10902 SDLoc DL(N0); 10903 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10904 DAG.getConstant(SignMask, DL, IntVT)); 10905 AddToWorklist(Int.getNode()); 10906 return DAG.getBitcast(N->getValueType(0), Int); 10907 } 10908 } 10909 10910 return SDValue(); 10911 } 10912 10913 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10914 SDValue Chain = N->getOperand(0); 10915 SDValue N1 = N->getOperand(1); 10916 SDValue N2 = N->getOperand(2); 10917 10918 // If N is a constant we could fold this into a fallthrough or unconditional 10919 // branch. However that doesn't happen very often in normal code, because 10920 // Instcombine/SimplifyCFG should have handled the available opportunities. 10921 // If we did this folding here, it would be necessary to update the 10922 // MachineBasicBlock CFG, which is awkward. 10923 10924 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10925 // on the target. 10926 if (N1.getOpcode() == ISD::SETCC && 10927 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10928 N1.getOperand(0).getValueType())) { 10929 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10930 Chain, N1.getOperand(2), 10931 N1.getOperand(0), N1.getOperand(1), N2); 10932 } 10933 10934 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10935 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10936 (N1.getOperand(0).hasOneUse() && 10937 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10938 SDNode *Trunc = nullptr; 10939 if (N1.getOpcode() == ISD::TRUNCATE) { 10940 // Look pass the truncate. 10941 Trunc = N1.getNode(); 10942 N1 = N1.getOperand(0); 10943 } 10944 10945 // Match this pattern so that we can generate simpler code: 10946 // 10947 // %a = ... 10948 // %b = and i32 %a, 2 10949 // %c = srl i32 %b, 1 10950 // brcond i32 %c ... 10951 // 10952 // into 10953 // 10954 // %a = ... 10955 // %b = and i32 %a, 2 10956 // %c = setcc eq %b, 0 10957 // brcond %c ... 10958 // 10959 // This applies only when the AND constant value has one bit set and the 10960 // SRL constant is equal to the log2 of the AND constant. The back-end is 10961 // smart enough to convert the result into a TEST/JMP sequence. 10962 SDValue Op0 = N1.getOperand(0); 10963 SDValue Op1 = N1.getOperand(1); 10964 10965 if (Op0.getOpcode() == ISD::AND && 10966 Op1.getOpcode() == ISD::Constant) { 10967 SDValue AndOp1 = Op0.getOperand(1); 10968 10969 if (AndOp1.getOpcode() == ISD::Constant) { 10970 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10971 10972 if (AndConst.isPowerOf2() && 10973 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10974 SDLoc DL(N); 10975 SDValue SetCC = 10976 DAG.getSetCC(DL, 10977 getSetCCResultType(Op0.getValueType()), 10978 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10979 ISD::SETNE); 10980 10981 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10982 MVT::Other, Chain, SetCC, N2); 10983 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10984 // will convert it back to (X & C1) >> C2. 10985 CombineTo(N, NewBRCond, false); 10986 // Truncate is dead. 10987 if (Trunc) 10988 deleteAndRecombine(Trunc); 10989 // Replace the uses of SRL with SETCC 10990 WorklistRemover DeadNodes(*this); 10991 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10992 deleteAndRecombine(N1.getNode()); 10993 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10994 } 10995 } 10996 } 10997 10998 if (Trunc) 10999 // Restore N1 if the above transformation doesn't match. 11000 N1 = N->getOperand(1); 11001 } 11002 11003 // Transform br(xor(x, y)) -> br(x != y) 11004 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 11005 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 11006 SDNode *TheXor = N1.getNode(); 11007 SDValue Op0 = TheXor->getOperand(0); 11008 SDValue Op1 = TheXor->getOperand(1); 11009 if (Op0.getOpcode() == Op1.getOpcode()) { 11010 // Avoid missing important xor optimizations. 11011 if (SDValue Tmp = visitXOR(TheXor)) { 11012 if (Tmp.getNode() != TheXor) { 11013 DEBUG(dbgs() << "\nReplacing.8 "; 11014 TheXor->dump(&DAG); 11015 dbgs() << "\nWith: "; 11016 Tmp.getNode()->dump(&DAG); 11017 dbgs() << '\n'); 11018 WorklistRemover DeadNodes(*this); 11019 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 11020 deleteAndRecombine(TheXor); 11021 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11022 MVT::Other, Chain, Tmp, N2); 11023 } 11024 11025 // visitXOR has changed XOR's operands or replaced the XOR completely, 11026 // bail out. 11027 return SDValue(N, 0); 11028 } 11029 } 11030 11031 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 11032 bool Equal = false; 11033 if (isOneConstant(Op0) && Op0.hasOneUse() && 11034 Op0.getOpcode() == ISD::XOR) { 11035 TheXor = Op0.getNode(); 11036 Equal = true; 11037 } 11038 11039 EVT SetCCVT = N1.getValueType(); 11040 if (LegalTypes) 11041 SetCCVT = getSetCCResultType(SetCCVT); 11042 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 11043 SetCCVT, 11044 Op0, Op1, 11045 Equal ? ISD::SETEQ : ISD::SETNE); 11046 // Replace the uses of XOR with SETCC 11047 WorklistRemover DeadNodes(*this); 11048 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 11049 deleteAndRecombine(N1.getNode()); 11050 return DAG.getNode(ISD::BRCOND, SDLoc(N), 11051 MVT::Other, Chain, SetCC, N2); 11052 } 11053 } 11054 11055 return SDValue(); 11056 } 11057 11058 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 11059 // 11060 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 11061 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 11062 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 11063 11064 // If N is a constant we could fold this into a fallthrough or unconditional 11065 // branch. However that doesn't happen very often in normal code, because 11066 // Instcombine/SimplifyCFG should have handled the available opportunities. 11067 // If we did this folding here, it would be necessary to update the 11068 // MachineBasicBlock CFG, which is awkward. 11069 11070 // Use SimplifySetCC to simplify SETCC's. 11071 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 11072 CondLHS, CondRHS, CC->get(), SDLoc(N), 11073 false); 11074 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 11075 11076 // fold to a simpler setcc 11077 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 11078 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 11079 N->getOperand(0), Simp.getOperand(2), 11080 Simp.getOperand(0), Simp.getOperand(1), 11081 N->getOperand(4)); 11082 11083 return SDValue(); 11084 } 11085 11086 /// Return true if 'Use' is a load or a store that uses N as its base pointer 11087 /// and that N may be folded in the load / store addressing mode. 11088 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 11089 SelectionDAG &DAG, 11090 const TargetLowering &TLI) { 11091 EVT VT; 11092 unsigned AS; 11093 11094 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 11095 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 11096 return false; 11097 VT = LD->getMemoryVT(); 11098 AS = LD->getAddressSpace(); 11099 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 11100 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 11101 return false; 11102 VT = ST->getMemoryVT(); 11103 AS = ST->getAddressSpace(); 11104 } else 11105 return false; 11106 11107 TargetLowering::AddrMode AM; 11108 if (N->getOpcode() == ISD::ADD) { 11109 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11110 if (Offset) 11111 // [reg +/- imm] 11112 AM.BaseOffs = Offset->getSExtValue(); 11113 else 11114 // [reg +/- reg] 11115 AM.Scale = 1; 11116 } else if (N->getOpcode() == ISD::SUB) { 11117 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11118 if (Offset) 11119 // [reg +/- imm] 11120 AM.BaseOffs = -Offset->getSExtValue(); 11121 else 11122 // [reg +/- reg] 11123 AM.Scale = 1; 11124 } else 11125 return false; 11126 11127 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 11128 VT.getTypeForEVT(*DAG.getContext()), AS); 11129 } 11130 11131 /// Try turning a load/store into a pre-indexed load/store when the base 11132 /// pointer is an add or subtract and it has other uses besides the load/store. 11133 /// After the transformation, the new indexed load/store has effectively folded 11134 /// the add/subtract in and all of its other uses are redirected to the 11135 /// new load/store. 11136 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 11137 if (Level < AfterLegalizeDAG) 11138 return false; 11139 11140 bool isLoad = true; 11141 SDValue Ptr; 11142 EVT VT; 11143 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11144 if (LD->isIndexed()) 11145 return false; 11146 VT = LD->getMemoryVT(); 11147 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 11148 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 11149 return false; 11150 Ptr = LD->getBasePtr(); 11151 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11152 if (ST->isIndexed()) 11153 return false; 11154 VT = ST->getMemoryVT(); 11155 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 11156 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 11157 return false; 11158 Ptr = ST->getBasePtr(); 11159 isLoad = false; 11160 } else { 11161 return false; 11162 } 11163 11164 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 11165 // out. There is no reason to make this a preinc/predec. 11166 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 11167 Ptr.getNode()->hasOneUse()) 11168 return false; 11169 11170 // Ask the target to do addressing mode selection. 11171 SDValue BasePtr; 11172 SDValue Offset; 11173 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11174 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 11175 return false; 11176 11177 // Backends without true r+i pre-indexed forms may need to pass a 11178 // constant base with a variable offset so that constant coercion 11179 // will work with the patterns in canonical form. 11180 bool Swapped = false; 11181 if (isa<ConstantSDNode>(BasePtr)) { 11182 std::swap(BasePtr, Offset); 11183 Swapped = true; 11184 } 11185 11186 // Don't create a indexed load / store with zero offset. 11187 if (isNullConstant(Offset)) 11188 return false; 11189 11190 // Try turning it into a pre-indexed load / store except when: 11191 // 1) The new base ptr is a frame index. 11192 // 2) If N is a store and the new base ptr is either the same as or is a 11193 // predecessor of the value being stored. 11194 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 11195 // that would create a cycle. 11196 // 4) All uses are load / store ops that use it as old base ptr. 11197 11198 // Check #1. Preinc'ing a frame index would require copying the stack pointer 11199 // (plus the implicit offset) to a register to preinc anyway. 11200 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11201 return false; 11202 11203 // Check #2. 11204 if (!isLoad) { 11205 SDValue Val = cast<StoreSDNode>(N)->getValue(); 11206 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 11207 return false; 11208 } 11209 11210 // Caches for hasPredecessorHelper. 11211 SmallPtrSet<const SDNode *, 32> Visited; 11212 SmallVector<const SDNode *, 16> Worklist; 11213 Worklist.push_back(N); 11214 11215 // If the offset is a constant, there may be other adds of constants that 11216 // can be folded with this one. We should do this to avoid having to keep 11217 // a copy of the original base pointer. 11218 SmallVector<SDNode *, 16> OtherUses; 11219 if (isa<ConstantSDNode>(Offset)) 11220 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11221 UE = BasePtr.getNode()->use_end(); 11222 UI != UE; ++UI) { 11223 SDUse &Use = UI.getUse(); 11224 // Skip the use that is Ptr and uses of other results from BasePtr's 11225 // node (important for nodes that return multiple results). 11226 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11227 continue; 11228 11229 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11230 continue; 11231 11232 if (Use.getUser()->getOpcode() != ISD::ADD && 11233 Use.getUser()->getOpcode() != ISD::SUB) { 11234 OtherUses.clear(); 11235 break; 11236 } 11237 11238 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11239 if (!isa<ConstantSDNode>(Op1)) { 11240 OtherUses.clear(); 11241 break; 11242 } 11243 11244 // FIXME: In some cases, we can be smarter about this. 11245 if (Op1.getValueType() != Offset.getValueType()) { 11246 OtherUses.clear(); 11247 break; 11248 } 11249 11250 OtherUses.push_back(Use.getUser()); 11251 } 11252 11253 if (Swapped) 11254 std::swap(BasePtr, Offset); 11255 11256 // Now check for #3 and #4. 11257 bool RealUse = false; 11258 11259 for (SDNode *Use : Ptr.getNode()->uses()) { 11260 if (Use == N) 11261 continue; 11262 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11263 return false; 11264 11265 // If Ptr may be folded in addressing mode of other use, then it's 11266 // not profitable to do this transformation. 11267 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11268 RealUse = true; 11269 } 11270 11271 if (!RealUse) 11272 return false; 11273 11274 SDValue Result; 11275 if (isLoad) 11276 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11277 BasePtr, Offset, AM); 11278 else 11279 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11280 BasePtr, Offset, AM); 11281 ++PreIndexedNodes; 11282 ++NodesCombined; 11283 DEBUG(dbgs() << "\nReplacing.4 "; 11284 N->dump(&DAG); 11285 dbgs() << "\nWith: "; 11286 Result.getNode()->dump(&DAG); 11287 dbgs() << '\n'); 11288 WorklistRemover DeadNodes(*this); 11289 if (isLoad) { 11290 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11291 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11292 } else { 11293 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11294 } 11295 11296 // Finally, since the node is now dead, remove it from the graph. 11297 deleteAndRecombine(N); 11298 11299 if (Swapped) 11300 std::swap(BasePtr, Offset); 11301 11302 // Replace other uses of BasePtr that can be updated to use Ptr 11303 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11304 unsigned OffsetIdx = 1; 11305 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11306 OffsetIdx = 0; 11307 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11308 BasePtr.getNode() && "Expected BasePtr operand"); 11309 11310 // We need to replace ptr0 in the following expression: 11311 // x0 * offset0 + y0 * ptr0 = t0 11312 // knowing that 11313 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11314 // 11315 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11316 // indexed load/store and the expression that needs to be re-written. 11317 // 11318 // Therefore, we have: 11319 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11320 11321 ConstantSDNode *CN = 11322 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11323 int X0, X1, Y0, Y1; 11324 const APInt &Offset0 = CN->getAPIntValue(); 11325 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11326 11327 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11328 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11329 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11330 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11331 11332 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11333 11334 APInt CNV = Offset0; 11335 if (X0 < 0) CNV = -CNV; 11336 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11337 else CNV = CNV - Offset1; 11338 11339 SDLoc DL(OtherUses[i]); 11340 11341 // We can now generate the new expression. 11342 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11343 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11344 11345 SDValue NewUse = DAG.getNode(Opcode, 11346 DL, 11347 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11348 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11349 deleteAndRecombine(OtherUses[i]); 11350 } 11351 11352 // Replace the uses of Ptr with uses of the updated base value. 11353 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11354 deleteAndRecombine(Ptr.getNode()); 11355 11356 return true; 11357 } 11358 11359 /// Try to combine a load/store with a add/sub of the base pointer node into a 11360 /// post-indexed load/store. The transformation folded the add/subtract into the 11361 /// new indexed load/store effectively and all of its uses are redirected to the 11362 /// new load/store. 11363 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11364 if (Level < AfterLegalizeDAG) 11365 return false; 11366 11367 bool isLoad = true; 11368 SDValue Ptr; 11369 EVT VT; 11370 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11371 if (LD->isIndexed()) 11372 return false; 11373 VT = LD->getMemoryVT(); 11374 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11375 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11376 return false; 11377 Ptr = LD->getBasePtr(); 11378 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11379 if (ST->isIndexed()) 11380 return false; 11381 VT = ST->getMemoryVT(); 11382 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11383 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11384 return false; 11385 Ptr = ST->getBasePtr(); 11386 isLoad = false; 11387 } else { 11388 return false; 11389 } 11390 11391 if (Ptr.getNode()->hasOneUse()) 11392 return false; 11393 11394 for (SDNode *Op : Ptr.getNode()->uses()) { 11395 if (Op == N || 11396 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11397 continue; 11398 11399 SDValue BasePtr; 11400 SDValue Offset; 11401 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11402 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11403 // Don't create a indexed load / store with zero offset. 11404 if (isNullConstant(Offset)) 11405 continue; 11406 11407 // Try turning it into a post-indexed load / store except when 11408 // 1) All uses are load / store ops that use it as base ptr (and 11409 // it may be folded as addressing mmode). 11410 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11411 // nor a successor of N. Otherwise, if Op is folded that would 11412 // create a cycle. 11413 11414 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11415 continue; 11416 11417 // Check for #1. 11418 bool TryNext = false; 11419 for (SDNode *Use : BasePtr.getNode()->uses()) { 11420 if (Use == Ptr.getNode()) 11421 continue; 11422 11423 // If all the uses are load / store addresses, then don't do the 11424 // transformation. 11425 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11426 bool RealUse = false; 11427 for (SDNode *UseUse : Use->uses()) { 11428 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11429 RealUse = true; 11430 } 11431 11432 if (!RealUse) { 11433 TryNext = true; 11434 break; 11435 } 11436 } 11437 } 11438 11439 if (TryNext) 11440 continue; 11441 11442 // Check for #2 11443 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11444 SDValue Result = isLoad 11445 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11446 BasePtr, Offset, AM) 11447 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11448 BasePtr, Offset, AM); 11449 ++PostIndexedNodes; 11450 ++NodesCombined; 11451 DEBUG(dbgs() << "\nReplacing.5 "; 11452 N->dump(&DAG); 11453 dbgs() << "\nWith: "; 11454 Result.getNode()->dump(&DAG); 11455 dbgs() << '\n'); 11456 WorklistRemover DeadNodes(*this); 11457 if (isLoad) { 11458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11460 } else { 11461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11462 } 11463 11464 // Finally, since the node is now dead, remove it from the graph. 11465 deleteAndRecombine(N); 11466 11467 // Replace the uses of Use with uses of the updated base value. 11468 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11469 Result.getValue(isLoad ? 1 : 0)); 11470 deleteAndRecombine(Op); 11471 return true; 11472 } 11473 } 11474 } 11475 11476 return false; 11477 } 11478 11479 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11480 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11481 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11482 assert(AM != ISD::UNINDEXED); 11483 SDValue BP = LD->getOperand(1); 11484 SDValue Inc = LD->getOperand(2); 11485 11486 // Some backends use TargetConstants for load offsets, but don't expect 11487 // TargetConstants in general ADD nodes. We can convert these constants into 11488 // regular Constants (if the constant is not opaque). 11489 assert((Inc.getOpcode() != ISD::TargetConstant || 11490 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11491 "Cannot split out indexing using opaque target constants"); 11492 if (Inc.getOpcode() == ISD::TargetConstant) { 11493 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11494 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11495 ConstInc->getValueType(0)); 11496 } 11497 11498 unsigned Opc = 11499 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11500 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11501 } 11502 11503 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11504 LoadSDNode *LD = cast<LoadSDNode>(N); 11505 SDValue Chain = LD->getChain(); 11506 SDValue Ptr = LD->getBasePtr(); 11507 11508 // If load is not volatile and there are no uses of the loaded value (and 11509 // the updated indexed value in case of indexed loads), change uses of the 11510 // chain value into uses of the chain input (i.e. delete the dead load). 11511 if (!LD->isVolatile()) { 11512 if (N->getValueType(1) == MVT::Other) { 11513 // Unindexed loads. 11514 if (!N->hasAnyUseOfValue(0)) { 11515 // It's not safe to use the two value CombineTo variant here. e.g. 11516 // v1, chain2 = load chain1, loc 11517 // v2, chain3 = load chain2, loc 11518 // v3 = add v2, c 11519 // Now we replace use of chain2 with chain1. This makes the second load 11520 // isomorphic to the one we are deleting, and thus makes this load live. 11521 DEBUG(dbgs() << "\nReplacing.6 "; 11522 N->dump(&DAG); 11523 dbgs() << "\nWith chain: "; 11524 Chain.getNode()->dump(&DAG); 11525 dbgs() << "\n"); 11526 WorklistRemover DeadNodes(*this); 11527 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11528 AddUsersToWorklist(Chain.getNode()); 11529 if (N->use_empty()) 11530 deleteAndRecombine(N); 11531 11532 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11533 } 11534 } else { 11535 // Indexed loads. 11536 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11537 11538 // If this load has an opaque TargetConstant offset, then we cannot split 11539 // the indexing into an add/sub directly (that TargetConstant may not be 11540 // valid for a different type of node, and we cannot convert an opaque 11541 // target constant into a regular constant). 11542 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11543 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11544 11545 if (!N->hasAnyUseOfValue(0) && 11546 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11547 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11548 SDValue Index; 11549 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11550 Index = SplitIndexingFromLoad(LD); 11551 // Try to fold the base pointer arithmetic into subsequent loads and 11552 // stores. 11553 AddUsersToWorklist(N); 11554 } else 11555 Index = DAG.getUNDEF(N->getValueType(1)); 11556 DEBUG(dbgs() << "\nReplacing.7 "; 11557 N->dump(&DAG); 11558 dbgs() << "\nWith: "; 11559 Undef.getNode()->dump(&DAG); 11560 dbgs() << " and 2 other values\n"); 11561 WorklistRemover DeadNodes(*this); 11562 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11564 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11565 deleteAndRecombine(N); 11566 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11567 } 11568 } 11569 } 11570 11571 // If this load is directly stored, replace the load value with the stored 11572 // value. 11573 // TODO: Handle store large -> read small portion. 11574 // TODO: Handle TRUNCSTORE/LOADEXT 11575 if (OptLevel != CodeGenOpt::None && 11576 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11577 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11578 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11579 if (PrevST->getBasePtr() == Ptr && 11580 PrevST->getValue().getValueType() == N->getValueType(0)) 11581 return CombineTo(N, PrevST->getOperand(1), Chain); 11582 } 11583 } 11584 11585 // Try to infer better alignment information than the load already has. 11586 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11587 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11588 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11589 SDValue NewLoad = DAG.getExtLoad( 11590 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11591 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11592 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11593 if (NewLoad.getNode() != N) 11594 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11595 } 11596 } 11597 } 11598 11599 if (LD->isUnindexed()) { 11600 // Walk up chain skipping non-aliasing memory nodes. 11601 SDValue BetterChain = FindBetterChain(N, Chain); 11602 11603 // If there is a better chain. 11604 if (Chain != BetterChain) { 11605 SDValue ReplLoad; 11606 11607 // Replace the chain to void dependency. 11608 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11609 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11610 BetterChain, Ptr, LD->getMemOperand()); 11611 } else { 11612 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11613 LD->getValueType(0), 11614 BetterChain, Ptr, LD->getMemoryVT(), 11615 LD->getMemOperand()); 11616 } 11617 11618 // Create token factor to keep old chain connected. 11619 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11620 MVT::Other, Chain, ReplLoad.getValue(1)); 11621 11622 // Replace uses with load result and token factor 11623 return CombineTo(N, ReplLoad.getValue(0), Token); 11624 } 11625 } 11626 11627 // Try transforming N to an indexed load. 11628 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11629 return SDValue(N, 0); 11630 11631 // Try to slice up N to more direct loads if the slices are mapped to 11632 // different register banks or pairing can take place. 11633 if (SliceUpLoad(N)) 11634 return SDValue(N, 0); 11635 11636 return SDValue(); 11637 } 11638 11639 namespace { 11640 11641 /// \brief Helper structure used to slice a load in smaller loads. 11642 /// Basically a slice is obtained from the following sequence: 11643 /// Origin = load Ty1, Base 11644 /// Shift = srl Ty1 Origin, CstTy Amount 11645 /// Inst = trunc Shift to Ty2 11646 /// 11647 /// Then, it will be rewritten into: 11648 /// Slice = load SliceTy, Base + SliceOffset 11649 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11650 /// 11651 /// SliceTy is deduced from the number of bits that are actually used to 11652 /// build Inst. 11653 struct LoadedSlice { 11654 /// \brief Helper structure used to compute the cost of a slice. 11655 struct Cost { 11656 /// Are we optimizing for code size. 11657 bool ForCodeSize; 11658 11659 /// Various cost. 11660 unsigned Loads = 0; 11661 unsigned Truncates = 0; 11662 unsigned CrossRegisterBanksCopies = 0; 11663 unsigned ZExts = 0; 11664 unsigned Shift = 0; 11665 11666 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 11667 11668 /// \brief Get the cost of one isolated slice. 11669 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11670 : ForCodeSize(ForCodeSize), Loads(1) { 11671 EVT TruncType = LS.Inst->getValueType(0); 11672 EVT LoadedType = LS.getLoadedType(); 11673 if (TruncType != LoadedType && 11674 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11675 ZExts = 1; 11676 } 11677 11678 /// \brief Account for slicing gain in the current cost. 11679 /// Slicing provide a few gains like removing a shift or a 11680 /// truncate. This method allows to grow the cost of the original 11681 /// load with the gain from this slice. 11682 void addSliceGain(const LoadedSlice &LS) { 11683 // Each slice saves a truncate. 11684 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11685 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11686 LS.Inst->getValueType(0))) 11687 ++Truncates; 11688 // If there is a shift amount, this slice gets rid of it. 11689 if (LS.Shift) 11690 ++Shift; 11691 // If this slice can merge a cross register bank copy, account for it. 11692 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11693 ++CrossRegisterBanksCopies; 11694 } 11695 11696 Cost &operator+=(const Cost &RHS) { 11697 Loads += RHS.Loads; 11698 Truncates += RHS.Truncates; 11699 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11700 ZExts += RHS.ZExts; 11701 Shift += RHS.Shift; 11702 return *this; 11703 } 11704 11705 bool operator==(const Cost &RHS) const { 11706 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11707 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11708 ZExts == RHS.ZExts && Shift == RHS.Shift; 11709 } 11710 11711 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11712 11713 bool operator<(const Cost &RHS) const { 11714 // Assume cross register banks copies are as expensive as loads. 11715 // FIXME: Do we want some more target hooks? 11716 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11717 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11718 // Unless we are optimizing for code size, consider the 11719 // expensive operation first. 11720 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11721 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11722 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11723 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11724 } 11725 11726 bool operator>(const Cost &RHS) const { return RHS < *this; } 11727 11728 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11729 11730 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11731 }; 11732 11733 // The last instruction that represent the slice. This should be a 11734 // truncate instruction. 11735 SDNode *Inst; 11736 11737 // The original load instruction. 11738 LoadSDNode *Origin; 11739 11740 // The right shift amount in bits from the original load. 11741 unsigned Shift; 11742 11743 // The DAG from which Origin came from. 11744 // This is used to get some contextual information about legal types, etc. 11745 SelectionDAG *DAG; 11746 11747 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11748 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11749 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11750 11751 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11752 /// \return Result is \p BitWidth and has used bits set to 1 and 11753 /// not used bits set to 0. 11754 APInt getUsedBits() const { 11755 // Reproduce the trunc(lshr) sequence: 11756 // - Start from the truncated value. 11757 // - Zero extend to the desired bit width. 11758 // - Shift left. 11759 assert(Origin && "No original load to compare against."); 11760 unsigned BitWidth = Origin->getValueSizeInBits(0); 11761 assert(Inst && "This slice is not bound to an instruction"); 11762 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11763 "Extracted slice is bigger than the whole type!"); 11764 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11765 UsedBits.setAllBits(); 11766 UsedBits = UsedBits.zext(BitWidth); 11767 UsedBits <<= Shift; 11768 return UsedBits; 11769 } 11770 11771 /// \brief Get the size of the slice to be loaded in bytes. 11772 unsigned getLoadedSize() const { 11773 unsigned SliceSize = getUsedBits().countPopulation(); 11774 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11775 return SliceSize / 8; 11776 } 11777 11778 /// \brief Get the type that will be loaded for this slice. 11779 /// Note: This may not be the final type for the slice. 11780 EVT getLoadedType() const { 11781 assert(DAG && "Missing context"); 11782 LLVMContext &Ctxt = *DAG->getContext(); 11783 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11784 } 11785 11786 /// \brief Get the alignment of the load used for this slice. 11787 unsigned getAlignment() const { 11788 unsigned Alignment = Origin->getAlignment(); 11789 unsigned Offset = getOffsetFromBase(); 11790 if (Offset != 0) 11791 Alignment = MinAlign(Alignment, Alignment + Offset); 11792 return Alignment; 11793 } 11794 11795 /// \brief Check if this slice can be rewritten with legal operations. 11796 bool isLegal() const { 11797 // An invalid slice is not legal. 11798 if (!Origin || !Inst || !DAG) 11799 return false; 11800 11801 // Offsets are for indexed load only, we do not handle that. 11802 if (!Origin->getOffset().isUndef()) 11803 return false; 11804 11805 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11806 11807 // Check that the type is legal. 11808 EVT SliceType = getLoadedType(); 11809 if (!TLI.isTypeLegal(SliceType)) 11810 return false; 11811 11812 // Check that the load is legal for this type. 11813 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11814 return false; 11815 11816 // Check that the offset can be computed. 11817 // 1. Check its type. 11818 EVT PtrType = Origin->getBasePtr().getValueType(); 11819 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11820 return false; 11821 11822 // 2. Check that it fits in the immediate. 11823 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11824 return false; 11825 11826 // 3. Check that the computation is legal. 11827 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11828 return false; 11829 11830 // Check that the zext is legal if it needs one. 11831 EVT TruncateType = Inst->getValueType(0); 11832 if (TruncateType != SliceType && 11833 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11834 return false; 11835 11836 return true; 11837 } 11838 11839 /// \brief Get the offset in bytes of this slice in the original chunk of 11840 /// bits. 11841 /// \pre DAG != nullptr. 11842 uint64_t getOffsetFromBase() const { 11843 assert(DAG && "Missing context."); 11844 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11845 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11846 uint64_t Offset = Shift / 8; 11847 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11848 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11849 "The size of the original loaded type is not a multiple of a" 11850 " byte."); 11851 // If Offset is bigger than TySizeInBytes, it means we are loading all 11852 // zeros. This should have been optimized before in the process. 11853 assert(TySizeInBytes > Offset && 11854 "Invalid shift amount for given loaded size"); 11855 if (IsBigEndian) 11856 Offset = TySizeInBytes - Offset - getLoadedSize(); 11857 return Offset; 11858 } 11859 11860 /// \brief Generate the sequence of instructions to load the slice 11861 /// represented by this object and redirect the uses of this slice to 11862 /// this new sequence of instructions. 11863 /// \pre this->Inst && this->Origin are valid Instructions and this 11864 /// object passed the legal check: LoadedSlice::isLegal returned true. 11865 /// \return The last instruction of the sequence used to load the slice. 11866 SDValue loadSlice() const { 11867 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11868 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11869 SDValue BaseAddr = OldBaseAddr; 11870 // Get the offset in that chunk of bytes w.r.t. the endianness. 11871 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11872 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11873 if (Offset) { 11874 // BaseAddr = BaseAddr + Offset. 11875 EVT ArithType = BaseAddr.getValueType(); 11876 SDLoc DL(Origin); 11877 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11878 DAG->getConstant(Offset, DL, ArithType)); 11879 } 11880 11881 // Create the type of the loaded slice according to its size. 11882 EVT SliceType = getLoadedType(); 11883 11884 // Create the load for the slice. 11885 SDValue LastInst = 11886 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11887 Origin->getPointerInfo().getWithOffset(Offset), 11888 getAlignment(), Origin->getMemOperand()->getFlags()); 11889 // If the final type is not the same as the loaded type, this means that 11890 // we have to pad with zero. Create a zero extend for that. 11891 EVT FinalType = Inst->getValueType(0); 11892 if (SliceType != FinalType) 11893 LastInst = 11894 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11895 return LastInst; 11896 } 11897 11898 /// \brief Check if this slice can be merged with an expensive cross register 11899 /// bank copy. E.g., 11900 /// i = load i32 11901 /// f = bitcast i32 i to float 11902 bool canMergeExpensiveCrossRegisterBankCopy() const { 11903 if (!Inst || !Inst->hasOneUse()) 11904 return false; 11905 SDNode *Use = *Inst->use_begin(); 11906 if (Use->getOpcode() != ISD::BITCAST) 11907 return false; 11908 assert(DAG && "Missing context"); 11909 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11910 EVT ResVT = Use->getValueType(0); 11911 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11912 const TargetRegisterClass *ArgRC = 11913 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11914 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11915 return false; 11916 11917 // At this point, we know that we perform a cross-register-bank copy. 11918 // Check if it is expensive. 11919 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11920 // Assume bitcasts are cheap, unless both register classes do not 11921 // explicitly share a common sub class. 11922 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11923 return false; 11924 11925 // Check if it will be merged with the load. 11926 // 1. Check the alignment constraint. 11927 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11928 ResVT.getTypeForEVT(*DAG->getContext())); 11929 11930 if (RequiredAlignment > getAlignment()) 11931 return false; 11932 11933 // 2. Check that the load is a legal operation for that type. 11934 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11935 return false; 11936 11937 // 3. Check that we do not have a zext in the way. 11938 if (Inst->getValueType(0) != getLoadedType()) 11939 return false; 11940 11941 return true; 11942 } 11943 }; 11944 11945 } // end anonymous namespace 11946 11947 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11948 /// \p UsedBits looks like 0..0 1..1 0..0. 11949 static bool areUsedBitsDense(const APInt &UsedBits) { 11950 // If all the bits are one, this is dense! 11951 if (UsedBits.isAllOnesValue()) 11952 return true; 11953 11954 // Get rid of the unused bits on the right. 11955 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11956 // Get rid of the unused bits on the left. 11957 if (NarrowedUsedBits.countLeadingZeros()) 11958 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11959 // Check that the chunk of bits is completely used. 11960 return NarrowedUsedBits.isAllOnesValue(); 11961 } 11962 11963 /// \brief Check whether or not \p First and \p Second are next to each other 11964 /// in memory. This means that there is no hole between the bits loaded 11965 /// by \p First and the bits loaded by \p Second. 11966 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11967 const LoadedSlice &Second) { 11968 assert(First.Origin == Second.Origin && First.Origin && 11969 "Unable to match different memory origins."); 11970 APInt UsedBits = First.getUsedBits(); 11971 assert((UsedBits & Second.getUsedBits()) == 0 && 11972 "Slices are not supposed to overlap."); 11973 UsedBits |= Second.getUsedBits(); 11974 return areUsedBitsDense(UsedBits); 11975 } 11976 11977 /// \brief Adjust the \p GlobalLSCost according to the target 11978 /// paring capabilities and the layout of the slices. 11979 /// \pre \p GlobalLSCost should account for at least as many loads as 11980 /// there is in the slices in \p LoadedSlices. 11981 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11982 LoadedSlice::Cost &GlobalLSCost) { 11983 unsigned NumberOfSlices = LoadedSlices.size(); 11984 // If there is less than 2 elements, no pairing is possible. 11985 if (NumberOfSlices < 2) 11986 return; 11987 11988 // Sort the slices so that elements that are likely to be next to each 11989 // other in memory are next to each other in the list. 11990 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11991 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11992 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11993 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11994 }); 11995 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11996 // First (resp. Second) is the first (resp. Second) potentially candidate 11997 // to be placed in a paired load. 11998 const LoadedSlice *First = nullptr; 11999 const LoadedSlice *Second = nullptr; 12000 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 12001 // Set the beginning of the pair. 12002 First = Second) { 12003 Second = &LoadedSlices[CurrSlice]; 12004 12005 // If First is NULL, it means we start a new pair. 12006 // Get to the next slice. 12007 if (!First) 12008 continue; 12009 12010 EVT LoadedType = First->getLoadedType(); 12011 12012 // If the types of the slices are different, we cannot pair them. 12013 if (LoadedType != Second->getLoadedType()) 12014 continue; 12015 12016 // Check if the target supplies paired loads for this type. 12017 unsigned RequiredAlignment = 0; 12018 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 12019 // move to the next pair, this type is hopeless. 12020 Second = nullptr; 12021 continue; 12022 } 12023 // Check if we meet the alignment requirement. 12024 if (RequiredAlignment > First->getAlignment()) 12025 continue; 12026 12027 // Check that both loads are next to each other in memory. 12028 if (!areSlicesNextToEachOther(*First, *Second)) 12029 continue; 12030 12031 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 12032 --GlobalLSCost.Loads; 12033 // Move to the next pair. 12034 Second = nullptr; 12035 } 12036 } 12037 12038 /// \brief Check the profitability of all involved LoadedSlice. 12039 /// Currently, it is considered profitable if there is exactly two 12040 /// involved slices (1) which are (2) next to each other in memory, and 12041 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 12042 /// 12043 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 12044 /// the elements themselves. 12045 /// 12046 /// FIXME: When the cost model will be mature enough, we can relax 12047 /// constraints (1) and (2). 12048 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 12049 const APInt &UsedBits, bool ForCodeSize) { 12050 unsigned NumberOfSlices = LoadedSlices.size(); 12051 if (StressLoadSlicing) 12052 return NumberOfSlices > 1; 12053 12054 // Check (1). 12055 if (NumberOfSlices != 2) 12056 return false; 12057 12058 // Check (2). 12059 if (!areUsedBitsDense(UsedBits)) 12060 return false; 12061 12062 // Check (3). 12063 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 12064 // The original code has one big load. 12065 OrigCost.Loads = 1; 12066 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 12067 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 12068 // Accumulate the cost of all the slices. 12069 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 12070 GlobalSlicingCost += SliceCost; 12071 12072 // Account as cost in the original configuration the gain obtained 12073 // with the current slices. 12074 OrigCost.addSliceGain(LS); 12075 } 12076 12077 // If the target supports paired load, adjust the cost accordingly. 12078 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 12079 return OrigCost > GlobalSlicingCost; 12080 } 12081 12082 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 12083 /// operations, split it in the various pieces being extracted. 12084 /// 12085 /// This sort of thing is introduced by SROA. 12086 /// This slicing takes care not to insert overlapping loads. 12087 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 12088 bool DAGCombiner::SliceUpLoad(SDNode *N) { 12089 if (Level < AfterLegalizeDAG) 12090 return false; 12091 12092 LoadSDNode *LD = cast<LoadSDNode>(N); 12093 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 12094 !LD->getValueType(0).isInteger()) 12095 return false; 12096 12097 // Keep track of already used bits to detect overlapping values. 12098 // In that case, we will just abort the transformation. 12099 APInt UsedBits(LD->getValueSizeInBits(0), 0); 12100 12101 SmallVector<LoadedSlice, 4> LoadedSlices; 12102 12103 // Check if this load is used as several smaller chunks of bits. 12104 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 12105 // of computation for each trunc. 12106 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 12107 UI != UIEnd; ++UI) { 12108 // Skip the uses of the chain. 12109 if (UI.getUse().getResNo() != 0) 12110 continue; 12111 12112 SDNode *User = *UI; 12113 unsigned Shift = 0; 12114 12115 // Check if this is a trunc(lshr). 12116 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 12117 isa<ConstantSDNode>(User->getOperand(1))) { 12118 Shift = User->getConstantOperandVal(1); 12119 User = *User->use_begin(); 12120 } 12121 12122 // At this point, User is a Truncate, iff we encountered, trunc or 12123 // trunc(lshr). 12124 if (User->getOpcode() != ISD::TRUNCATE) 12125 return false; 12126 12127 // The width of the type must be a power of 2 and greater than 8-bits. 12128 // Otherwise the load cannot be represented in LLVM IR. 12129 // Moreover, if we shifted with a non-8-bits multiple, the slice 12130 // will be across several bytes. We do not support that. 12131 unsigned Width = User->getValueSizeInBits(0); 12132 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 12133 return false; 12134 12135 // Build the slice for this chain of computations. 12136 LoadedSlice LS(User, LD, Shift, &DAG); 12137 APInt CurrentUsedBits = LS.getUsedBits(); 12138 12139 // Check if this slice overlaps with another. 12140 if ((CurrentUsedBits & UsedBits) != 0) 12141 return false; 12142 // Update the bits used globally. 12143 UsedBits |= CurrentUsedBits; 12144 12145 // Check if the new slice would be legal. 12146 if (!LS.isLegal()) 12147 return false; 12148 12149 // Record the slice. 12150 LoadedSlices.push_back(LS); 12151 } 12152 12153 // Abort slicing if it does not seem to be profitable. 12154 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 12155 return false; 12156 12157 ++SlicedLoads; 12158 12159 // Rewrite each chain to use an independent load. 12160 // By construction, each chain can be represented by a unique load. 12161 12162 // Prepare the argument for the new token factor for all the slices. 12163 SmallVector<SDValue, 8> ArgChains; 12164 for (SmallVectorImpl<LoadedSlice>::const_iterator 12165 LSIt = LoadedSlices.begin(), 12166 LSItEnd = LoadedSlices.end(); 12167 LSIt != LSItEnd; ++LSIt) { 12168 SDValue SliceInst = LSIt->loadSlice(); 12169 CombineTo(LSIt->Inst, SliceInst, true); 12170 if (SliceInst.getOpcode() != ISD::LOAD) 12171 SliceInst = SliceInst.getOperand(0); 12172 assert(SliceInst->getOpcode() == ISD::LOAD && 12173 "It takes more than a zext to get to the loaded slice!!"); 12174 ArgChains.push_back(SliceInst.getValue(1)); 12175 } 12176 12177 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 12178 ArgChains); 12179 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 12180 AddToWorklist(Chain.getNode()); 12181 return true; 12182 } 12183 12184 /// Check to see if V is (and load (ptr), imm), where the load is having 12185 /// specific bytes cleared out. If so, return the byte size being masked out 12186 /// and the shift amount. 12187 static std::pair<unsigned, unsigned> 12188 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 12189 std::pair<unsigned, unsigned> Result(0, 0); 12190 12191 // Check for the structure we're looking for. 12192 if (V->getOpcode() != ISD::AND || 12193 !isa<ConstantSDNode>(V->getOperand(1)) || 12194 !ISD::isNormalLoad(V->getOperand(0).getNode())) 12195 return Result; 12196 12197 // Check the chain and pointer. 12198 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 12199 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 12200 12201 // The store should be chained directly to the load or be an operand of a 12202 // tokenfactor. 12203 if (LD == Chain.getNode()) 12204 ; // ok. 12205 else if (Chain->getOpcode() != ISD::TokenFactor) 12206 return Result; // Fail. 12207 else { 12208 bool isOk = false; 12209 for (const SDValue &ChainOp : Chain->op_values()) 12210 if (ChainOp.getNode() == LD) { 12211 isOk = true; 12212 break; 12213 } 12214 if (!isOk) return Result; 12215 } 12216 12217 // This only handles simple types. 12218 if (V.getValueType() != MVT::i16 && 12219 V.getValueType() != MVT::i32 && 12220 V.getValueType() != MVT::i64) 12221 return Result; 12222 12223 // Check the constant mask. Invert it so that the bits being masked out are 12224 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12225 // follow the sign bit for uniformity. 12226 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12227 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12228 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12229 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12230 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12231 if (NotMaskLZ == 64) return Result; // All zero mask. 12232 12233 // See if we have a continuous run of bits. If so, we have 0*1+0* 12234 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12235 return Result; 12236 12237 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12238 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12239 NotMaskLZ -= 64-V.getValueSizeInBits(); 12240 12241 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12242 switch (MaskedBytes) { 12243 case 1: 12244 case 2: 12245 case 4: break; 12246 default: return Result; // All one mask, or 5-byte mask. 12247 } 12248 12249 // Verify that the first bit starts at a multiple of mask so that the access 12250 // is aligned the same as the access width. 12251 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12252 12253 Result.first = MaskedBytes; 12254 Result.second = NotMaskTZ/8; 12255 return Result; 12256 } 12257 12258 /// Check to see if IVal is something that provides a value as specified by 12259 /// MaskInfo. If so, replace the specified store with a narrower store of 12260 /// truncated IVal. 12261 static SDNode * 12262 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12263 SDValue IVal, StoreSDNode *St, 12264 DAGCombiner *DC) { 12265 unsigned NumBytes = MaskInfo.first; 12266 unsigned ByteShift = MaskInfo.second; 12267 SelectionDAG &DAG = DC->getDAG(); 12268 12269 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12270 // that uses this. If not, this is not a replacement. 12271 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12272 ByteShift*8, (ByteShift+NumBytes)*8); 12273 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12274 12275 // Check that it is legal on the target to do this. It is legal if the new 12276 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12277 // legalization. 12278 MVT VT = MVT::getIntegerVT(NumBytes*8); 12279 if (!DC->isTypeLegal(VT)) 12280 return nullptr; 12281 12282 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12283 // shifted by ByteShift and truncated down to NumBytes. 12284 if (ByteShift) { 12285 SDLoc DL(IVal); 12286 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12287 DAG.getConstant(ByteShift*8, DL, 12288 DC->getShiftAmountTy(IVal.getValueType()))); 12289 } 12290 12291 // Figure out the offset for the store and the alignment of the access. 12292 unsigned StOffset; 12293 unsigned NewAlign = St->getAlignment(); 12294 12295 if (DAG.getDataLayout().isLittleEndian()) 12296 StOffset = ByteShift; 12297 else 12298 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12299 12300 SDValue Ptr = St->getBasePtr(); 12301 if (StOffset) { 12302 SDLoc DL(IVal); 12303 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12304 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12305 NewAlign = MinAlign(NewAlign, StOffset); 12306 } 12307 12308 // Truncate down to the new size. 12309 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12310 12311 ++OpsNarrowed; 12312 return DAG 12313 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12314 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12315 .getNode(); 12316 } 12317 12318 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12319 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12320 /// narrowing the load and store if it would end up being a win for performance 12321 /// or code size. 12322 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12323 StoreSDNode *ST = cast<StoreSDNode>(N); 12324 if (ST->isVolatile()) 12325 return SDValue(); 12326 12327 SDValue Chain = ST->getChain(); 12328 SDValue Value = ST->getValue(); 12329 SDValue Ptr = ST->getBasePtr(); 12330 EVT VT = Value.getValueType(); 12331 12332 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12333 return SDValue(); 12334 12335 unsigned Opc = Value.getOpcode(); 12336 12337 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12338 // is a byte mask indicating a consecutive number of bytes, check to see if 12339 // Y is known to provide just those bytes. If so, we try to replace the 12340 // load + replace + store sequence with a single (narrower) store, which makes 12341 // the load dead. 12342 if (Opc == ISD::OR) { 12343 std::pair<unsigned, unsigned> MaskedLoad; 12344 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12345 if (MaskedLoad.first) 12346 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12347 Value.getOperand(1), ST,this)) 12348 return SDValue(NewST, 0); 12349 12350 // Or is commutative, so try swapping X and Y. 12351 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12352 if (MaskedLoad.first) 12353 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12354 Value.getOperand(0), ST,this)) 12355 return SDValue(NewST, 0); 12356 } 12357 12358 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12359 Value.getOperand(1).getOpcode() != ISD::Constant) 12360 return SDValue(); 12361 12362 SDValue N0 = Value.getOperand(0); 12363 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12364 Chain == SDValue(N0.getNode(), 1)) { 12365 LoadSDNode *LD = cast<LoadSDNode>(N0); 12366 if (LD->getBasePtr() != Ptr || 12367 LD->getPointerInfo().getAddrSpace() != 12368 ST->getPointerInfo().getAddrSpace()) 12369 return SDValue(); 12370 12371 // Find the type to narrow it the load / op / store to. 12372 SDValue N1 = Value.getOperand(1); 12373 unsigned BitWidth = N1.getValueSizeInBits(); 12374 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12375 if (Opc == ISD::AND) 12376 Imm ^= APInt::getAllOnesValue(BitWidth); 12377 if (Imm == 0 || Imm.isAllOnesValue()) 12378 return SDValue(); 12379 unsigned ShAmt = Imm.countTrailingZeros(); 12380 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12381 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12383 // The narrowing should be profitable, the load/store operation should be 12384 // legal (or custom) and the store size should be equal to the NewVT width. 12385 while (NewBW < BitWidth && 12386 (NewVT.getStoreSizeInBits() != NewBW || 12387 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12388 !TLI.isNarrowingProfitable(VT, NewVT))) { 12389 NewBW = NextPowerOf2(NewBW); 12390 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12391 } 12392 if (NewBW >= BitWidth) 12393 return SDValue(); 12394 12395 // If the lsb changed does not start at the type bitwidth boundary, 12396 // start at the previous one. 12397 if (ShAmt % NewBW) 12398 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12399 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12400 std::min(BitWidth, ShAmt + NewBW)); 12401 if ((Imm & Mask) == Imm) { 12402 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12403 if (Opc == ISD::AND) 12404 NewImm ^= APInt::getAllOnesValue(NewBW); 12405 uint64_t PtrOff = ShAmt / 8; 12406 // For big endian targets, we need to adjust the offset to the pointer to 12407 // load the correct bytes. 12408 if (DAG.getDataLayout().isBigEndian()) 12409 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12410 12411 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12412 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12413 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12414 return SDValue(); 12415 12416 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12417 Ptr.getValueType(), Ptr, 12418 DAG.getConstant(PtrOff, SDLoc(LD), 12419 Ptr.getValueType())); 12420 SDValue NewLD = 12421 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12422 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12423 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12424 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12425 DAG.getConstant(NewImm, SDLoc(Value), 12426 NewVT)); 12427 SDValue NewST = 12428 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12429 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12430 12431 AddToWorklist(NewPtr.getNode()); 12432 AddToWorklist(NewLD.getNode()); 12433 AddToWorklist(NewVal.getNode()); 12434 WorklistRemover DeadNodes(*this); 12435 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12436 ++OpsNarrowed; 12437 return NewST; 12438 } 12439 } 12440 12441 return SDValue(); 12442 } 12443 12444 /// For a given floating point load / store pair, if the load value isn't used 12445 /// by any other operations, then consider transforming the pair to integer 12446 /// load / store operations if the target deems the transformation profitable. 12447 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12448 StoreSDNode *ST = cast<StoreSDNode>(N); 12449 SDValue Chain = ST->getChain(); 12450 SDValue Value = ST->getValue(); 12451 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12452 Value.hasOneUse() && 12453 Chain == SDValue(Value.getNode(), 1)) { 12454 LoadSDNode *LD = cast<LoadSDNode>(Value); 12455 EVT VT = LD->getMemoryVT(); 12456 if (!VT.isFloatingPoint() || 12457 VT != ST->getMemoryVT() || 12458 LD->isNonTemporal() || 12459 ST->isNonTemporal() || 12460 LD->getPointerInfo().getAddrSpace() != 0 || 12461 ST->getPointerInfo().getAddrSpace() != 0) 12462 return SDValue(); 12463 12464 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12465 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12466 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12467 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12468 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12469 return SDValue(); 12470 12471 unsigned LDAlign = LD->getAlignment(); 12472 unsigned STAlign = ST->getAlignment(); 12473 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12474 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12475 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12476 return SDValue(); 12477 12478 SDValue NewLD = 12479 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12480 LD->getPointerInfo(), LDAlign); 12481 12482 SDValue NewST = 12483 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12484 ST->getPointerInfo(), STAlign); 12485 12486 AddToWorklist(NewLD.getNode()); 12487 AddToWorklist(NewST.getNode()); 12488 WorklistRemover DeadNodes(*this); 12489 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12490 ++LdStFP2Int; 12491 return NewST; 12492 } 12493 12494 return SDValue(); 12495 } 12496 12497 // This is a helper function for visitMUL to check the profitability 12498 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12499 // MulNode is the original multiply, AddNode is (add x, c1), 12500 // and ConstNode is c2. 12501 // 12502 // If the (add x, c1) has multiple uses, we could increase 12503 // the number of adds if we make this transformation. 12504 // It would only be worth doing this if we can remove a 12505 // multiply in the process. Check for that here. 12506 // To illustrate: 12507 // (A + c1) * c3 12508 // (A + c2) * c3 12509 // We're checking for cases where we have common "c3 * A" expressions. 12510 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12511 SDValue &AddNode, 12512 SDValue &ConstNode) { 12513 APInt Val; 12514 12515 // If the add only has one use, this would be OK to do. 12516 if (AddNode.getNode()->hasOneUse()) 12517 return true; 12518 12519 // Walk all the users of the constant with which we're multiplying. 12520 for (SDNode *Use : ConstNode->uses()) { 12521 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12522 continue; 12523 12524 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12525 SDNode *OtherOp; 12526 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12527 12528 // OtherOp is what we're multiplying against the constant. 12529 if (Use->getOperand(0) == ConstNode) 12530 OtherOp = Use->getOperand(1).getNode(); 12531 else 12532 OtherOp = Use->getOperand(0).getNode(); 12533 12534 // Check to see if multiply is with the same operand of our "add". 12535 // 12536 // ConstNode = CONST 12537 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12538 // ... 12539 // AddNode = (A + c1) <-- MulVar is A. 12540 // = AddNode * ConstNode <-- current visiting instruction. 12541 // 12542 // If we make this transformation, we will have a common 12543 // multiply (ConstNode * A) that we can save. 12544 if (OtherOp == MulVar) 12545 return true; 12546 12547 // Now check to see if a future expansion will give us a common 12548 // multiply. 12549 // 12550 // ConstNode = CONST 12551 // AddNode = (A + c1) 12552 // ... = AddNode * ConstNode <-- current visiting instruction. 12553 // ... 12554 // OtherOp = (A + c2) 12555 // Use = OtherOp * ConstNode <-- visiting Use. 12556 // 12557 // If we make this transformation, we will have a common 12558 // multiply (CONST * A) after we also do the same transformation 12559 // to the "t2" instruction. 12560 if (OtherOp->getOpcode() == ISD::ADD && 12561 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12562 OtherOp->getOperand(0).getNode() == MulVar) 12563 return true; 12564 } 12565 } 12566 12567 // Didn't find a case where this would be profitable. 12568 return false; 12569 } 12570 12571 static SDValue peekThroughBitcast(SDValue V) { 12572 while (V.getOpcode() == ISD::BITCAST) 12573 V = V.getOperand(0); 12574 return V; 12575 } 12576 12577 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12578 unsigned NumStores) { 12579 SmallVector<SDValue, 8> Chains; 12580 SmallPtrSet<const SDNode *, 8> Visited; 12581 SDLoc StoreDL(StoreNodes[0].MemNode); 12582 12583 for (unsigned i = 0; i < NumStores; ++i) { 12584 Visited.insert(StoreNodes[i].MemNode); 12585 } 12586 12587 // don't include nodes that are children 12588 for (unsigned i = 0; i < NumStores; ++i) { 12589 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12590 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12591 } 12592 12593 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12594 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12595 } 12596 12597 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12598 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12599 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12600 // Make sure we have something to merge. 12601 if (NumStores < 2) 12602 return false; 12603 12604 // The latest Node in the DAG. 12605 SDLoc DL(StoreNodes[0].MemNode); 12606 12607 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 12608 unsigned SizeInBits = NumStores * ElementSizeBits; 12609 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 12610 12611 EVT StoreTy; 12612 if (UseVector) { 12613 unsigned Elts = NumStores * NumMemElts; 12614 // Get the type for the merged vector store. 12615 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12616 } else 12617 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12618 12619 SDValue StoredVal; 12620 if (UseVector) { 12621 if (IsConstantSrc) { 12622 SmallVector<SDValue, 8> BuildVector; 12623 for (unsigned I = 0; I != NumStores; ++I) { 12624 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12625 SDValue Val = St->getValue(); 12626 // If constant is of the wrong type, convert it now. 12627 if (MemVT != Val.getValueType()) { 12628 Val = peekThroughBitcast(Val); 12629 // Deal with constants of wrong size. 12630 if (ElementSizeBits != Val.getValueSizeInBits()) { 12631 EVT IntMemVT = 12632 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 12633 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Val)) 12634 Val = DAG.getConstant( 12635 CFP->getValueAPF().bitcastToAPInt().zextOrTrunc( 12636 ElementSizeBits), 12637 SDLoc(CFP), IntMemVT); 12638 else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 12639 Val = DAG.getConstant( 12640 C->getAPIntValue().zextOrTrunc(ElementSizeBits), 12641 SDLoc(C), IntMemVT); 12642 } 12643 // Make sure correctly size type is the correct type. 12644 Val = DAG.getBitcast(MemVT, Val); 12645 } 12646 BuildVector.push_back(Val); 12647 } 12648 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12649 : ISD::BUILD_VECTOR, 12650 DL, StoreTy, BuildVector); 12651 } else { 12652 SmallVector<SDValue, 8> Ops; 12653 for (unsigned i = 0; i < NumStores; ++i) { 12654 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12655 SDValue Val = peekThroughBitcast(St->getValue()); 12656 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 12657 // type MemVT. If the underlying value is not the correct 12658 // type, but it is an extraction of an appropriate vector we 12659 // can recast Val to be of the correct type. This may require 12660 // converting between EXTRACT_VECTOR_ELT and 12661 // EXTRACT_SUBVECTOR. 12662 if ((MemVT != Val.getValueType()) && 12663 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12664 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 12665 SDValue Vec = Val.getOperand(0); 12666 EVT MemVTScalarTy = MemVT.getScalarType(); 12667 // We may need to add a bitcast here to get types to line up. 12668 if (MemVTScalarTy != Vec.getValueType()) { 12669 unsigned Elts = Vec.getValueType().getSizeInBits() / 12670 MemVTScalarTy.getSizeInBits(); 12671 EVT NewVecTy = 12672 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts); 12673 Vec = DAG.getBitcast(NewVecTy, Vec); 12674 } 12675 auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR 12676 : ISD::EXTRACT_VECTOR_ELT; 12677 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1)); 12678 } 12679 Ops.push_back(Val); 12680 } 12681 12682 // Build the extracted vector elements back into a vector. 12683 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 12684 : ISD::BUILD_VECTOR, 12685 DL, StoreTy, Ops); 12686 } 12687 } else { 12688 // We should always use a vector store when merging extracted vector 12689 // elements, so this path implies a store of constants. 12690 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12691 12692 APInt StoreInt(SizeInBits, 0); 12693 12694 // Construct a single integer constant which is made of the smaller 12695 // constant inputs. 12696 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12697 for (unsigned i = 0; i < NumStores; ++i) { 12698 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12699 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12700 12701 SDValue Val = St->getValue(); 12702 StoreInt <<= ElementSizeBits; 12703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12704 StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits); 12705 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12706 StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits); 12707 } else { 12708 llvm_unreachable("Invalid constant element type"); 12709 } 12710 } 12711 12712 // Create the new Load and Store operations. 12713 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12714 } 12715 12716 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12717 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12718 12719 // make sure we use trunc store if it's necessary to be legal. 12720 SDValue NewStore; 12721 if (!UseTrunc) { 12722 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12723 FirstInChain->getPointerInfo(), 12724 FirstInChain->getAlignment()); 12725 } else { // Must be realized as a trunc store 12726 EVT LegalizedStoredValueTy = 12727 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12728 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12729 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12730 SDValue ExtendedStoreVal = 12731 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12732 LegalizedStoredValueTy); 12733 NewStore = DAG.getTruncStore( 12734 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12735 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12736 FirstInChain->getAlignment(), 12737 FirstInChain->getMemOperand()->getFlags()); 12738 } 12739 12740 // Replace all merged stores with the new store. 12741 for (unsigned i = 0; i < NumStores; ++i) 12742 CombineTo(StoreNodes[i].MemNode, NewStore); 12743 12744 AddToWorklist(NewChain.getNode()); 12745 return true; 12746 } 12747 12748 void DAGCombiner::getStoreMergeCandidates( 12749 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12750 // This holds the base pointer, index, and the offset in bytes from the base 12751 // pointer. 12752 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12753 EVT MemVT = St->getMemoryVT(); 12754 12755 SDValue Val = peekThroughBitcast(St->getValue()); 12756 // We must have a base and an offset. 12757 if (!BasePtr.getBase().getNode()) 12758 return; 12759 12760 // Do not handle stores to undef base pointers. 12761 if (BasePtr.getBase().isUndef()) 12762 return; 12763 12764 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 12765 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12766 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12767 bool IsLoadSrc = isa<LoadSDNode>(Val); 12768 BaseIndexOffset LBasePtr; 12769 // Match on loadbaseptr if relevant. 12770 EVT LoadVT; 12771 if (IsLoadSrc) { 12772 auto *Ld = cast<LoadSDNode>(Val); 12773 LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12774 LoadVT = Ld->getMemoryVT(); 12775 // Load and store should be the same type. 12776 if (MemVT != LoadVT) 12777 return; 12778 } 12779 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 12780 int64_t &Offset) -> bool { 12781 if (Other->isVolatile() || Other->isIndexed()) 12782 return false; 12783 SDValue Val = peekThroughBitcast(Other->getValue()); 12784 // Allow merging constants of different types as integers. 12785 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 12786 : Other->getMemoryVT() != MemVT; 12787 if (IsLoadSrc) { 12788 if (NoTypeMatch) 12789 return false; 12790 // The Load's Base Ptr must also match 12791 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 12792 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG); 12793 if (LoadVT != OtherLd->getMemoryVT()) 12794 return false; 12795 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 12796 return false; 12797 } else 12798 return false; 12799 } 12800 if (IsConstantSrc) { 12801 if (NoTypeMatch) 12802 return false; 12803 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 12804 return false; 12805 } 12806 if (IsExtractVecSrc) { 12807 // Do not merge truncated stores here. 12808 if (Other->isTruncatingStore()) 12809 return false; 12810 if (!MemVT.bitsEq(Val.getValueType())) 12811 return false; 12812 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 12813 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12814 return false; 12815 } 12816 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12817 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 12818 }; 12819 12820 // We looking for a root node which is an ancestor to all mergable 12821 // stores. We search up through a load, to our root and then down 12822 // through all children. For instance we will find Store{1,2,3} if 12823 // St is Store1, Store2. or Store3 where the root is not a load 12824 // which always true for nonvolatile ops. TODO: Expand 12825 // the search to find all valid candidates through multiple layers of loads. 12826 // 12827 // Root 12828 // |-------|-------| 12829 // Load Load Store3 12830 // | | 12831 // Store1 Store2 12832 // 12833 // FIXME: We should be able to climb and 12834 // descend TokenFactors to find candidates as well. 12835 12836 SDNode *RootNode = (St->getChain()).getNode(); 12837 12838 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12839 RootNode = Ldn->getChain().getNode(); 12840 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12841 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12842 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 12843 if (I2.getOperandNo() == 0) 12844 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 12845 BaseIndexOffset Ptr; 12846 int64_t PtrDiff; 12847 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 12848 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 12849 } 12850 } else 12851 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12852 if (I.getOperandNo() == 0) 12853 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12854 BaseIndexOffset Ptr; 12855 int64_t PtrDiff; 12856 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 12857 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 12858 } 12859 } 12860 12861 // We need to check that merging these stores does not cause a loop in 12862 // the DAG. Any store candidate may depend on another candidate 12863 // indirectly through its operand (we already consider dependencies 12864 // through the chain). Check in parallel by searching up from 12865 // non-chain operands of candidates. 12866 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12867 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 12868 // FIXME: We should be able to truncate a full search of 12869 // predecessors by doing a BFS and keeping tabs the originating 12870 // stores from which worklist nodes come from in a similar way to 12871 // TokenFactor simplfication. 12872 12873 SmallPtrSet<const SDNode *, 16> Visited; 12874 SmallVector<const SDNode *, 8> Worklist; 12875 unsigned int Max = 8192; 12876 // Search Ops of store candidates. 12877 for (unsigned i = 0; i < NumStores; ++i) { 12878 SDNode *n = StoreNodes[i].MemNode; 12879 // Potential loops may happen only through non-chain operands 12880 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12881 Worklist.push_back(n->getOperand(j).getNode()); 12882 } 12883 // Search through DAG. We can stop early if we find a store node. 12884 for (unsigned i = 0; i < NumStores; ++i) { 12885 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 12886 Max)) 12887 return false; 12888 // Check if we ended early, failing conservatively if so. 12889 if (Visited.size() >= Max) 12890 return false; 12891 } 12892 return true; 12893 } 12894 12895 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12896 if (OptLevel == CodeGenOpt::None) 12897 return false; 12898 12899 EVT MemVT = St->getMemoryVT(); 12900 int64_t ElementSizeBytes = MemVT.getStoreSize(); 12901 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 12902 12903 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 12904 return false; 12905 12906 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12907 Attribute::NoImplicitFloat); 12908 12909 // This function cannot currently deal with non-byte-sized memory sizes. 12910 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12911 return false; 12912 12913 if (!MemVT.isSimple()) 12914 return false; 12915 12916 // Perform an early exit check. Do not bother looking at stored values that 12917 // are not constants, loads, or extracted vector elements. 12918 SDValue StoredVal = peekThroughBitcast(St->getValue()); 12919 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12920 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12921 isa<ConstantFPSDNode>(StoredVal); 12922 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12923 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12924 12925 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12926 return false; 12927 12928 SmallVector<MemOpLink, 8> StoreNodes; 12929 // Find potential store merge candidates by searching through chain sub-DAG 12930 getStoreMergeCandidates(St, StoreNodes); 12931 12932 // Check if there is anything to merge. 12933 if (StoreNodes.size() < 2) 12934 return false; 12935 12936 // Sort the memory operands according to their distance from the 12937 // base pointer. 12938 std::sort(StoreNodes.begin(), StoreNodes.end(), 12939 [](MemOpLink LHS, MemOpLink RHS) { 12940 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12941 }); 12942 12943 // Store Merge attempts to merge the lowest stores. This generally 12944 // works out as if successful, as the remaining stores are checked 12945 // after the first collection of stores is merged. However, in the 12946 // case that a non-mergeable store is found first, e.g., {p[-2], 12947 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 12948 // mergeable cases. To prevent this, we prune such stores from the 12949 // front of StoreNodes here. 12950 12951 bool RV = false; 12952 while (StoreNodes.size() > 1) { 12953 unsigned StartIdx = 0; 12954 while ((StartIdx + 1 < StoreNodes.size()) && 12955 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 12956 StoreNodes[StartIdx + 1].OffsetFromBase) 12957 ++StartIdx; 12958 12959 // Bail if we don't have enough candidates to merge. 12960 if (StartIdx + 1 >= StoreNodes.size()) 12961 return RV; 12962 12963 if (StartIdx) 12964 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 12965 12966 // Scan the memory operations on the chain and find the first 12967 // non-consecutive store memory address. 12968 unsigned NumConsecutiveStores = 1; 12969 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12970 // Check that the addresses are consecutive starting from the second 12971 // element in the list of stores. 12972 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12973 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12974 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12975 break; 12976 NumConsecutiveStores = i + 1; 12977 } 12978 12979 if (NumConsecutiveStores < 2) { 12980 StoreNodes.erase(StoreNodes.begin(), 12981 StoreNodes.begin() + NumConsecutiveStores); 12982 continue; 12983 } 12984 12985 // Check that we can merge these candidates without causing a cycle 12986 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 12987 NumConsecutiveStores)) { 12988 StoreNodes.erase(StoreNodes.begin(), 12989 StoreNodes.begin() + NumConsecutiveStores); 12990 continue; 12991 } 12992 12993 // The node with the lowest store address. 12994 LLVMContext &Context = *DAG.getContext(); 12995 const DataLayout &DL = DAG.getDataLayout(); 12996 12997 // Store the constants into memory as one consecutive store. 12998 if (IsConstantSrc) { 12999 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13000 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13001 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13002 unsigned LastLegalType = 1; 13003 unsigned LastLegalVectorType = 1; 13004 bool LastIntegerTrunc = false; 13005 bool NonZero = false; 13006 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 13007 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13008 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 13009 SDValue StoredVal = ST->getValue(); 13010 bool IsElementZero = false; 13011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 13012 IsElementZero = C->isNullValue(); 13013 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 13014 IsElementZero = C->getConstantFPValue()->isNullValue(); 13015 if (IsElementZero) { 13016 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 13017 FirstZeroAfterNonZero = i; 13018 } 13019 NonZero |= !IsElementZero; 13020 13021 // Find a legal type for the constant store. 13022 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13023 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13024 bool IsFast = false; 13025 if (TLI.isTypeLegal(StoreTy) && 13026 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13027 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13028 FirstStoreAlign, &IsFast) && 13029 IsFast) { 13030 LastIntegerTrunc = false; 13031 LastLegalType = i + 1; 13032 // Or check whether a truncstore is legal. 13033 } else if (TLI.getTypeAction(Context, StoreTy) == 13034 TargetLowering::TypePromoteInteger) { 13035 EVT LegalizedStoredValueTy = 13036 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 13037 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13038 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13039 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13040 FirstStoreAlign, &IsFast) && 13041 IsFast) { 13042 LastIntegerTrunc = true; 13043 LastLegalType = i + 1; 13044 } 13045 } 13046 13047 // We only use vectors if the constant is known to be zero or the target 13048 // allows it and the function is not marked with the noimplicitfloat 13049 // attribute. 13050 if ((!NonZero || 13051 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 13052 !NoVectors) { 13053 // Find a legal type for the vector store. 13054 unsigned Elts = (i + 1) * NumMemElts; 13055 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13056 if (TLI.isTypeLegal(Ty) && 13057 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13058 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13059 FirstStoreAlign, &IsFast) && 13060 IsFast) 13061 LastLegalVectorType = i + 1; 13062 } 13063 } 13064 13065 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 13066 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 13067 13068 // Check if we found a legal integer type that creates a meaningful merge. 13069 if (NumElem < 2) { 13070 // We know that candidate stores are in order and of correct 13071 // shape. While there is no mergeable sequence from the 13072 // beginning one may start later in the sequence. The only 13073 // reason a merge of size N could have failed where another of 13074 // the same size would not have, is if the alignment has 13075 // improved or we've dropped a non-zero value. Drop as many 13076 // candidates as we can here. 13077 unsigned NumSkip = 1; 13078 while ( 13079 (NumSkip < NumConsecutiveStores) && 13080 (NumSkip < FirstZeroAfterNonZero) && 13081 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) { 13082 NumSkip++; 13083 } 13084 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13085 continue; 13086 } 13087 13088 bool Merged = MergeStoresOfConstantsOrVecElts( 13089 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 13090 RV |= Merged; 13091 13092 // Remove merged stores for next iteration. 13093 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13094 continue; 13095 } 13096 13097 // When extracting multiple vector elements, try to store them 13098 // in one vector store rather than a sequence of scalar stores. 13099 if (IsExtractVecSrc) { 13100 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13101 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13102 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13103 unsigned NumStoresToMerge = 1; 13104 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13105 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13106 SDValue StVal = peekThroughBitcast(St->getValue()); 13107 // This restriction could be loosened. 13108 // Bail out if any stored values are not elements extracted from a 13109 // vector. It should be possible to handle mixed sources, but load 13110 // sources need more careful handling (see the block of code below that 13111 // handles consecutive loads). 13112 if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 13113 StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13114 return RV; 13115 13116 // Find a legal type for the vector store. 13117 unsigned Elts = (i + 1) * NumMemElts; 13118 EVT Ty = 13119 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 13120 bool IsFast; 13121 if (TLI.isTypeLegal(Ty) && 13122 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 13123 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 13124 FirstStoreAlign, &IsFast) && 13125 IsFast) 13126 NumStoresToMerge = i + 1; 13127 } 13128 13129 // Check if we found a legal integer type that creates a meaningful merge. 13130 if (NumStoresToMerge < 2) { 13131 // We know that candidate stores are in order and of correct 13132 // shape. While there is no mergeable sequence from the 13133 // beginning one may start later in the sequence. The only 13134 // reason a merge of size N could have failed where another of 13135 // the same size would not have, is if the alignment has 13136 // improved. Drop as many candidates as we can here. 13137 unsigned NumSkip = 1; 13138 while ((NumSkip < NumConsecutiveStores) && 13139 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13140 NumSkip++; 13141 13142 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13143 continue; 13144 } 13145 13146 bool Merged = MergeStoresOfConstantsOrVecElts( 13147 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 13148 if (!Merged) { 13149 StoreNodes.erase(StoreNodes.begin(), 13150 StoreNodes.begin() + NumStoresToMerge); 13151 continue; 13152 } 13153 // Remove merged stores for next iteration. 13154 StoreNodes.erase(StoreNodes.begin(), 13155 StoreNodes.begin() + NumStoresToMerge); 13156 RV = true; 13157 continue; 13158 } 13159 13160 // Below we handle the case of multiple consecutive stores that 13161 // come from multiple consecutive loads. We merge them into a single 13162 // wide load and a single wide store. 13163 13164 // Look for load nodes which are used by the stored values. 13165 SmallVector<MemOpLink, 8> LoadNodes; 13166 13167 // Find acceptable loads. Loads need to have the same chain (token factor), 13168 // must not be zext, volatile, indexed, and they must be consecutive. 13169 BaseIndexOffset LdBasePtr; 13170 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 13171 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 13172 SDValue Val = peekThroughBitcast(St->getValue()); 13173 LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val); 13174 if (!Ld) 13175 break; 13176 13177 // Loads must only have one use. 13178 if (!Ld->hasNUsesOfValue(1, 0)) 13179 break; 13180 13181 // The memory operands must not be volatile. 13182 if (Ld->isVolatile() || Ld->isIndexed()) 13183 break; 13184 13185 // The stored memory type must be the same. 13186 if (Ld->getMemoryVT() != MemVT) 13187 break; 13188 13189 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 13190 // If this is not the first ptr that we check. 13191 int64_t LdOffset = 0; 13192 if (LdBasePtr.getBase().getNode()) { 13193 // The base ptr must be the same. 13194 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 13195 break; 13196 } else { 13197 // Check that all other base pointers are the same as this one. 13198 LdBasePtr = LdPtr; 13199 } 13200 13201 // We found a potential memory operand to merge. 13202 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 13203 } 13204 13205 if (LoadNodes.size() < 2) { 13206 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13207 continue; 13208 } 13209 13210 // If we have load/store pair instructions and we only have two values, 13211 // don't bother merging. 13212 unsigned RequiredAlignment; 13213 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 13214 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 13215 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 13216 continue; 13217 } 13218 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 13219 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 13220 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 13221 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 13222 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 13223 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 13224 13225 // Scan the memory operations on the chain and find the first 13226 // non-consecutive load memory address. These variables hold the index in 13227 // the store node array. 13228 unsigned LastConsecutiveLoad = 1; 13229 // This variable refers to the size and not index in the array. 13230 unsigned LastLegalVectorType = 1; 13231 unsigned LastLegalIntegerType = 1; 13232 bool isDereferenceable = true; 13233 bool DoIntegerTruncate = false; 13234 StartAddress = LoadNodes[0].OffsetFromBase; 13235 SDValue FirstChain = FirstLoad->getChain(); 13236 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 13237 // All loads must share the same chain. 13238 if (LoadNodes[i].MemNode->getChain() != FirstChain) 13239 break; 13240 13241 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 13242 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 13243 break; 13244 LastConsecutiveLoad = i; 13245 13246 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 13247 isDereferenceable = false; 13248 13249 // Find a legal type for the vector store. 13250 unsigned Elts = (i + 1) * NumMemElts; 13251 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13252 13253 bool IsFastSt, IsFastLd; 13254 if (TLI.isTypeLegal(StoreTy) && 13255 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13256 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13257 FirstStoreAlign, &IsFastSt) && 13258 IsFastSt && 13259 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13260 FirstLoadAlign, &IsFastLd) && 13261 IsFastLd) { 13262 LastLegalVectorType = i + 1; 13263 } 13264 13265 // Find a legal type for the integer store. 13266 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 13267 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 13268 if (TLI.isTypeLegal(StoreTy) && 13269 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 13270 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13271 FirstStoreAlign, &IsFastSt) && 13272 IsFastSt && 13273 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13274 FirstLoadAlign, &IsFastLd) && 13275 IsFastLd) { 13276 LastLegalIntegerType = i + 1; 13277 DoIntegerTruncate = false; 13278 // Or check whether a truncstore and extload is legal. 13279 } else if (TLI.getTypeAction(Context, StoreTy) == 13280 TargetLowering::TypePromoteInteger) { 13281 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 13282 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 13283 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) && 13284 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 13285 StoreTy) && 13286 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 13287 StoreTy) && 13288 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 13289 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 13290 FirstStoreAlign, &IsFastSt) && 13291 IsFastSt && 13292 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 13293 FirstLoadAlign, &IsFastLd) && 13294 IsFastLd) { 13295 LastLegalIntegerType = i + 1; 13296 DoIntegerTruncate = true; 13297 } 13298 } 13299 } 13300 13301 // Only use vector types if the vector type is larger than the integer type. 13302 // If they are the same, use integers. 13303 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 13304 unsigned LastLegalType = 13305 std::max(LastLegalVectorType, LastLegalIntegerType); 13306 13307 // We add +1 here because the LastXXX variables refer to location while 13308 // the NumElem refers to array/index size. 13309 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 13310 NumElem = std::min(LastLegalType, NumElem); 13311 13312 if (NumElem < 2) { 13313 // We know that candidate stores are in order and of correct 13314 // shape. While there is no mergeable sequence from the 13315 // beginning one may start later in the sequence. The only 13316 // reason a merge of size N could have failed where another of 13317 // the same size would not have is if the alignment or either 13318 // the load or store has improved. Drop as many candidates as we 13319 // can here. 13320 unsigned NumSkip = 1; 13321 while ((NumSkip < LoadNodes.size()) && 13322 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 13323 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 13324 NumSkip++; 13325 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 13326 continue; 13327 } 13328 13329 // Find if it is better to use vectors or integers to load and store 13330 // to memory. 13331 EVT JointMemOpVT; 13332 if (UseVectorTy) { 13333 // Find a legal type for the vector store. 13334 unsigned Elts = NumElem * NumMemElts; 13335 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 13336 } else { 13337 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13338 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13339 } 13340 13341 SDLoc LoadDL(LoadNodes[0].MemNode); 13342 SDLoc StoreDL(StoreNodes[0].MemNode); 13343 13344 // The merged loads are required to have the same incoming chain, so 13345 // using the first's chain is acceptable. 13346 13347 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13348 AddToWorklist(NewStoreChain.getNode()); 13349 13350 MachineMemOperand::Flags MMOFlags = isDereferenceable ? 13351 MachineMemOperand::MODereferenceable: 13352 MachineMemOperand::MONone; 13353 13354 SDValue NewLoad, NewStore; 13355 if (UseVectorTy || !DoIntegerTruncate) { 13356 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13357 FirstLoad->getBasePtr(), 13358 FirstLoad->getPointerInfo(), FirstLoadAlign, 13359 MMOFlags); 13360 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13361 FirstInChain->getBasePtr(), 13362 FirstInChain->getPointerInfo(), FirstStoreAlign); 13363 } else { // This must be the truncstore/extload case 13364 EVT ExtendedTy = 13365 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13366 NewLoad = 13367 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13368 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13369 JointMemOpVT, FirstLoadAlign, MMOFlags); 13370 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13371 FirstInChain->getBasePtr(), 13372 FirstInChain->getPointerInfo(), JointMemOpVT, 13373 FirstInChain->getAlignment(), 13374 FirstInChain->getMemOperand()->getFlags()); 13375 } 13376 13377 // Transfer chain users from old loads to the new load. 13378 for (unsigned i = 0; i < NumElem; ++i) { 13379 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13380 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13381 SDValue(NewLoad.getNode(), 1)); 13382 } 13383 13384 // Replace the all stores with the new store. Recursively remove 13385 // corresponding value if its no longer used. 13386 for (unsigned i = 0; i < NumElem; ++i) { 13387 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 13388 CombineTo(StoreNodes[i].MemNode, NewStore); 13389 if (Val.getNode()->use_empty()) 13390 recursivelyDeleteUnusedNodes(Val.getNode()); 13391 } 13392 13393 RV = true; 13394 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13395 } 13396 return RV; 13397 } 13398 13399 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13400 SDLoc SL(ST); 13401 SDValue ReplStore; 13402 13403 // Replace the chain to avoid dependency. 13404 if (ST->isTruncatingStore()) { 13405 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13406 ST->getBasePtr(), ST->getMemoryVT(), 13407 ST->getMemOperand()); 13408 } else { 13409 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13410 ST->getMemOperand()); 13411 } 13412 13413 // Create token to keep both nodes around. 13414 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13415 MVT::Other, ST->getChain(), ReplStore); 13416 13417 // Make sure the new and old chains are cleaned up. 13418 AddToWorklist(Token.getNode()); 13419 13420 // Don't add users to work list. 13421 return CombineTo(ST, Token, false); 13422 } 13423 13424 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13425 SDValue Value = ST->getValue(); 13426 if (Value.getOpcode() == ISD::TargetConstantFP) 13427 return SDValue(); 13428 13429 SDLoc DL(ST); 13430 13431 SDValue Chain = ST->getChain(); 13432 SDValue Ptr = ST->getBasePtr(); 13433 13434 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13435 13436 // NOTE: If the original store is volatile, this transform must not increase 13437 // the number of stores. For example, on x86-32 an f64 can be stored in one 13438 // processor operation but an i64 (which is not legal) requires two. So the 13439 // transform should not be done in this case. 13440 13441 SDValue Tmp; 13442 switch (CFP->getSimpleValueType(0).SimpleTy) { 13443 default: 13444 llvm_unreachable("Unknown FP type"); 13445 case MVT::f16: // We don't do this for these yet. 13446 case MVT::f80: 13447 case MVT::f128: 13448 case MVT::ppcf128: 13449 return SDValue(); 13450 case MVT::f32: 13451 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13452 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13453 ; 13454 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13455 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13456 MVT::i32); 13457 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13458 } 13459 13460 return SDValue(); 13461 case MVT::f64: 13462 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13463 !ST->isVolatile()) || 13464 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13465 ; 13466 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13467 getZExtValue(), SDLoc(CFP), MVT::i64); 13468 return DAG.getStore(Chain, DL, Tmp, 13469 Ptr, ST->getMemOperand()); 13470 } 13471 13472 if (!ST->isVolatile() && 13473 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13474 // Many FP stores are not made apparent until after legalize, e.g. for 13475 // argument passing. Since this is so common, custom legalize the 13476 // 64-bit integer store into two 32-bit stores. 13477 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13478 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13479 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13480 if (DAG.getDataLayout().isBigEndian()) 13481 std::swap(Lo, Hi); 13482 13483 unsigned Alignment = ST->getAlignment(); 13484 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13485 AAMDNodes AAInfo = ST->getAAInfo(); 13486 13487 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13488 ST->getAlignment(), MMOFlags, AAInfo); 13489 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13490 DAG.getConstant(4, DL, Ptr.getValueType())); 13491 Alignment = MinAlign(Alignment, 4U); 13492 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13493 ST->getPointerInfo().getWithOffset(4), 13494 Alignment, MMOFlags, AAInfo); 13495 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13496 St0, St1); 13497 } 13498 13499 return SDValue(); 13500 } 13501 } 13502 13503 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13504 StoreSDNode *ST = cast<StoreSDNode>(N); 13505 SDValue Chain = ST->getChain(); 13506 SDValue Value = ST->getValue(); 13507 SDValue Ptr = ST->getBasePtr(); 13508 13509 // If this is a store of a bit convert, store the input value if the 13510 // resultant store does not need a higher alignment than the original. 13511 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13512 ST->isUnindexed()) { 13513 EVT SVT = Value.getOperand(0).getValueType(); 13514 if (((!LegalOperations && !ST->isVolatile()) || 13515 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13516 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13517 unsigned OrigAlign = ST->getAlignment(); 13518 bool Fast = false; 13519 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13520 ST->getAddressSpace(), OrigAlign, &Fast) && 13521 Fast) { 13522 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13523 ST->getPointerInfo(), OrigAlign, 13524 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13525 } 13526 } 13527 } 13528 13529 // Turn 'store undef, Ptr' -> nothing. 13530 if (Value.isUndef() && ST->isUnindexed()) 13531 return Chain; 13532 13533 // Try to infer better alignment information than the store already has. 13534 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13535 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13536 if (Align > ST->getAlignment()) { 13537 SDValue NewStore = 13538 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13539 ST->getMemoryVT(), Align, 13540 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13541 if (NewStore.getNode() != N) 13542 return CombineTo(ST, NewStore, true); 13543 } 13544 } 13545 } 13546 13547 // Try transforming a pair floating point load / store ops to integer 13548 // load / store ops. 13549 if (SDValue NewST = TransformFPLoadStorePair(N)) 13550 return NewST; 13551 13552 if (ST->isUnindexed()) { 13553 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13554 // adjacent stores. 13555 if (findBetterNeighborChains(ST)) { 13556 // replaceStoreChain uses CombineTo, which handled all of the worklist 13557 // manipulation. Return the original node to not do anything else. 13558 return SDValue(ST, 0); 13559 } 13560 Chain = ST->getChain(); 13561 } 13562 13563 // FIXME: is there such a thing as a truncating indexed store? 13564 if (ST->isTruncatingStore() && ST->isUnindexed() && 13565 Value.getValueType().isInteger()) { 13566 // See if we can simplify the input to this truncstore with knowledge that 13567 // only the low bits are being used. For example: 13568 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13569 SDValue Shorter = DAG.GetDemandedBits( 13570 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13571 ST->getMemoryVT().getScalarSizeInBits())); 13572 AddToWorklist(Value.getNode()); 13573 if (Shorter.getNode()) 13574 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13575 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13576 13577 // Otherwise, see if we can simplify the operation with 13578 // SimplifyDemandedBits, which only works if the value has a single use. 13579 if (SimplifyDemandedBits( 13580 Value, 13581 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13582 ST->getMemoryVT().getScalarSizeInBits()))) { 13583 // Re-visit the store if anything changed and the store hasn't been merged 13584 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13585 // node back to the worklist if necessary, but we also need to re-visit 13586 // the Store node itself. 13587 if (N->getOpcode() != ISD::DELETED_NODE) 13588 AddToWorklist(N); 13589 return SDValue(N, 0); 13590 } 13591 } 13592 13593 // If this is a load followed by a store to the same location, then the store 13594 // is dead/noop. 13595 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13596 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13597 ST->isUnindexed() && !ST->isVolatile() && 13598 // There can't be any side effects between the load and store, such as 13599 // a call or store. 13600 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13601 // The store is dead, remove it. 13602 return Chain; 13603 } 13604 } 13605 13606 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13607 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13608 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13609 ST->getMemoryVT() == ST1->getMemoryVT()) { 13610 // If this is a store followed by a store with the same value to the same 13611 // location, then the store is dead/noop. 13612 if (ST1->getValue() == Value) { 13613 // The store is dead, remove it. 13614 return Chain; 13615 } 13616 13617 // If this is a store who's preceeding store to the same location 13618 // and no one other node is chained to that store we can effectively 13619 // drop the store. Do not remove stores to undef as they may be used as 13620 // data sinks. 13621 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13622 !ST1->getBasePtr().isUndef()) { 13623 // ST1 is fully overwritten and can be elided. Combine with it's chain 13624 // value. 13625 CombineTo(ST1, ST1->getChain()); 13626 return SDValue(); 13627 } 13628 } 13629 } 13630 13631 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13632 // truncating store. We can do this even if this is already a truncstore. 13633 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13634 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13635 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13636 ST->getMemoryVT())) { 13637 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13638 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13639 } 13640 13641 // Always perform this optimization before types are legal. If the target 13642 // prefers, also try this after legalization to catch stores that were created 13643 // by intrinsics or other nodes. 13644 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 13645 while (true) { 13646 // There can be multiple store sequences on the same chain. 13647 // Keep trying to merge store sequences until we are unable to do so 13648 // or until we merge the last store on the chain. 13649 bool Changed = MergeConsecutiveStores(ST); 13650 if (!Changed) break; 13651 // Return N as merge only uses CombineTo and no worklist clean 13652 // up is necessary. 13653 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13654 return SDValue(N, 0); 13655 } 13656 } 13657 13658 // Try transforming N to an indexed store. 13659 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13660 return SDValue(N, 0); 13661 13662 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13663 // 13664 // Make sure to do this only after attempting to merge stores in order to 13665 // avoid changing the types of some subset of stores due to visit order, 13666 // preventing their merging. 13667 if (isa<ConstantFPSDNode>(ST->getValue())) { 13668 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13669 return NewSt; 13670 } 13671 13672 if (SDValue NewSt = splitMergedValStore(ST)) 13673 return NewSt; 13674 13675 return ReduceLoadOpStoreWidth(N); 13676 } 13677 13678 /// For the instruction sequence of store below, F and I values 13679 /// are bundled together as an i64 value before being stored into memory. 13680 /// Sometimes it is more efficent to generate separate stores for F and I, 13681 /// which can remove the bitwise instructions or sink them to colder places. 13682 /// 13683 /// (store (or (zext (bitcast F to i32) to i64), 13684 /// (shl (zext I to i64), 32)), addr) --> 13685 /// (store F, addr) and (store I, addr+4) 13686 /// 13687 /// Similarly, splitting for other merged store can also be beneficial, like: 13688 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13689 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13690 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13691 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13692 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13693 /// 13694 /// We allow each target to determine specifically which kind of splitting is 13695 /// supported. 13696 /// 13697 /// The store patterns are commonly seen from the simple code snippet below 13698 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13699 /// void goo(const std::pair<int, float> &); 13700 /// hoo() { 13701 /// ... 13702 /// goo(std::make_pair(tmp, ftmp)); 13703 /// ... 13704 /// } 13705 /// 13706 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13707 if (OptLevel == CodeGenOpt::None) 13708 return SDValue(); 13709 13710 SDValue Val = ST->getValue(); 13711 SDLoc DL(ST); 13712 13713 // Match OR operand. 13714 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13715 return SDValue(); 13716 13717 // Match SHL operand and get Lower and Higher parts of Val. 13718 SDValue Op1 = Val.getOperand(0); 13719 SDValue Op2 = Val.getOperand(1); 13720 SDValue Lo, Hi; 13721 if (Op1.getOpcode() != ISD::SHL) { 13722 std::swap(Op1, Op2); 13723 if (Op1.getOpcode() != ISD::SHL) 13724 return SDValue(); 13725 } 13726 Lo = Op2; 13727 Hi = Op1.getOperand(0); 13728 if (!Op1.hasOneUse()) 13729 return SDValue(); 13730 13731 // Match shift amount to HalfValBitSize. 13732 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13733 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13734 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13735 return SDValue(); 13736 13737 // Lo and Hi are zero-extended from int with size less equal than 32 13738 // to i64. 13739 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13740 !Lo.getOperand(0).getValueType().isScalarInteger() || 13741 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13742 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13743 !Hi.getOperand(0).getValueType().isScalarInteger() || 13744 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13745 return SDValue(); 13746 13747 // Use the EVT of low and high parts before bitcast as the input 13748 // of target query. 13749 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13750 ? Lo.getOperand(0).getValueType() 13751 : Lo.getValueType(); 13752 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13753 ? Hi.getOperand(0).getValueType() 13754 : Hi.getValueType(); 13755 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13756 return SDValue(); 13757 13758 // Start to split store. 13759 unsigned Alignment = ST->getAlignment(); 13760 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13761 AAMDNodes AAInfo = ST->getAAInfo(); 13762 13763 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13764 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13765 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13766 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13767 13768 SDValue Chain = ST->getChain(); 13769 SDValue Ptr = ST->getBasePtr(); 13770 // Lower value store. 13771 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13772 ST->getAlignment(), MMOFlags, AAInfo); 13773 Ptr = 13774 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13775 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13776 // Higher value store. 13777 SDValue St1 = 13778 DAG.getStore(St0, DL, Hi, Ptr, 13779 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13780 Alignment / 2, MMOFlags, AAInfo); 13781 return St1; 13782 } 13783 13784 /// Convert a disguised subvector insertion into a shuffle: 13785 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 13786 /// bitcast(shuffle (bitcast V), (extended X), Mask) 13787 /// Note: We do not use an insert_subvector node because that requires a legal 13788 /// subvector type. 13789 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 13790 SDValue InsertVal = N->getOperand(1); 13791 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 13792 !InsertVal.getOperand(0).getValueType().isVector()) 13793 return SDValue(); 13794 13795 SDValue SubVec = InsertVal.getOperand(0); 13796 SDValue DestVec = N->getOperand(0); 13797 EVT SubVecVT = SubVec.getValueType(); 13798 EVT VT = DestVec.getValueType(); 13799 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 13800 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 13801 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 13802 13803 // Step 1: Create a shuffle mask that implements this insert operation. The 13804 // vector that we are inserting into will be operand 0 of the shuffle, so 13805 // those elements are just 'i'. The inserted subvector is in the first 13806 // positions of operand 1 of the shuffle. Example: 13807 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 13808 SmallVector<int, 16> Mask(NumMaskVals); 13809 for (unsigned i = 0; i != NumMaskVals; ++i) { 13810 if (i / NumSrcElts == InsIndex) 13811 Mask[i] = (i % NumSrcElts) + NumMaskVals; 13812 else 13813 Mask[i] = i; 13814 } 13815 13816 // Bail out if the target can not handle the shuffle we want to create. 13817 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 13818 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 13819 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 13820 return SDValue(); 13821 13822 // Step 2: Create a wide vector from the inserted source vector by appending 13823 // undefined elements. This is the same size as our destination vector. 13824 SDLoc DL(N); 13825 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 13826 ConcatOps[0] = SubVec; 13827 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 13828 13829 // Step 3: Shuffle in the padded subvector. 13830 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 13831 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 13832 AddToWorklist(PaddedSubV.getNode()); 13833 AddToWorklist(DestVecBC.getNode()); 13834 AddToWorklist(Shuf.getNode()); 13835 return DAG.getBitcast(VT, Shuf); 13836 } 13837 13838 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 13839 SDValue InVec = N->getOperand(0); 13840 SDValue InVal = N->getOperand(1); 13841 SDValue EltNo = N->getOperand(2); 13842 SDLoc DL(N); 13843 13844 // If the inserted element is an UNDEF, just use the input vector. 13845 if (InVal.isUndef()) 13846 return InVec; 13847 13848 EVT VT = InVec.getValueType(); 13849 13850 // Remove redundant insertions: 13851 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 13852 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 13853 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 13854 return InVec; 13855 13856 // We must know which element is being inserted for folds below here. 13857 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 13858 if (!IndexC) 13859 return SDValue(); 13860 unsigned Elt = IndexC->getZExtValue(); 13861 13862 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 13863 return Shuf; 13864 13865 // Canonicalize insert_vector_elt dag nodes. 13866 // Example: 13867 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 13868 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 13869 // 13870 // Do this only if the child insert_vector node has one use; also 13871 // do this only if indices are both constants and Idx1 < Idx0. 13872 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 13873 && isa<ConstantSDNode>(InVec.getOperand(2))) { 13874 unsigned OtherElt = InVec.getConstantOperandVal(2); 13875 if (Elt < OtherElt) { 13876 // Swap nodes. 13877 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 13878 InVec.getOperand(0), InVal, EltNo); 13879 AddToWorklist(NewOp.getNode()); 13880 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 13881 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 13882 } 13883 } 13884 13885 // If we can't generate a legal BUILD_VECTOR, exit 13886 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13887 return SDValue(); 13888 13889 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13890 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13891 // vector elements. 13892 SmallVector<SDValue, 8> Ops; 13893 // Do not combine these two vectors if the output vector will not replace 13894 // the input vector. 13895 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13896 Ops.append(InVec.getNode()->op_begin(), 13897 InVec.getNode()->op_end()); 13898 } else if (InVec.isUndef()) { 13899 unsigned NElts = VT.getVectorNumElements(); 13900 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13901 } else { 13902 return SDValue(); 13903 } 13904 13905 // Insert the element 13906 if (Elt < Ops.size()) { 13907 // All the operands of BUILD_VECTOR must have the same type; 13908 // we enforce that here. 13909 EVT OpVT = Ops[0].getValueType(); 13910 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13911 } 13912 13913 // Return the new vector 13914 return DAG.getBuildVector(VT, DL, Ops); 13915 } 13916 13917 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13918 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13919 assert(!OriginalLoad->isVolatile()); 13920 13921 EVT ResultVT = EVE->getValueType(0); 13922 EVT VecEltVT = InVecVT.getVectorElementType(); 13923 unsigned Align = OriginalLoad->getAlignment(); 13924 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13925 VecEltVT.getTypeForEVT(*DAG.getContext())); 13926 13927 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13928 return SDValue(); 13929 13930 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13931 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13932 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13933 return SDValue(); 13934 13935 Align = NewAlign; 13936 13937 SDValue NewPtr = OriginalLoad->getBasePtr(); 13938 SDValue Offset; 13939 EVT PtrType = NewPtr.getValueType(); 13940 MachinePointerInfo MPI; 13941 SDLoc DL(EVE); 13942 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13943 int Elt = ConstEltNo->getZExtValue(); 13944 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13945 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13946 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13947 } else { 13948 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13949 Offset = DAG.getNode( 13950 ISD::MUL, DL, PtrType, Offset, 13951 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13952 MPI = OriginalLoad->getPointerInfo(); 13953 } 13954 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13955 13956 // The replacement we need to do here is a little tricky: we need to 13957 // replace an extractelement of a load with a load. 13958 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13959 // Note that this replacement assumes that the extractvalue is the only 13960 // use of the load; that's okay because we don't want to perform this 13961 // transformation in other cases anyway. 13962 SDValue Load; 13963 SDValue Chain; 13964 if (ResultVT.bitsGT(VecEltVT)) { 13965 // If the result type of vextract is wider than the load, then issue an 13966 // extending load instead. 13967 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13968 VecEltVT) 13969 ? ISD::ZEXTLOAD 13970 : ISD::EXTLOAD; 13971 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13972 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13973 Align, OriginalLoad->getMemOperand()->getFlags(), 13974 OriginalLoad->getAAInfo()); 13975 Chain = Load.getValue(1); 13976 } else { 13977 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13978 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13979 OriginalLoad->getAAInfo()); 13980 Chain = Load.getValue(1); 13981 if (ResultVT.bitsLT(VecEltVT)) 13982 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13983 else 13984 Load = DAG.getBitcast(ResultVT, Load); 13985 } 13986 WorklistRemover DeadNodes(*this); 13987 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13988 SDValue To[] = { Load, Chain }; 13989 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13990 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13991 // worklist explicitly as well. 13992 AddToWorklist(Load.getNode()); 13993 AddUsersToWorklist(Load.getNode()); // Add users too 13994 // Make sure to revisit this node to clean it up; it will usually be dead. 13995 AddToWorklist(EVE); 13996 ++OpsNarrowed; 13997 return SDValue(EVE, 0); 13998 } 13999 14000 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 14001 // (vextract (scalar_to_vector val, 0) -> val 14002 SDValue InVec = N->getOperand(0); 14003 EVT VT = InVec.getValueType(); 14004 EVT NVT = N->getValueType(0); 14005 14006 if (InVec.isUndef()) 14007 return DAG.getUNDEF(NVT); 14008 14009 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14010 // Check if the result type doesn't match the inserted element type. A 14011 // SCALAR_TO_VECTOR may truncate the inserted element and the 14012 // EXTRACT_VECTOR_ELT may widen the extracted vector. 14013 SDValue InOp = InVec.getOperand(0); 14014 if (InOp.getValueType() != NVT) { 14015 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14016 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 14017 } 14018 return InOp; 14019 } 14020 14021 SDValue EltNo = N->getOperand(1); 14022 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 14023 14024 // extract_vector_elt (build_vector x, y), 1 -> y 14025 if (ConstEltNo && 14026 InVec.getOpcode() == ISD::BUILD_VECTOR && 14027 TLI.isTypeLegal(VT) && 14028 (InVec.hasOneUse() || 14029 TLI.aggressivelyPreferBuildVectorSources(VT))) { 14030 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 14031 EVT InEltVT = Elt.getValueType(); 14032 14033 // Sometimes build_vector's scalar input types do not match result type. 14034 if (NVT == InEltVT) 14035 return Elt; 14036 14037 // TODO: It may be useful to truncate if free if the build_vector implicitly 14038 // converts. 14039 } 14040 14041 // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x) 14042 bool isLE = DAG.getDataLayout().isLittleEndian(); 14043 unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1; 14044 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 14045 ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) { 14046 SDValue BCSrc = InVec.getOperand(0); 14047 if (BCSrc.getValueType().isScalarInteger()) 14048 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 14049 } 14050 14051 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 14052 // 14053 // This only really matters if the index is non-constant since other combines 14054 // on the constant elements already work. 14055 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 14056 EltNo == InVec.getOperand(2)) { 14057 SDValue Elt = InVec.getOperand(1); 14058 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 14059 } 14060 14061 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 14062 // We only perform this optimization before the op legalization phase because 14063 // we may introduce new vector instructions which are not backed by TD 14064 // patterns. For example on AVX, extracting elements from a wide vector 14065 // without using extract_subvector. However, if we can find an underlying 14066 // scalar value, then we can always use that. 14067 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 14068 int NumElem = VT.getVectorNumElements(); 14069 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 14070 // Find the new index to extract from. 14071 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 14072 14073 // Extracting an undef index is undef. 14074 if (OrigElt == -1) 14075 return DAG.getUNDEF(NVT); 14076 14077 // Select the right vector half to extract from. 14078 SDValue SVInVec; 14079 if (OrigElt < NumElem) { 14080 SVInVec = InVec->getOperand(0); 14081 } else { 14082 SVInVec = InVec->getOperand(1); 14083 OrigElt -= NumElem; 14084 } 14085 14086 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 14087 SDValue InOp = SVInVec.getOperand(OrigElt); 14088 if (InOp.getValueType() != NVT) { 14089 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 14090 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 14091 } 14092 14093 return InOp; 14094 } 14095 14096 // FIXME: We should handle recursing on other vector shuffles and 14097 // scalar_to_vector here as well. 14098 14099 if (!LegalOperations || 14100 // FIXME: Should really be just isOperationLegalOrCustom. 14101 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) || 14102 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) { 14103 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14104 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 14105 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 14106 } 14107 } 14108 14109 bool BCNumEltsChanged = false; 14110 EVT ExtVT = VT.getVectorElementType(); 14111 EVT LVT = ExtVT; 14112 14113 // If the result of load has to be truncated, then it's not necessarily 14114 // profitable. 14115 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 14116 return SDValue(); 14117 14118 if (InVec.getOpcode() == ISD::BITCAST) { 14119 // Don't duplicate a load with other uses. 14120 if (!InVec.hasOneUse()) 14121 return SDValue(); 14122 14123 EVT BCVT = InVec.getOperand(0).getValueType(); 14124 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 14125 return SDValue(); 14126 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 14127 BCNumEltsChanged = true; 14128 InVec = InVec.getOperand(0); 14129 ExtVT = BCVT.getVectorElementType(); 14130 } 14131 14132 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 14133 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 14134 ISD::isNormalLoad(InVec.getNode()) && 14135 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 14136 SDValue Index = N->getOperand(1); 14137 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 14138 if (!OrigLoad->isVolatile()) { 14139 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 14140 OrigLoad); 14141 } 14142 } 14143 } 14144 14145 // Perform only after legalization to ensure build_vector / vector_shuffle 14146 // optimizations have already been done. 14147 if (!LegalOperations) return SDValue(); 14148 14149 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 14150 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 14151 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 14152 14153 if (ConstEltNo) { 14154 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 14155 14156 LoadSDNode *LN0 = nullptr; 14157 const ShuffleVectorSDNode *SVN = nullptr; 14158 if (ISD::isNormalLoad(InVec.getNode())) { 14159 LN0 = cast<LoadSDNode>(InVec); 14160 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 14161 InVec.getOperand(0).getValueType() == ExtVT && 14162 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 14163 // Don't duplicate a load with other uses. 14164 if (!InVec.hasOneUse()) 14165 return SDValue(); 14166 14167 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 14168 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 14169 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 14170 // => 14171 // (load $addr+1*size) 14172 14173 // Don't duplicate a load with other uses. 14174 if (!InVec.hasOneUse()) 14175 return SDValue(); 14176 14177 // If the bit convert changed the number of elements, it is unsafe 14178 // to examine the mask. 14179 if (BCNumEltsChanged) 14180 return SDValue(); 14181 14182 // Select the input vector, guarding against out of range extract vector. 14183 unsigned NumElems = VT.getVectorNumElements(); 14184 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 14185 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 14186 14187 if (InVec.getOpcode() == ISD::BITCAST) { 14188 // Don't duplicate a load with other uses. 14189 if (!InVec.hasOneUse()) 14190 return SDValue(); 14191 14192 InVec = InVec.getOperand(0); 14193 } 14194 if (ISD::isNormalLoad(InVec.getNode())) { 14195 LN0 = cast<LoadSDNode>(InVec); 14196 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 14197 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 14198 } 14199 } 14200 14201 // Make sure we found a non-volatile load and the extractelement is 14202 // the only use. 14203 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 14204 return SDValue(); 14205 14206 // If Idx was -1 above, Elt is going to be -1, so just return undef. 14207 if (Elt == -1) 14208 return DAG.getUNDEF(LVT); 14209 14210 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 14211 } 14212 14213 return SDValue(); 14214 } 14215 14216 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 14217 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 14218 // We perform this optimization post type-legalization because 14219 // the type-legalizer often scalarizes integer-promoted vectors. 14220 // Performing this optimization before may create bit-casts which 14221 // will be type-legalized to complex code sequences. 14222 // We perform this optimization only before the operation legalizer because we 14223 // may introduce illegal operations. 14224 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 14225 return SDValue(); 14226 14227 unsigned NumInScalars = N->getNumOperands(); 14228 SDLoc DL(N); 14229 EVT VT = N->getValueType(0); 14230 14231 // Check to see if this is a BUILD_VECTOR of a bunch of values 14232 // which come from any_extend or zero_extend nodes. If so, we can create 14233 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 14234 // optimizations. We do not handle sign-extend because we can't fill the sign 14235 // using shuffles. 14236 EVT SourceType = MVT::Other; 14237 bool AllAnyExt = true; 14238 14239 for (unsigned i = 0; i != NumInScalars; ++i) { 14240 SDValue In = N->getOperand(i); 14241 // Ignore undef inputs. 14242 if (In.isUndef()) continue; 14243 14244 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 14245 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 14246 14247 // Abort if the element is not an extension. 14248 if (!ZeroExt && !AnyExt) { 14249 SourceType = MVT::Other; 14250 break; 14251 } 14252 14253 // The input is a ZeroExt or AnyExt. Check the original type. 14254 EVT InTy = In.getOperand(0).getValueType(); 14255 14256 // Check that all of the widened source types are the same. 14257 if (SourceType == MVT::Other) 14258 // First time. 14259 SourceType = InTy; 14260 else if (InTy != SourceType) { 14261 // Multiple income types. Abort. 14262 SourceType = MVT::Other; 14263 break; 14264 } 14265 14266 // Check if all of the extends are ANY_EXTENDs. 14267 AllAnyExt &= AnyExt; 14268 } 14269 14270 // In order to have valid types, all of the inputs must be extended from the 14271 // same source type and all of the inputs must be any or zero extend. 14272 // Scalar sizes must be a power of two. 14273 EVT OutScalarTy = VT.getScalarType(); 14274 bool ValidTypes = SourceType != MVT::Other && 14275 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 14276 isPowerOf2_32(SourceType.getSizeInBits()); 14277 14278 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 14279 // turn into a single shuffle instruction. 14280 if (!ValidTypes) 14281 return SDValue(); 14282 14283 bool isLE = DAG.getDataLayout().isLittleEndian(); 14284 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 14285 assert(ElemRatio > 1 && "Invalid element size ratio"); 14286 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 14287 DAG.getConstant(0, DL, SourceType); 14288 14289 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 14290 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 14291 14292 // Populate the new build_vector 14293 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14294 SDValue Cast = N->getOperand(i); 14295 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 14296 Cast.getOpcode() == ISD::ZERO_EXTEND || 14297 Cast.isUndef()) && "Invalid cast opcode"); 14298 SDValue In; 14299 if (Cast.isUndef()) 14300 In = DAG.getUNDEF(SourceType); 14301 else 14302 In = Cast->getOperand(0); 14303 unsigned Index = isLE ? (i * ElemRatio) : 14304 (i * ElemRatio + (ElemRatio - 1)); 14305 14306 assert(Index < Ops.size() && "Invalid index"); 14307 Ops[Index] = In; 14308 } 14309 14310 // The type of the new BUILD_VECTOR node. 14311 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 14312 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 14313 "Invalid vector size"); 14314 // Check if the new vector type is legal. 14315 if (!isTypeLegal(VecVT)) return SDValue(); 14316 14317 // Make the new BUILD_VECTOR. 14318 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 14319 14320 // The new BUILD_VECTOR node has the potential to be further optimized. 14321 AddToWorklist(BV.getNode()); 14322 // Bitcast to the desired type. 14323 return DAG.getBitcast(VT, BV); 14324 } 14325 14326 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 14327 EVT VT = N->getValueType(0); 14328 14329 unsigned NumInScalars = N->getNumOperands(); 14330 SDLoc DL(N); 14331 14332 EVT SrcVT = MVT::Other; 14333 unsigned Opcode = ISD::DELETED_NODE; 14334 unsigned NumDefs = 0; 14335 14336 for (unsigned i = 0; i != NumInScalars; ++i) { 14337 SDValue In = N->getOperand(i); 14338 unsigned Opc = In.getOpcode(); 14339 14340 if (Opc == ISD::UNDEF) 14341 continue; 14342 14343 // If all scalar values are floats and converted from integers. 14344 if (Opcode == ISD::DELETED_NODE && 14345 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 14346 Opcode = Opc; 14347 } 14348 14349 if (Opc != Opcode) 14350 return SDValue(); 14351 14352 EVT InVT = In.getOperand(0).getValueType(); 14353 14354 // If all scalar values are typed differently, bail out. It's chosen to 14355 // simplify BUILD_VECTOR of integer types. 14356 if (SrcVT == MVT::Other) 14357 SrcVT = InVT; 14358 if (SrcVT != InVT) 14359 return SDValue(); 14360 NumDefs++; 14361 } 14362 14363 // If the vector has just one element defined, it's not worth to fold it into 14364 // a vectorized one. 14365 if (NumDefs < 2) 14366 return SDValue(); 14367 14368 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 14369 && "Should only handle conversion from integer to float."); 14370 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 14371 14372 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 14373 14374 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 14375 return SDValue(); 14376 14377 // Just because the floating-point vector type is legal does not necessarily 14378 // mean that the corresponding integer vector type is. 14379 if (!isTypeLegal(NVT)) 14380 return SDValue(); 14381 14382 SmallVector<SDValue, 8> Opnds; 14383 for (unsigned i = 0; i != NumInScalars; ++i) { 14384 SDValue In = N->getOperand(i); 14385 14386 if (In.isUndef()) 14387 Opnds.push_back(DAG.getUNDEF(SrcVT)); 14388 else 14389 Opnds.push_back(In.getOperand(0)); 14390 } 14391 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 14392 AddToWorklist(BV.getNode()); 14393 14394 return DAG.getNode(Opcode, DL, VT, BV); 14395 } 14396 14397 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 14398 ArrayRef<int> VectorMask, 14399 SDValue VecIn1, SDValue VecIn2, 14400 unsigned LeftIdx) { 14401 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14402 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 14403 14404 EVT VT = N->getValueType(0); 14405 EVT InVT1 = VecIn1.getValueType(); 14406 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14407 14408 unsigned Vec2Offset = 0; 14409 unsigned NumElems = VT.getVectorNumElements(); 14410 unsigned ShuffleNumElems = NumElems; 14411 14412 // In case both the input vectors are extracted from same base 14413 // vector we do not need extra addend (Vec2Offset) while 14414 // computing shuffle mask. 14415 if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14416 !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) || 14417 !(VecIn1.getOperand(0) == VecIn2.getOperand(0))) 14418 Vec2Offset = InVT1.getVectorNumElements(); 14419 14420 // We can't generate a shuffle node with mismatched input and output types. 14421 // Try to make the types match the type of the output. 14422 if (InVT1 != VT || InVT2 != VT) { 14423 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14424 // If the output vector length is a multiple of both input lengths, 14425 // we can concatenate them and pad the rest with undefs. 14426 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14427 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14428 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14429 ConcatOps[0] = VecIn1; 14430 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14431 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14432 VecIn2 = SDValue(); 14433 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14434 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 14435 return SDValue(); 14436 14437 if (!VecIn2.getNode()) { 14438 // If we only have one input vector, and it's twice the size of the 14439 // output, split it in two. 14440 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14441 DAG.getConstant(NumElems, DL, IdxTy)); 14442 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14443 // Since we now have shorter input vectors, adjust the offset of the 14444 // second vector's start. 14445 Vec2Offset = NumElems; 14446 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14447 // VecIn1 is wider than the output, and we have another, possibly 14448 // smaller input. Pad the smaller input with undefs, shuffle at the 14449 // input vector width, and extract the output. 14450 // The shuffle type is different than VT, so check legality again. 14451 if (LegalOperations && 14452 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14453 return SDValue(); 14454 14455 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14456 // lower it back into a BUILD_VECTOR. So if the inserted type is 14457 // illegal, don't even try. 14458 if (InVT1 != InVT2) { 14459 if (!TLI.isTypeLegal(InVT2)) 14460 return SDValue(); 14461 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14462 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14463 } 14464 ShuffleNumElems = NumElems * 2; 14465 } else { 14466 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14467 // than VecIn1. We can't handle this for now - this case will disappear 14468 // when we start sorting the vectors by type. 14469 return SDValue(); 14470 } 14471 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 14472 InVT1.getSizeInBits() == VT.getSizeInBits()) { 14473 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 14474 ConcatOps[0] = VecIn2; 14475 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14476 } else { 14477 // TODO: Support cases where the length mismatch isn't exactly by a 14478 // factor of 2. 14479 // TODO: Move this check upwards, so that if we have bad type 14480 // mismatches, we don't create any DAG nodes. 14481 return SDValue(); 14482 } 14483 } 14484 14485 // Initialize mask to undef. 14486 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14487 14488 // Only need to run up to the number of elements actually used, not the 14489 // total number of elements in the shuffle - if we are shuffling a wider 14490 // vector, the high lanes should be set to undef. 14491 for (unsigned i = 0; i != NumElems; ++i) { 14492 if (VectorMask[i] <= 0) 14493 continue; 14494 14495 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14496 if (VectorMask[i] == (int)LeftIdx) { 14497 Mask[i] = ExtIndex; 14498 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14499 Mask[i] = Vec2Offset + ExtIndex; 14500 } 14501 } 14502 14503 // The type the input vectors may have changed above. 14504 InVT1 = VecIn1.getValueType(); 14505 14506 // If we already have a VecIn2, it should have the same type as VecIn1. 14507 // If we don't, get an undef/zero vector of the appropriate type. 14508 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14509 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14510 14511 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14512 if (ShuffleNumElems > NumElems) 14513 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14514 14515 return Shuffle; 14516 } 14517 14518 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14519 // operations. If the types of the vectors we're extracting from allow it, 14520 // turn this into a vector_shuffle node. 14521 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14522 SDLoc DL(N); 14523 EVT VT = N->getValueType(0); 14524 14525 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14526 if (!isTypeLegal(VT)) 14527 return SDValue(); 14528 14529 // May only combine to shuffle after legalize if shuffle is legal. 14530 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14531 return SDValue(); 14532 14533 bool UsesZeroVector = false; 14534 unsigned NumElems = N->getNumOperands(); 14535 14536 // Record, for each element of the newly built vector, which input vector 14537 // that element comes from. -1 stands for undef, 0 for the zero vector, 14538 // and positive values for the input vectors. 14539 // VectorMask maps each element to its vector number, and VecIn maps vector 14540 // numbers to their initial SDValues. 14541 14542 SmallVector<int, 8> VectorMask(NumElems, -1); 14543 SmallVector<SDValue, 8> VecIn; 14544 VecIn.push_back(SDValue()); 14545 14546 for (unsigned i = 0; i != NumElems; ++i) { 14547 SDValue Op = N->getOperand(i); 14548 14549 if (Op.isUndef()) 14550 continue; 14551 14552 // See if we can use a blend with a zero vector. 14553 // TODO: Should we generalize this to a blend with an arbitrary constant 14554 // vector? 14555 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14556 UsesZeroVector = true; 14557 VectorMask[i] = 0; 14558 continue; 14559 } 14560 14561 // Not an undef or zero. If the input is something other than an 14562 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14563 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14564 !isa<ConstantSDNode>(Op.getOperand(1))) 14565 return SDValue(); 14566 SDValue ExtractedFromVec = Op.getOperand(0); 14567 14568 // All inputs must have the same element type as the output. 14569 if (VT.getVectorElementType() != 14570 ExtractedFromVec.getValueType().getVectorElementType()) 14571 return SDValue(); 14572 14573 // Have we seen this input vector before? 14574 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14575 // a map back from SDValues to numbers isn't worth it. 14576 unsigned Idx = std::distance( 14577 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14578 if (Idx == VecIn.size()) 14579 VecIn.push_back(ExtractedFromVec); 14580 14581 VectorMask[i] = Idx; 14582 } 14583 14584 // If we didn't find at least one input vector, bail out. 14585 if (VecIn.size() < 2) 14586 return SDValue(); 14587 14588 // If all the Operands of BUILD_VECTOR extract from same 14589 // vector, then split the vector efficiently based on the maximum 14590 // vector access index and adjust the VectorMask and 14591 // VecIn accordingly. 14592 if (VecIn.size() == 2) { 14593 unsigned MaxIndex = 0; 14594 unsigned NearestPow2 = 0; 14595 SDValue Vec = VecIn.back(); 14596 EVT InVT = Vec.getValueType(); 14597 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 14598 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 14599 14600 for (unsigned i = 0; i < NumElems; i++) { 14601 if (VectorMask[i] <= 0) 14602 continue; 14603 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 14604 IndexVec[i] = Index; 14605 MaxIndex = std::max(MaxIndex, Index); 14606 } 14607 14608 NearestPow2 = PowerOf2Ceil(MaxIndex); 14609 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 14610 NumElems * 2 < NearestPow2) { 14611 unsigned SplitSize = NearestPow2 / 2; 14612 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 14613 InVT.getVectorElementType(), SplitSize); 14614 if (TLI.isTypeLegal(SplitVT)) { 14615 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14616 DAG.getConstant(SplitSize, DL, IdxTy)); 14617 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 14618 DAG.getConstant(0, DL, IdxTy)); 14619 VecIn.pop_back(); 14620 VecIn.push_back(VecIn1); 14621 VecIn.push_back(VecIn2); 14622 14623 for (unsigned i = 0; i < NumElems; i++) { 14624 if (VectorMask[i] <= 0) 14625 continue; 14626 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 14627 } 14628 } 14629 } 14630 } 14631 14632 // TODO: We want to sort the vectors by descending length, so that adjacent 14633 // pairs have similar length, and the longer vector is always first in the 14634 // pair. 14635 14636 // TODO: Should this fire if some of the input vectors has illegal type (like 14637 // it does now), or should we let legalization run its course first? 14638 14639 // Shuffle phase: 14640 // Take pairs of vectors, and shuffle them so that the result has elements 14641 // from these vectors in the correct places. 14642 // For example, given: 14643 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14644 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14645 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14646 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14647 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14648 // We will generate: 14649 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14650 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14651 SmallVector<SDValue, 4> Shuffles; 14652 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14653 unsigned LeftIdx = 2 * In + 1; 14654 SDValue VecLeft = VecIn[LeftIdx]; 14655 SDValue VecRight = 14656 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14657 14658 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14659 VecRight, LeftIdx)) 14660 Shuffles.push_back(Shuffle); 14661 else 14662 return SDValue(); 14663 } 14664 14665 // If we need the zero vector as an "ingredient" in the blend tree, add it 14666 // to the list of shuffles. 14667 if (UsesZeroVector) 14668 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14669 : DAG.getConstantFP(0.0, DL, VT)); 14670 14671 // If we only have one shuffle, we're done. 14672 if (Shuffles.size() == 1) 14673 return Shuffles[0]; 14674 14675 // Update the vector mask to point to the post-shuffle vectors. 14676 for (int &Vec : VectorMask) 14677 if (Vec == 0) 14678 Vec = Shuffles.size() - 1; 14679 else 14680 Vec = (Vec - 1) / 2; 14681 14682 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14683 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14684 // generate: 14685 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14686 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14687 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14688 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14689 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14690 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14691 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14692 14693 // Make sure the initial size of the shuffle list is even. 14694 if (Shuffles.size() % 2) 14695 Shuffles.push_back(DAG.getUNDEF(VT)); 14696 14697 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14698 if (CurSize % 2) { 14699 Shuffles[CurSize] = DAG.getUNDEF(VT); 14700 CurSize++; 14701 } 14702 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14703 int Left = 2 * In; 14704 int Right = 2 * In + 1; 14705 SmallVector<int, 8> Mask(NumElems, -1); 14706 for (unsigned i = 0; i != NumElems; ++i) { 14707 if (VectorMask[i] == Left) { 14708 Mask[i] = i; 14709 VectorMask[i] = In; 14710 } else if (VectorMask[i] == Right) { 14711 Mask[i] = i + NumElems; 14712 VectorMask[i] = In; 14713 } 14714 } 14715 14716 Shuffles[In] = 14717 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14718 } 14719 } 14720 return Shuffles[0]; 14721 } 14722 14723 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14724 EVT VT = N->getValueType(0); 14725 14726 // A vector built entirely of undefs is undef. 14727 if (ISD::allOperandsUndef(N)) 14728 return DAG.getUNDEF(VT); 14729 14730 // Check if we can express BUILD VECTOR via subvector extract. 14731 if (!LegalTypes && (N->getNumOperands() > 1)) { 14732 SDValue Op0 = N->getOperand(0); 14733 auto checkElem = [&](SDValue Op) -> uint64_t { 14734 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14735 (Op0.getOperand(0) == Op.getOperand(0))) 14736 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14737 return CNode->getZExtValue(); 14738 return -1; 14739 }; 14740 14741 int Offset = checkElem(Op0); 14742 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14743 if (Offset + i != checkElem(N->getOperand(i))) { 14744 Offset = -1; 14745 break; 14746 } 14747 } 14748 14749 if ((Offset == 0) && 14750 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14751 return Op0.getOperand(0); 14752 if ((Offset != -1) && 14753 ((Offset % N->getValueType(0).getVectorNumElements()) == 14754 0)) // IDX must be multiple of output size. 14755 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14756 Op0.getOperand(0), Op0.getOperand(1)); 14757 } 14758 14759 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14760 return V; 14761 14762 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14763 return V; 14764 14765 if (SDValue V = reduceBuildVecToShuffle(N)) 14766 return V; 14767 14768 return SDValue(); 14769 } 14770 14771 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14773 EVT OpVT = N->getOperand(0).getValueType(); 14774 14775 // If the operands are legal vectors, leave them alone. 14776 if (TLI.isTypeLegal(OpVT)) 14777 return SDValue(); 14778 14779 SDLoc DL(N); 14780 EVT VT = N->getValueType(0); 14781 SmallVector<SDValue, 8> Ops; 14782 14783 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14784 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14785 14786 // Keep track of what we encounter. 14787 bool AnyInteger = false; 14788 bool AnyFP = false; 14789 for (const SDValue &Op : N->ops()) { 14790 if (ISD::BITCAST == Op.getOpcode() && 14791 !Op.getOperand(0).getValueType().isVector()) 14792 Ops.push_back(Op.getOperand(0)); 14793 else if (ISD::UNDEF == Op.getOpcode()) 14794 Ops.push_back(ScalarUndef); 14795 else 14796 return SDValue(); 14797 14798 // Note whether we encounter an integer or floating point scalar. 14799 // If it's neither, bail out, it could be something weird like x86mmx. 14800 EVT LastOpVT = Ops.back().getValueType(); 14801 if (LastOpVT.isFloatingPoint()) 14802 AnyFP = true; 14803 else if (LastOpVT.isInteger()) 14804 AnyInteger = true; 14805 else 14806 return SDValue(); 14807 } 14808 14809 // If any of the operands is a floating point scalar bitcast to a vector, 14810 // use floating point types throughout, and bitcast everything. 14811 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14812 if (AnyFP) { 14813 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14814 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14815 if (AnyInteger) { 14816 for (SDValue &Op : Ops) { 14817 if (Op.getValueType() == SVT) 14818 continue; 14819 if (Op.isUndef()) 14820 Op = ScalarUndef; 14821 else 14822 Op = DAG.getBitcast(SVT, Op); 14823 } 14824 } 14825 } 14826 14827 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 14828 VT.getSizeInBits() / SVT.getSizeInBits()); 14829 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 14830 } 14831 14832 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 14833 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 14834 // most two distinct vectors the same size as the result, attempt to turn this 14835 // into a legal shuffle. 14836 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 14837 EVT VT = N->getValueType(0); 14838 EVT OpVT = N->getOperand(0).getValueType(); 14839 int NumElts = VT.getVectorNumElements(); 14840 int NumOpElts = OpVT.getVectorNumElements(); 14841 14842 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 14843 SmallVector<int, 8> Mask; 14844 14845 for (SDValue Op : N->ops()) { 14846 // Peek through any bitcast. 14847 Op = peekThroughBitcast(Op); 14848 14849 // UNDEF nodes convert to UNDEF shuffle mask values. 14850 if (Op.isUndef()) { 14851 Mask.append((unsigned)NumOpElts, -1); 14852 continue; 14853 } 14854 14855 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14856 return SDValue(); 14857 14858 // What vector are we extracting the subvector from and at what index? 14859 SDValue ExtVec = Op.getOperand(0); 14860 14861 // We want the EVT of the original extraction to correctly scale the 14862 // extraction index. 14863 EVT ExtVT = ExtVec.getValueType(); 14864 14865 // Peek through any bitcast. 14866 ExtVec = peekThroughBitcast(ExtVec); 14867 14868 // UNDEF nodes convert to UNDEF shuffle mask values. 14869 if (ExtVec.isUndef()) { 14870 Mask.append((unsigned)NumOpElts, -1); 14871 continue; 14872 } 14873 14874 if (!isa<ConstantSDNode>(Op.getOperand(1))) 14875 return SDValue(); 14876 int ExtIdx = Op.getConstantOperandVal(1); 14877 14878 // Ensure that we are extracting a subvector from a vector the same 14879 // size as the result. 14880 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 14881 return SDValue(); 14882 14883 // Scale the subvector index to account for any bitcast. 14884 int NumExtElts = ExtVT.getVectorNumElements(); 14885 if (0 == (NumExtElts % NumElts)) 14886 ExtIdx /= (NumExtElts / NumElts); 14887 else if (0 == (NumElts % NumExtElts)) 14888 ExtIdx *= (NumElts / NumExtElts); 14889 else 14890 return SDValue(); 14891 14892 // At most we can reference 2 inputs in the final shuffle. 14893 if (SV0.isUndef() || SV0 == ExtVec) { 14894 SV0 = ExtVec; 14895 for (int i = 0; i != NumOpElts; ++i) 14896 Mask.push_back(i + ExtIdx); 14897 } else if (SV1.isUndef() || SV1 == ExtVec) { 14898 SV1 = ExtVec; 14899 for (int i = 0; i != NumOpElts; ++i) 14900 Mask.push_back(i + ExtIdx + NumElts); 14901 } else { 14902 return SDValue(); 14903 } 14904 } 14905 14906 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 14907 return SDValue(); 14908 14909 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 14910 DAG.getBitcast(VT, SV1), Mask); 14911 } 14912 14913 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 14914 // If we only have one input vector, we don't need to do any concatenation. 14915 if (N->getNumOperands() == 1) 14916 return N->getOperand(0); 14917 14918 // Check if all of the operands are undefs. 14919 EVT VT = N->getValueType(0); 14920 if (ISD::allOperandsUndef(N)) 14921 return DAG.getUNDEF(VT); 14922 14923 // Optimize concat_vectors where all but the first of the vectors are undef. 14924 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 14925 return Op.isUndef(); 14926 })) { 14927 SDValue In = N->getOperand(0); 14928 assert(In.getValueType().isVector() && "Must concat vectors"); 14929 14930 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 14931 if (In->getOpcode() == ISD::BITCAST && 14932 !In->getOperand(0)->getValueType(0).isVector()) { 14933 SDValue Scalar = In->getOperand(0); 14934 14935 // If the bitcast type isn't legal, it might be a trunc of a legal type; 14936 // look through the trunc so we can still do the transform: 14937 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 14938 if (Scalar->getOpcode() == ISD::TRUNCATE && 14939 !TLI.isTypeLegal(Scalar.getValueType()) && 14940 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 14941 Scalar = Scalar->getOperand(0); 14942 14943 EVT SclTy = Scalar->getValueType(0); 14944 14945 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 14946 return SDValue(); 14947 14948 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 14949 if (VNTNumElms < 2) 14950 return SDValue(); 14951 14952 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 14953 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 14954 return SDValue(); 14955 14956 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 14957 return DAG.getBitcast(VT, Res); 14958 } 14959 } 14960 14961 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 14962 // We have already tested above for an UNDEF only concatenation. 14963 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 14964 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 14965 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 14966 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 14967 }; 14968 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 14969 SmallVector<SDValue, 8> Opnds; 14970 EVT SVT = VT.getScalarType(); 14971 14972 EVT MinVT = SVT; 14973 if (!SVT.isFloatingPoint()) { 14974 // If BUILD_VECTOR are from built from integer, they may have different 14975 // operand types. Get the smallest type and truncate all operands to it. 14976 bool FoundMinVT = false; 14977 for (const SDValue &Op : N->ops()) 14978 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14979 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14980 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14981 FoundMinVT = true; 14982 } 14983 assert(FoundMinVT && "Concat vector type mismatch"); 14984 } 14985 14986 for (const SDValue &Op : N->ops()) { 14987 EVT OpVT = Op.getValueType(); 14988 unsigned NumElts = OpVT.getVectorNumElements(); 14989 14990 if (ISD::UNDEF == Op.getOpcode()) 14991 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14992 14993 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14994 if (SVT.isFloatingPoint()) { 14995 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14996 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14997 } else { 14998 for (unsigned i = 0; i != NumElts; ++i) 14999 Opnds.push_back( 15000 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 15001 } 15002 } 15003 } 15004 15005 assert(VT.getVectorNumElements() == Opnds.size() && 15006 "Concat vector type mismatch"); 15007 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 15008 } 15009 15010 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 15011 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 15012 return V; 15013 15014 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 15015 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15016 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 15017 return V; 15018 15019 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 15020 // nodes often generate nop CONCAT_VECTOR nodes. 15021 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 15022 // place the incoming vectors at the exact same location. 15023 SDValue SingleSource = SDValue(); 15024 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 15025 15026 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 15027 SDValue Op = N->getOperand(i); 15028 15029 if (Op.isUndef()) 15030 continue; 15031 15032 // Check if this is the identity extract: 15033 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 15034 return SDValue(); 15035 15036 // Find the single incoming vector for the extract_subvector. 15037 if (SingleSource.getNode()) { 15038 if (Op.getOperand(0) != SingleSource) 15039 return SDValue(); 15040 } else { 15041 SingleSource = Op.getOperand(0); 15042 15043 // Check the source type is the same as the type of the result. 15044 // If not, this concat may extend the vector, so we can not 15045 // optimize it away. 15046 if (SingleSource.getValueType() != N->getValueType(0)) 15047 return SDValue(); 15048 } 15049 15050 unsigned IdentityIndex = i * PartNumElem; 15051 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 15052 // The extract index must be constant. 15053 if (!CS) 15054 return SDValue(); 15055 15056 // Check that we are reading from the identity index. 15057 if (CS->getZExtValue() != IdentityIndex) 15058 return SDValue(); 15059 } 15060 15061 if (SingleSource.getNode()) 15062 return SingleSource; 15063 15064 return SDValue(); 15065 } 15066 15067 /// If we are extracting a subvector produced by a wide binary operator with at 15068 /// at least one operand that was the result of a vector concatenation, then try 15069 /// to use the narrow vector operands directly to avoid the concatenation and 15070 /// extraction. 15071 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 15072 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 15073 // some of these bailouts with other transforms. 15074 15075 // The extract index must be a constant, so we can map it to a concat operand. 15076 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15077 if (!ExtractIndex) 15078 return SDValue(); 15079 15080 // Only handle the case where we are doubling and then halving. A larger ratio 15081 // may require more than two narrow binops to replace the wide binop. 15082 EVT VT = Extract->getValueType(0); 15083 unsigned NumElems = VT.getVectorNumElements(); 15084 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 15085 "Extract index is not a multiple of the vector length."); 15086 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 15087 return SDValue(); 15088 15089 // We are looking for an optionally bitcasted wide vector binary operator 15090 // feeding an extract subvector. 15091 SDValue BinOp = peekThroughBitcast(Extract->getOperand(0)); 15092 15093 // TODO: The motivating case for this transform is an x86 AVX1 target. That 15094 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 15095 // flavors, but no other 256-bit integer support. This could be extended to 15096 // handle any binop, but that may require fixing/adding other folds to avoid 15097 // codegen regressions. 15098 unsigned BOpcode = BinOp.getOpcode(); 15099 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 15100 return SDValue(); 15101 15102 // The binop must be a vector type, so we can chop it in half. 15103 EVT WideBVT = BinOp.getValueType(); 15104 if (!WideBVT.isVector()) 15105 return SDValue(); 15106 15107 // Bail out if the target does not support a narrower version of the binop. 15108 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 15109 WideBVT.getVectorNumElements() / 2); 15110 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15111 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 15112 return SDValue(); 15113 15114 // Peek through bitcasts of the binary operator operands if needed. 15115 SDValue LHS = peekThroughBitcast(BinOp.getOperand(0)); 15116 SDValue RHS = peekThroughBitcast(BinOp.getOperand(1)); 15117 15118 // We need at least one concatenation operation of a binop operand to make 15119 // this transform worthwhile. The concat must double the input vector sizes. 15120 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 15121 bool ConcatL = 15122 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 15123 bool ConcatR = 15124 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 15125 if (!ConcatL && !ConcatR) 15126 return SDValue(); 15127 15128 // If one of the binop operands was not the result of a concat, we must 15129 // extract a half-sized operand for our new narrow binop. We can't just reuse 15130 // the original extract index operand because we may have bitcasted. 15131 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 15132 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 15133 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 15134 SDLoc DL(Extract); 15135 15136 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 15137 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 15138 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 15139 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 15140 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15141 BinOp.getOperand(0), 15142 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15143 15144 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 15145 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 15146 BinOp.getOperand(1), 15147 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 15148 15149 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 15150 return DAG.getBitcast(VT, NarrowBinOp); 15151 } 15152 15153 /// If we are extracting a subvector from a wide vector load, convert to a 15154 /// narrow load to eliminate the extraction: 15155 /// (extract_subvector (load wide vector)) --> (load narrow vector) 15156 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 15157 // TODO: Add support for big-endian. The offset calculation must be adjusted. 15158 if (DAG.getDataLayout().isBigEndian()) 15159 return SDValue(); 15160 15161 // TODO: The one-use check is overly conservative. Check the cost of the 15162 // extract instead or remove that condition entirely. 15163 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 15164 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 15165 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 15166 !ExtIdx) 15167 return SDValue(); 15168 15169 // The narrow load will be offset from the base address of the old load if 15170 // we are extracting from something besides index 0 (little-endian). 15171 EVT VT = Extract->getValueType(0); 15172 SDLoc DL(Extract); 15173 SDValue BaseAddr = Ld->getOperand(1); 15174 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 15175 15176 // TODO: Use "BaseIndexOffset" to make this more effective. 15177 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 15178 MachineFunction &MF = DAG.getMachineFunction(); 15179 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 15180 VT.getStoreSize()); 15181 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 15182 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 15183 return NewLd; 15184 } 15185 15186 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 15187 EVT NVT = N->getValueType(0); 15188 SDValue V = N->getOperand(0); 15189 15190 // Extract from UNDEF is UNDEF. 15191 if (V.isUndef()) 15192 return DAG.getUNDEF(NVT); 15193 15194 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 15195 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 15196 return NarrowLoad; 15197 15198 // Combine: 15199 // (extract_subvec (concat V1, V2, ...), i) 15200 // Into: 15201 // Vi if possible 15202 // Only operand 0 is checked as 'concat' assumes all inputs of the same 15203 // type. 15204 if (V->getOpcode() == ISD::CONCAT_VECTORS && 15205 isa<ConstantSDNode>(N->getOperand(1)) && 15206 V->getOperand(0).getValueType() == NVT) { 15207 unsigned Idx = N->getConstantOperandVal(1); 15208 unsigned NumElems = NVT.getVectorNumElements(); 15209 assert((Idx % NumElems) == 0 && 15210 "IDX in concat is not a multiple of the result vector length."); 15211 return V->getOperand(Idx / NumElems); 15212 } 15213 15214 // Skip bitcasting 15215 V = peekThroughBitcast(V); 15216 15217 // If the input is a build vector. Try to make a smaller build vector. 15218 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15219 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 15220 EVT InVT = V->getValueType(0); 15221 unsigned ExtractSize = NVT.getSizeInBits(); 15222 unsigned EltSize = InVT.getScalarSizeInBits(); 15223 // Only do this if we won't split any elements. 15224 if (ExtractSize % EltSize == 0) { 15225 unsigned NumElems = ExtractSize / EltSize; 15226 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(), 15227 InVT.getVectorElementType(), NumElems); 15228 if ((!LegalOperations || 15229 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) && 15230 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 15231 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 15232 EltSize; 15233 15234 // Extract the pieces from the original build_vector. 15235 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 15236 makeArrayRef(V->op_begin() + IdxVal, 15237 NumElems)); 15238 return DAG.getBitcast(NVT, BuildVec); 15239 } 15240 } 15241 } 15242 } 15243 15244 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 15245 // Handle only simple case where vector being inserted and vector 15246 // being extracted are of same size. 15247 EVT SmallVT = V->getOperand(1).getValueType(); 15248 if (!NVT.bitsEq(SmallVT)) 15249 return SDValue(); 15250 15251 // Only handle cases where both indexes are constants. 15252 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15253 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15254 15255 if (InsIdx && ExtIdx) { 15256 // Combine: 15257 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 15258 // Into: 15259 // indices are equal or bit offsets are equal => V1 15260 // otherwise => (extract_subvec V1, ExtIdx) 15261 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 15262 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 15263 return DAG.getBitcast(NVT, V->getOperand(1)); 15264 return DAG.getNode( 15265 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 15266 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 15267 N->getOperand(1)); 15268 } 15269 } 15270 15271 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 15272 return NarrowBOp; 15273 15274 return SDValue(); 15275 } 15276 15277 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 15278 SDValue V, SelectionDAG &DAG) { 15279 SDLoc DL(V); 15280 EVT VT = V.getValueType(); 15281 15282 switch (V.getOpcode()) { 15283 default: 15284 return V; 15285 15286 case ISD::CONCAT_VECTORS: { 15287 EVT OpVT = V->getOperand(0).getValueType(); 15288 int OpSize = OpVT.getVectorNumElements(); 15289 SmallBitVector OpUsedElements(OpSize, false); 15290 bool FoundSimplification = false; 15291 SmallVector<SDValue, 4> NewOps; 15292 NewOps.reserve(V->getNumOperands()); 15293 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 15294 SDValue Op = V->getOperand(i); 15295 bool OpUsed = false; 15296 for (int j = 0; j < OpSize; ++j) 15297 if (UsedElements[i * OpSize + j]) { 15298 OpUsedElements[j] = true; 15299 OpUsed = true; 15300 } 15301 NewOps.push_back( 15302 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 15303 : DAG.getUNDEF(OpVT)); 15304 FoundSimplification |= Op == NewOps.back(); 15305 OpUsedElements.reset(); 15306 } 15307 if (FoundSimplification) 15308 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 15309 return V; 15310 } 15311 15312 case ISD::INSERT_SUBVECTOR: { 15313 SDValue BaseV = V->getOperand(0); 15314 SDValue SubV = V->getOperand(1); 15315 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 15316 if (!IdxN) 15317 return V; 15318 15319 int SubSize = SubV.getValueType().getVectorNumElements(); 15320 int Idx = IdxN->getZExtValue(); 15321 bool SubVectorUsed = false; 15322 SmallBitVector SubUsedElements(SubSize, false); 15323 for (int i = 0; i < SubSize; ++i) 15324 if (UsedElements[i + Idx]) { 15325 SubVectorUsed = true; 15326 SubUsedElements[i] = true; 15327 UsedElements[i + Idx] = false; 15328 } 15329 15330 // Now recurse on both the base and sub vectors. 15331 SDValue SimplifiedSubV = 15332 SubVectorUsed 15333 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 15334 : DAG.getUNDEF(SubV.getValueType()); 15335 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 15336 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 15337 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 15338 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 15339 return V; 15340 } 15341 } 15342 } 15343 15344 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 15345 SDValue N1, SelectionDAG &DAG) { 15346 EVT VT = SVN->getValueType(0); 15347 int NumElts = VT.getVectorNumElements(); 15348 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 15349 for (int M : SVN->getMask()) 15350 if (M >= 0 && M < NumElts) 15351 N0UsedElements[M] = true; 15352 else if (M >= NumElts) 15353 N1UsedElements[M - NumElts] = true; 15354 15355 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 15356 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 15357 if (S0 == N0 && S1 == N1) 15358 return SDValue(); 15359 15360 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 15361 } 15362 15363 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0, 15364 SDValue N1, SelectionDAG &DAG) { 15365 auto isUndefElt = [](SDValue V, int Idx) { 15366 // TODO - handle more cases as required. 15367 if (V.getOpcode() == ISD::BUILD_VECTOR) 15368 return V.getOperand(Idx).isUndef(); 15369 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 15370 return (Idx != 0) || V.getOperand(0).isUndef(); 15371 return false; 15372 }; 15373 15374 EVT VT = SVN->getValueType(0); 15375 unsigned NumElts = VT.getVectorNumElements(); 15376 15377 bool Changed = false; 15378 SmallVector<int, 8> NewMask; 15379 for (unsigned i = 0; i != NumElts; ++i) { 15380 int Idx = SVN->getMaskElt(i); 15381 if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) || 15382 ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) { 15383 Changed = true; 15384 Idx = -1; 15385 } 15386 NewMask.push_back(Idx); 15387 } 15388 if (Changed) 15389 return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask); 15390 15391 return SDValue(); 15392 } 15393 15394 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 15395 // or turn a shuffle of a single concat into simpler shuffle then concat. 15396 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 15397 EVT VT = N->getValueType(0); 15398 unsigned NumElts = VT.getVectorNumElements(); 15399 15400 SDValue N0 = N->getOperand(0); 15401 SDValue N1 = N->getOperand(1); 15402 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15403 15404 SmallVector<SDValue, 4> Ops; 15405 EVT ConcatVT = N0.getOperand(0).getValueType(); 15406 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 15407 unsigned NumConcats = NumElts / NumElemsPerConcat; 15408 15409 // Special case: shuffle(concat(A,B)) can be more efficiently represented 15410 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 15411 // half vector elements. 15412 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 15413 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 15414 SVN->getMask().end(), [](int i) { return i == -1; })) { 15415 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 15416 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 15417 N1 = DAG.getUNDEF(ConcatVT); 15418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 15419 } 15420 15421 // Look at every vector that's inserted. We're looking for exact 15422 // subvector-sized copies from a concatenated vector 15423 for (unsigned I = 0; I != NumConcats; ++I) { 15424 // Make sure we're dealing with a copy. 15425 unsigned Begin = I * NumElemsPerConcat; 15426 bool AllUndef = true, NoUndef = true; 15427 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 15428 if (SVN->getMaskElt(J) >= 0) 15429 AllUndef = false; 15430 else 15431 NoUndef = false; 15432 } 15433 15434 if (NoUndef) { 15435 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 15436 return SDValue(); 15437 15438 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 15439 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 15440 return SDValue(); 15441 15442 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 15443 if (FirstElt < N0.getNumOperands()) 15444 Ops.push_back(N0.getOperand(FirstElt)); 15445 else 15446 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 15447 15448 } else if (AllUndef) { 15449 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 15450 } else { // Mixed with general masks and undefs, can't do optimization. 15451 return SDValue(); 15452 } 15453 } 15454 15455 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15456 } 15457 15458 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15459 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15460 // 15461 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 15462 // a simplification in some sense, but it isn't appropriate in general: some 15463 // BUILD_VECTORs are substantially cheaper than others. The general case 15464 // of a BUILD_VECTOR requires inserting each element individually (or 15465 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 15466 // all constants is a single constant pool load. A BUILD_VECTOR where each 15467 // element is identical is a splat. A BUILD_VECTOR where most of the operands 15468 // are undef lowers to a small number of element insertions. 15469 // 15470 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 15471 // We don't fold shuffles where one side is a non-zero constant, and we don't 15472 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 15473 // non-constant operands. This seems to work out reasonably well in practice. 15474 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 15475 SelectionDAG &DAG, 15476 const TargetLowering &TLI) { 15477 EVT VT = SVN->getValueType(0); 15478 unsigned NumElts = VT.getVectorNumElements(); 15479 SDValue N0 = SVN->getOperand(0); 15480 SDValue N1 = SVN->getOperand(1); 15481 15482 if (!N0->hasOneUse() || !N1->hasOneUse()) 15483 return SDValue(); 15484 15485 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 15486 // discussed above. 15487 if (!N1.isUndef()) { 15488 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 15489 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 15490 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 15491 return SDValue(); 15492 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 15493 return SDValue(); 15494 } 15495 15496 // If both inputs are splats of the same value then we can safely merge this 15497 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 15498 bool IsSplat = false; 15499 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 15500 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 15501 if (BV0 && BV1) 15502 if (SDValue Splat0 = BV0->getSplatValue()) 15503 IsSplat = (Splat0 == BV1->getSplatValue()); 15504 15505 SmallVector<SDValue, 8> Ops; 15506 SmallSet<SDValue, 16> DuplicateOps; 15507 for (int M : SVN->getMask()) { 15508 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 15509 if (M >= 0) { 15510 int Idx = M < (int)NumElts ? M : M - NumElts; 15511 SDValue &S = (M < (int)NumElts ? N0 : N1); 15512 if (S.getOpcode() == ISD::BUILD_VECTOR) { 15513 Op = S.getOperand(Idx); 15514 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 15515 assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index."); 15516 Op = S.getOperand(0); 15517 } else { 15518 // Operand can't be combined - bail out. 15519 return SDValue(); 15520 } 15521 } 15522 15523 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 15524 // generating a splat; semantically, this is fine, but it's likely to 15525 // generate low-quality code if the target can't reconstruct an appropriate 15526 // shuffle. 15527 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15528 if (!IsSplat && !DuplicateOps.insert(Op).second) 15529 return SDValue(); 15530 15531 Ops.push_back(Op); 15532 } 15533 15534 // BUILD_VECTOR requires all inputs to be of the same type, find the 15535 // maximum type and extend them all. 15536 EVT SVT = VT.getScalarType(); 15537 if (SVT.isInteger()) 15538 for (SDValue &Op : Ops) 15539 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15540 if (SVT != VT.getScalarType()) 15541 for (SDValue &Op : Ops) 15542 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15543 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15544 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15545 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15546 } 15547 15548 // Match shuffles that can be converted to any_vector_extend_in_reg. 15549 // This is often generated during legalization. 15550 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15551 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15552 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15553 SelectionDAG &DAG, 15554 const TargetLowering &TLI, 15555 bool LegalOperations, 15556 bool LegalTypes) { 15557 EVT VT = SVN->getValueType(0); 15558 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15559 15560 // TODO Add support for big-endian when we have a test case. 15561 if (!VT.isInteger() || IsBigEndian) 15562 return SDValue(); 15563 15564 unsigned NumElts = VT.getVectorNumElements(); 15565 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15566 ArrayRef<int> Mask = SVN->getMask(); 15567 SDValue N0 = SVN->getOperand(0); 15568 15569 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15570 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15571 for (unsigned i = 0; i != NumElts; ++i) { 15572 if (Mask[i] < 0) 15573 continue; 15574 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15575 continue; 15576 return false; 15577 } 15578 return true; 15579 }; 15580 15581 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15582 // power-of-2 extensions as they are the most likely. 15583 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15584 // Check for non power of 2 vector sizes 15585 if (NumElts % Scale != 0) 15586 continue; 15587 if (!isAnyExtend(Scale)) 15588 continue; 15589 15590 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15591 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15592 if (!LegalTypes || TLI.isTypeLegal(OutVT)) 15593 if (!LegalOperations || 15594 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15595 return DAG.getBitcast(VT, 15596 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15597 } 15598 15599 return SDValue(); 15600 } 15601 15602 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15603 // each source element of a large type into the lowest elements of a smaller 15604 // destination type. This is often generated during legalization. 15605 // If the source node itself was a '*_extend_vector_inreg' node then we should 15606 // then be able to remove it. 15607 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15608 SelectionDAG &DAG) { 15609 EVT VT = SVN->getValueType(0); 15610 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15611 15612 // TODO Add support for big-endian when we have a test case. 15613 if (!VT.isInteger() || IsBigEndian) 15614 return SDValue(); 15615 15616 SDValue N0 = peekThroughBitcast(SVN->getOperand(0)); 15617 15618 unsigned Opcode = N0.getOpcode(); 15619 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15620 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15621 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15622 return SDValue(); 15623 15624 SDValue N00 = N0.getOperand(0); 15625 ArrayRef<int> Mask = SVN->getMask(); 15626 unsigned NumElts = VT.getVectorNumElements(); 15627 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15628 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15629 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 15630 15631 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 15632 return SDValue(); 15633 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 15634 15635 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15636 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15637 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15638 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15639 for (unsigned i = 0; i != NumElts; ++i) { 15640 if (Mask[i] < 0) 15641 continue; 15642 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15643 continue; 15644 return false; 15645 } 15646 return true; 15647 }; 15648 15649 // At the moment we just handle the case where we've truncated back to the 15650 // same size as before the extension. 15651 // TODO: handle more extension/truncation cases as cases arise. 15652 if (EltSizeInBits != ExtSrcSizeInBits) 15653 return SDValue(); 15654 15655 // We can remove *extend_vector_inreg only if the truncation happens at 15656 // the same scale as the extension. 15657 if (isTruncate(ExtScale)) 15658 return DAG.getBitcast(VT, N00); 15659 15660 return SDValue(); 15661 } 15662 15663 // Combine shuffles of splat-shuffles of the form: 15664 // shuffle (shuffle V, undef, splat-mask), undef, M 15665 // If splat-mask contains undef elements, we need to be careful about 15666 // introducing undef's in the folded mask which are not the result of composing 15667 // the masks of the shuffles. 15668 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15669 ShuffleVectorSDNode *Splat, 15670 SelectionDAG &DAG) { 15671 ArrayRef<int> SplatMask = Splat->getMask(); 15672 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15673 15674 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15675 // every undef mask element in the splat-shuffle has a corresponding undef 15676 // element in the user-shuffle's mask or if the composition of mask elements 15677 // would result in undef. 15678 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15679 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15680 // In this case it is not legal to simplify to the splat-shuffle because we 15681 // may be exposing the users of the shuffle an undef element at index 1 15682 // which was not there before the combine. 15683 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15684 // In this case the composition of masks yields SplatMask, so it's ok to 15685 // simplify to the splat-shuffle. 15686 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15687 // In this case the composed mask includes all undef elements of SplatMask 15688 // and in addition sets element zero to undef. It is safe to simplify to 15689 // the splat-shuffle. 15690 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15691 ArrayRef<int> SplatMask) { 15692 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15693 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15694 SplatMask[UserMask[i]] != -1) 15695 return false; 15696 return true; 15697 }; 15698 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15699 return SDValue(Splat, 0); 15700 15701 // Create a new shuffle with a mask that is composed of the two shuffles' 15702 // masks. 15703 SmallVector<int, 32> NewMask; 15704 for (int Idx : UserMask) 15705 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15706 15707 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15708 Splat->getOperand(0), Splat->getOperand(1), 15709 NewMask); 15710 } 15711 15712 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15713 EVT VT = N->getValueType(0); 15714 unsigned NumElts = VT.getVectorNumElements(); 15715 15716 SDValue N0 = N->getOperand(0); 15717 SDValue N1 = N->getOperand(1); 15718 15719 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15720 15721 // Canonicalize shuffle undef, undef -> undef 15722 if (N0.isUndef() && N1.isUndef()) 15723 return DAG.getUNDEF(VT); 15724 15725 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15726 15727 // Canonicalize shuffle v, v -> v, undef 15728 if (N0 == N1) { 15729 SmallVector<int, 8> NewMask; 15730 for (unsigned i = 0; i != NumElts; ++i) { 15731 int Idx = SVN->getMaskElt(i); 15732 if (Idx >= (int)NumElts) Idx -= NumElts; 15733 NewMask.push_back(Idx); 15734 } 15735 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 15736 } 15737 15738 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 15739 if (N0.isUndef()) 15740 return DAG.getCommutedVectorShuffle(*SVN); 15741 15742 // Remove references to rhs if it is undef 15743 if (N1.isUndef()) { 15744 bool Changed = false; 15745 SmallVector<int, 8> NewMask; 15746 for (unsigned i = 0; i != NumElts; ++i) { 15747 int Idx = SVN->getMaskElt(i); 15748 if (Idx >= (int)NumElts) { 15749 Idx = -1; 15750 Changed = true; 15751 } 15752 NewMask.push_back(Idx); 15753 } 15754 if (Changed) 15755 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 15756 } 15757 15758 // Simplify shuffle mask if a referenced element is UNDEF. 15759 if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG)) 15760 return V; 15761 15762 // A shuffle of a single vector that is a splat can always be folded. 15763 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 15764 if (N1->isUndef() && N0Shuf->isSplat()) 15765 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 15766 15767 // If it is a splat, check if the argument vector is another splat or a 15768 // build_vector. 15769 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 15770 SDNode *V = N0.getNode(); 15771 15772 // If this is a bit convert that changes the element type of the vector but 15773 // not the number of vector elements, look through it. Be careful not to 15774 // look though conversions that change things like v4f32 to v2f64. 15775 if (V->getOpcode() == ISD::BITCAST) { 15776 SDValue ConvInput = V->getOperand(0); 15777 if (ConvInput.getValueType().isVector() && 15778 ConvInput.getValueType().getVectorNumElements() == NumElts) 15779 V = ConvInput.getNode(); 15780 } 15781 15782 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15783 assert(V->getNumOperands() == NumElts && 15784 "BUILD_VECTOR has wrong number of operands"); 15785 SDValue Base; 15786 bool AllSame = true; 15787 for (unsigned i = 0; i != NumElts; ++i) { 15788 if (!V->getOperand(i).isUndef()) { 15789 Base = V->getOperand(i); 15790 break; 15791 } 15792 } 15793 // Splat of <u, u, u, u>, return <u, u, u, u> 15794 if (!Base.getNode()) 15795 return N0; 15796 for (unsigned i = 0; i != NumElts; ++i) { 15797 if (V->getOperand(i) != Base) { 15798 AllSame = false; 15799 break; 15800 } 15801 } 15802 // Splat of <x, x, x, x>, return <x, x, x, x> 15803 if (AllSame) 15804 return N0; 15805 15806 // Canonicalize any other splat as a build_vector. 15807 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 15808 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 15809 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 15810 15811 // We may have jumped through bitcasts, so the type of the 15812 // BUILD_VECTOR may not match the type of the shuffle. 15813 if (V->getValueType(0) != VT) 15814 NewBV = DAG.getBitcast(VT, NewBV); 15815 return NewBV; 15816 } 15817 } 15818 15819 // There are various patterns used to build up a vector from smaller vectors, 15820 // subvectors, or elements. Scan chains of these and replace unused insertions 15821 // or components with undef. 15822 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 15823 return S; 15824 15825 // Match shuffles that can be converted to any_vector_extend_in_reg. 15826 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes)) 15827 return V; 15828 15829 // Combine "truncate_vector_in_reg" style shuffles. 15830 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 15831 return V; 15832 15833 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 15834 Level < AfterLegalizeVectorOps && 15835 (N1.isUndef() || 15836 (N1.getOpcode() == ISD::CONCAT_VECTORS && 15837 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 15838 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 15839 return V; 15840 } 15841 15842 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15843 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15844 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15845 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 15846 return Res; 15847 15848 // If this shuffle only has a single input that is a bitcasted shuffle, 15849 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 15850 // back to their original types. 15851 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 15852 N1.isUndef() && Level < AfterLegalizeVectorOps && 15853 TLI.isTypeLegal(VT)) { 15854 15855 // Peek through the bitcast only if there is one user. 15856 SDValue BC0 = N0; 15857 while (BC0.getOpcode() == ISD::BITCAST) { 15858 if (!BC0.hasOneUse()) 15859 break; 15860 BC0 = BC0.getOperand(0); 15861 } 15862 15863 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 15864 if (Scale == 1) 15865 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 15866 15867 SmallVector<int, 8> NewMask; 15868 for (int M : Mask) 15869 for (int s = 0; s != Scale; ++s) 15870 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 15871 return NewMask; 15872 }; 15873 15874 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 15875 EVT SVT = VT.getScalarType(); 15876 EVT InnerVT = BC0->getValueType(0); 15877 EVT InnerSVT = InnerVT.getScalarType(); 15878 15879 // Determine which shuffle works with the smaller scalar type. 15880 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 15881 EVT ScaleSVT = ScaleVT.getScalarType(); 15882 15883 if (TLI.isTypeLegal(ScaleVT) && 15884 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 15885 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 15886 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15887 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15888 15889 // Scale the shuffle masks to the smaller scalar type. 15890 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 15891 SmallVector<int, 8> InnerMask = 15892 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 15893 SmallVector<int, 8> OuterMask = 15894 ScaleShuffleMask(SVN->getMask(), OuterScale); 15895 15896 // Merge the shuffle masks. 15897 SmallVector<int, 8> NewMask; 15898 for (int M : OuterMask) 15899 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 15900 15901 // Test for shuffle mask legality over both commutations. 15902 SDValue SV0 = BC0->getOperand(0); 15903 SDValue SV1 = BC0->getOperand(1); 15904 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15905 if (!LegalMask) { 15906 std::swap(SV0, SV1); 15907 ShuffleVectorSDNode::commuteMask(NewMask); 15908 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15909 } 15910 15911 if (LegalMask) { 15912 SV0 = DAG.getBitcast(ScaleVT, SV0); 15913 SV1 = DAG.getBitcast(ScaleVT, SV1); 15914 return DAG.getBitcast( 15915 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 15916 } 15917 } 15918 } 15919 } 15920 15921 // Canonicalize shuffles according to rules: 15922 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 15923 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 15924 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 15925 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 15926 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 15927 TLI.isTypeLegal(VT)) { 15928 // The incoming shuffle must be of the same type as the result of the 15929 // current shuffle. 15930 assert(N1->getOperand(0).getValueType() == VT && 15931 "Shuffle types don't match"); 15932 15933 SDValue SV0 = N1->getOperand(0); 15934 SDValue SV1 = N1->getOperand(1); 15935 bool HasSameOp0 = N0 == SV0; 15936 bool IsSV1Undef = SV1.isUndef(); 15937 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 15938 // Commute the operands of this shuffle so that next rule 15939 // will trigger. 15940 return DAG.getCommutedVectorShuffle(*SVN); 15941 } 15942 15943 // Try to fold according to rules: 15944 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15945 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15946 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15947 // Don't try to fold shuffles with illegal type. 15948 // Only fold if this shuffle is the only user of the other shuffle. 15949 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 15950 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 15951 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 15952 15953 // Don't try to fold splats; they're likely to simplify somehow, or they 15954 // might be free. 15955 if (OtherSV->isSplat()) 15956 return SDValue(); 15957 15958 // The incoming shuffle must be of the same type as the result of the 15959 // current shuffle. 15960 assert(OtherSV->getOperand(0).getValueType() == VT && 15961 "Shuffle types don't match"); 15962 15963 SDValue SV0, SV1; 15964 SmallVector<int, 4> Mask; 15965 // Compute the combined shuffle mask for a shuffle with SV0 as the first 15966 // operand, and SV1 as the second operand. 15967 for (unsigned i = 0; i != NumElts; ++i) { 15968 int Idx = SVN->getMaskElt(i); 15969 if (Idx < 0) { 15970 // Propagate Undef. 15971 Mask.push_back(Idx); 15972 continue; 15973 } 15974 15975 SDValue CurrentVec; 15976 if (Idx < (int)NumElts) { 15977 // This shuffle index refers to the inner shuffle N0. Lookup the inner 15978 // shuffle mask to identify which vector is actually referenced. 15979 Idx = OtherSV->getMaskElt(Idx); 15980 if (Idx < 0) { 15981 // Propagate Undef. 15982 Mask.push_back(Idx); 15983 continue; 15984 } 15985 15986 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 15987 : OtherSV->getOperand(1); 15988 } else { 15989 // This shuffle index references an element within N1. 15990 CurrentVec = N1; 15991 } 15992 15993 // Simple case where 'CurrentVec' is UNDEF. 15994 if (CurrentVec.isUndef()) { 15995 Mask.push_back(-1); 15996 continue; 15997 } 15998 15999 // Canonicalize the shuffle index. We don't know yet if CurrentVec 16000 // will be the first or second operand of the combined shuffle. 16001 Idx = Idx % NumElts; 16002 if (!SV0.getNode() || SV0 == CurrentVec) { 16003 // Ok. CurrentVec is the left hand side. 16004 // Update the mask accordingly. 16005 SV0 = CurrentVec; 16006 Mask.push_back(Idx); 16007 continue; 16008 } 16009 16010 // Bail out if we cannot convert the shuffle pair into a single shuffle. 16011 if (SV1.getNode() && SV1 != CurrentVec) 16012 return SDValue(); 16013 16014 // Ok. CurrentVec is the right hand side. 16015 // Update the mask accordingly. 16016 SV1 = CurrentVec; 16017 Mask.push_back(Idx + NumElts); 16018 } 16019 16020 // Check if all indices in Mask are Undef. In case, propagate Undef. 16021 bool isUndefMask = true; 16022 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 16023 isUndefMask &= Mask[i] < 0; 16024 16025 if (isUndefMask) 16026 return DAG.getUNDEF(VT); 16027 16028 if (!SV0.getNode()) 16029 SV0 = DAG.getUNDEF(VT); 16030 if (!SV1.getNode()) 16031 SV1 = DAG.getUNDEF(VT); 16032 16033 // Avoid introducing shuffles with illegal mask. 16034 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 16035 ShuffleVectorSDNode::commuteMask(Mask); 16036 16037 if (!TLI.isShuffleMaskLegal(Mask, VT)) 16038 return SDValue(); 16039 16040 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 16041 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 16042 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 16043 std::swap(SV0, SV1); 16044 } 16045 16046 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 16047 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 16048 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 16049 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 16050 } 16051 16052 return SDValue(); 16053 } 16054 16055 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 16056 SDValue InVal = N->getOperand(0); 16057 EVT VT = N->getValueType(0); 16058 16059 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 16060 // with a VECTOR_SHUFFLE and possible truncate. 16061 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 16062 SDValue InVec = InVal->getOperand(0); 16063 SDValue EltNo = InVal->getOperand(1); 16064 auto InVecT = InVec.getValueType(); 16065 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 16066 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 16067 int Elt = C0->getZExtValue(); 16068 NewMask[0] = Elt; 16069 SDValue Val; 16070 // If we have an implict truncate do truncate here as long as it's legal. 16071 // if it's not legal, this should 16072 if (VT.getScalarType() != InVal.getValueType() && 16073 InVal.getValueType().isScalarInteger() && 16074 isTypeLegal(VT.getScalarType())) { 16075 Val = 16076 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 16077 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 16078 } 16079 if (VT.getScalarType() == InVecT.getScalarType() && 16080 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 16081 TLI.isShuffleMaskLegal(NewMask, VT)) { 16082 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 16083 DAG.getUNDEF(InVecT), NewMask); 16084 // If the initial vector is the correct size this shuffle is a 16085 // valid result. 16086 if (VT == InVecT) 16087 return Val; 16088 // If not we must truncate the vector. 16089 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 16090 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16091 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 16092 EVT SubVT = 16093 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 16094 VT.getVectorNumElements()); 16095 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 16096 ZeroIdx); 16097 return Val; 16098 } 16099 } 16100 } 16101 } 16102 16103 return SDValue(); 16104 } 16105 16106 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 16107 EVT VT = N->getValueType(0); 16108 SDValue N0 = N->getOperand(0); 16109 SDValue N1 = N->getOperand(1); 16110 SDValue N2 = N->getOperand(2); 16111 16112 // If inserting an UNDEF, just return the original vector. 16113 if (N1.isUndef()) 16114 return N0; 16115 16116 // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow 16117 // us to pull BITCASTs from input to output. 16118 if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR) 16119 if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode())) 16120 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2); 16121 16122 // If this is an insert of an extracted vector into an undef vector, we can 16123 // just use the input to the extract. 16124 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 16125 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 16126 return N1.getOperand(0); 16127 16128 // If we are inserting a bitcast value into an undef, with the same 16129 // number of elements, just use the bitcast input of the extract. 16130 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 16131 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 16132 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 16133 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 16134 N1.getOperand(0).getOperand(1) == N2 && 16135 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 16136 VT.getVectorNumElements()) { 16137 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 16138 } 16139 16140 // If both N1 and N2 are bitcast values on which insert_subvector 16141 // would makes sense, pull the bitcast through. 16142 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 16143 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 16144 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 16145 SDValue CN0 = N0.getOperand(0); 16146 SDValue CN1 = N1.getOperand(0); 16147 if (CN0.getValueType().getVectorElementType() == 16148 CN1.getValueType().getVectorElementType() && 16149 CN0.getValueType().getVectorNumElements() == 16150 VT.getVectorNumElements()) { 16151 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 16152 CN0.getValueType(), CN0, CN1, N2); 16153 return DAG.getBitcast(VT, NewINSERT); 16154 } 16155 } 16156 16157 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 16158 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 16159 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 16160 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 16161 N0.getOperand(1).getValueType() == N1.getValueType() && 16162 N0.getOperand(2) == N2) 16163 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 16164 N1, N2); 16165 16166 if (!isa<ConstantSDNode>(N2)) 16167 return SDValue(); 16168 16169 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 16170 16171 // Canonicalize insert_subvector dag nodes. 16172 // Example: 16173 // (insert_subvector (insert_subvector A, Idx0), Idx1) 16174 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 16175 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 16176 N1.getValueType() == N0.getOperand(1).getValueType() && 16177 isa<ConstantSDNode>(N0.getOperand(2))) { 16178 unsigned OtherIdx = N0.getConstantOperandVal(2); 16179 if (InsIdx < OtherIdx) { 16180 // Swap nodes. 16181 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 16182 N0.getOperand(0), N1, N2); 16183 AddToWorklist(NewOp.getNode()); 16184 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 16185 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 16186 } 16187 } 16188 16189 // If the input vector is a concatenation, and the insert replaces 16190 // one of the pieces, we can optimize into a single concat_vectors. 16191 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 16192 N0.getOperand(0).getValueType() == N1.getValueType()) { 16193 unsigned Factor = N1.getValueType().getVectorNumElements(); 16194 16195 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 16196 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 16197 16198 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 16199 } 16200 16201 return SDValue(); 16202 } 16203 16204 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 16205 SDValue N0 = N->getOperand(0); 16206 16207 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 16208 if (N0->getOpcode() == ISD::FP16_TO_FP) 16209 return N0->getOperand(0); 16210 16211 return SDValue(); 16212 } 16213 16214 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 16215 SDValue N0 = N->getOperand(0); 16216 16217 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 16218 if (N0->getOpcode() == ISD::AND) { 16219 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 16220 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 16221 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 16222 N0.getOperand(0)); 16223 } 16224 } 16225 16226 return SDValue(); 16227 } 16228 16229 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 16230 /// with the destination vector and a zero vector. 16231 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 16232 /// vector_shuffle V, Zero, <0, 4, 2, 4> 16233 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 16234 EVT VT = N->getValueType(0); 16235 SDValue LHS = N->getOperand(0); 16236 SDValue RHS = peekThroughBitcast(N->getOperand(1)); 16237 SDLoc DL(N); 16238 16239 // Make sure we're not running after operation legalization where it 16240 // may have custom lowered the vector shuffles. 16241 if (LegalOperations) 16242 return SDValue(); 16243 16244 if (N->getOpcode() != ISD::AND) 16245 return SDValue(); 16246 16247 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 16248 return SDValue(); 16249 16250 EVT RVT = RHS.getValueType(); 16251 unsigned NumElts = RHS.getNumOperands(); 16252 16253 // Attempt to create a valid clear mask, splitting the mask into 16254 // sub elements and checking to see if each is 16255 // all zeros or all ones - suitable for shuffle masking. 16256 auto BuildClearMask = [&](int Split) { 16257 int NumSubElts = NumElts * Split; 16258 int NumSubBits = RVT.getScalarSizeInBits() / Split; 16259 16260 SmallVector<int, 8> Indices; 16261 for (int i = 0; i != NumSubElts; ++i) { 16262 int EltIdx = i / Split; 16263 int SubIdx = i % Split; 16264 SDValue Elt = RHS.getOperand(EltIdx); 16265 if (Elt.isUndef()) { 16266 Indices.push_back(-1); 16267 continue; 16268 } 16269 16270 APInt Bits; 16271 if (isa<ConstantSDNode>(Elt)) 16272 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 16273 else if (isa<ConstantFPSDNode>(Elt)) 16274 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 16275 else 16276 return SDValue(); 16277 16278 // Extract the sub element from the constant bit mask. 16279 if (DAG.getDataLayout().isBigEndian()) { 16280 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 16281 } else { 16282 Bits.lshrInPlace(SubIdx * NumSubBits); 16283 } 16284 16285 if (Split > 1) 16286 Bits = Bits.trunc(NumSubBits); 16287 16288 if (Bits.isAllOnesValue()) 16289 Indices.push_back(i); 16290 else if (Bits == 0) 16291 Indices.push_back(i + NumSubElts); 16292 else 16293 return SDValue(); 16294 } 16295 16296 // Let's see if the target supports this vector_shuffle. 16297 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 16298 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 16299 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 16300 return SDValue(); 16301 16302 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 16303 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 16304 DAG.getBitcast(ClearVT, LHS), 16305 Zero, Indices)); 16306 }; 16307 16308 // Determine maximum split level (byte level masking). 16309 int MaxSplit = 1; 16310 if (RVT.getScalarSizeInBits() % 8 == 0) 16311 MaxSplit = RVT.getScalarSizeInBits() / 8; 16312 16313 for (int Split = 1; Split <= MaxSplit; ++Split) 16314 if (RVT.getScalarSizeInBits() % Split == 0) 16315 if (SDValue S = BuildClearMask(Split)) 16316 return S; 16317 16318 return SDValue(); 16319 } 16320 16321 /// Visit a binary vector operation, like ADD. 16322 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 16323 assert(N->getValueType(0).isVector() && 16324 "SimplifyVBinOp only works on vectors!"); 16325 16326 SDValue LHS = N->getOperand(0); 16327 SDValue RHS = N->getOperand(1); 16328 SDValue Ops[] = {LHS, RHS}; 16329 16330 // See if we can constant fold the vector operation. 16331 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 16332 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 16333 return Fold; 16334 16335 // Try to convert a constant mask AND into a shuffle clear mask. 16336 if (SDValue Shuffle = XformToShuffleWithZero(N)) 16337 return Shuffle; 16338 16339 // Type legalization might introduce new shuffles in the DAG. 16340 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 16341 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 16342 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 16343 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 16344 LHS.getOperand(1).isUndef() && 16345 RHS.getOperand(1).isUndef()) { 16346 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 16347 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 16348 16349 if (SVN0->getMask().equals(SVN1->getMask())) { 16350 EVT VT = N->getValueType(0); 16351 SDValue UndefVector = LHS.getOperand(1); 16352 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 16353 LHS.getOperand(0), RHS.getOperand(0), 16354 N->getFlags()); 16355 AddUsersToWorklist(N); 16356 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 16357 SVN0->getMask()); 16358 } 16359 } 16360 16361 return SDValue(); 16362 } 16363 16364 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 16365 SDValue N2) { 16366 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 16367 16368 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 16369 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 16370 16371 // If we got a simplified select_cc node back from SimplifySelectCC, then 16372 // break it down into a new SETCC node, and a new SELECT node, and then return 16373 // the SELECT node, since we were called with a SELECT node. 16374 if (SCC.getNode()) { 16375 // Check to see if we got a select_cc back (to turn into setcc/select). 16376 // Otherwise, just return whatever node we got back, like fabs. 16377 if (SCC.getOpcode() == ISD::SELECT_CC) { 16378 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 16379 N0.getValueType(), 16380 SCC.getOperand(0), SCC.getOperand(1), 16381 SCC.getOperand(4)); 16382 AddToWorklist(SETCC.getNode()); 16383 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 16384 SCC.getOperand(2), SCC.getOperand(3)); 16385 } 16386 16387 return SCC; 16388 } 16389 return SDValue(); 16390 } 16391 16392 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 16393 /// being selected between, see if we can simplify the select. Callers of this 16394 /// should assume that TheSelect is deleted if this returns true. As such, they 16395 /// should return the appropriate thing (e.g. the node) back to the top-level of 16396 /// the DAG combiner loop to avoid it being looked at. 16397 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 16398 SDValue RHS) { 16399 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16400 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 16401 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 16402 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 16403 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 16404 SDValue Sqrt = RHS; 16405 ISD::CondCode CC; 16406 SDValue CmpLHS; 16407 const ConstantFPSDNode *Zero = nullptr; 16408 16409 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 16410 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 16411 CmpLHS = TheSelect->getOperand(0); 16412 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 16413 } else { 16414 // SELECT or VSELECT 16415 SDValue Cmp = TheSelect->getOperand(0); 16416 if (Cmp.getOpcode() == ISD::SETCC) { 16417 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 16418 CmpLHS = Cmp.getOperand(0); 16419 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 16420 } 16421 } 16422 if (Zero && Zero->isZero() && 16423 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 16424 CC == ISD::SETULT || CC == ISD::SETLT)) { 16425 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 16426 CombineTo(TheSelect, Sqrt); 16427 return true; 16428 } 16429 } 16430 } 16431 // Cannot simplify select with vector condition 16432 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 16433 16434 // If this is a select from two identical things, try to pull the operation 16435 // through the select. 16436 if (LHS.getOpcode() != RHS.getOpcode() || 16437 !LHS.hasOneUse() || !RHS.hasOneUse()) 16438 return false; 16439 16440 // If this is a load and the token chain is identical, replace the select 16441 // of two loads with a load through a select of the address to load from. 16442 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 16443 // constants have been dropped into the constant pool. 16444 if (LHS.getOpcode() == ISD::LOAD) { 16445 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 16446 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 16447 16448 // Token chains must be identical. 16449 if (LHS.getOperand(0) != RHS.getOperand(0) || 16450 // Do not let this transformation reduce the number of volatile loads. 16451 LLD->isVolatile() || RLD->isVolatile() || 16452 // FIXME: If either is a pre/post inc/dec load, 16453 // we'd need to split out the address adjustment. 16454 LLD->isIndexed() || RLD->isIndexed() || 16455 // If this is an EXTLOAD, the VT's must match. 16456 LLD->getMemoryVT() != RLD->getMemoryVT() || 16457 // If this is an EXTLOAD, the kind of extension must match. 16458 (LLD->getExtensionType() != RLD->getExtensionType() && 16459 // The only exception is if one of the extensions is anyext. 16460 LLD->getExtensionType() != ISD::EXTLOAD && 16461 RLD->getExtensionType() != ISD::EXTLOAD) || 16462 // FIXME: this discards src value information. This is 16463 // over-conservative. It would be beneficial to be able to remember 16464 // both potential memory locations. Since we are discarding 16465 // src value info, don't do the transformation if the memory 16466 // locations are not in the default address space. 16467 LLD->getPointerInfo().getAddrSpace() != 0 || 16468 RLD->getPointerInfo().getAddrSpace() != 0 || 16469 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 16470 LLD->getBasePtr().getValueType())) 16471 return false; 16472 16473 // Check that the select condition doesn't reach either load. If so, 16474 // folding this will induce a cycle into the DAG. If not, this is safe to 16475 // xform, so create a select of the addresses. 16476 SDValue Addr; 16477 if (TheSelect->getOpcode() == ISD::SELECT) { 16478 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 16479 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 16480 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 16481 return false; 16482 // The loads must not depend on one another. 16483 if (LLD->isPredecessorOf(RLD) || 16484 RLD->isPredecessorOf(LLD)) 16485 return false; 16486 Addr = DAG.getSelect(SDLoc(TheSelect), 16487 LLD->getBasePtr().getValueType(), 16488 TheSelect->getOperand(0), LLD->getBasePtr(), 16489 RLD->getBasePtr()); 16490 } else { // Otherwise SELECT_CC 16491 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 16492 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 16493 16494 if ((LLD->hasAnyUseOfValue(1) && 16495 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 16496 (RLD->hasAnyUseOfValue(1) && 16497 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 16498 return false; 16499 16500 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 16501 LLD->getBasePtr().getValueType(), 16502 TheSelect->getOperand(0), 16503 TheSelect->getOperand(1), 16504 LLD->getBasePtr(), RLD->getBasePtr(), 16505 TheSelect->getOperand(4)); 16506 } 16507 16508 SDValue Load; 16509 // It is safe to replace the two loads if they have different alignments, 16510 // but the new load must be the minimum (most restrictive) alignment of the 16511 // inputs. 16512 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 16513 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 16514 if (!RLD->isInvariant()) 16515 MMOFlags &= ~MachineMemOperand::MOInvariant; 16516 if (!RLD->isDereferenceable()) 16517 MMOFlags &= ~MachineMemOperand::MODereferenceable; 16518 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 16519 // FIXME: Discards pointer and AA info. 16520 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 16521 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 16522 MMOFlags); 16523 } else { 16524 // FIXME: Discards pointer and AA info. 16525 Load = DAG.getExtLoad( 16526 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 16527 : LLD->getExtensionType(), 16528 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 16529 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 16530 } 16531 16532 // Users of the select now use the result of the load. 16533 CombineTo(TheSelect, Load); 16534 16535 // Users of the old loads now use the new load's chain. We know the 16536 // old-load value is dead now. 16537 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 16538 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 16539 return true; 16540 } 16541 16542 return false; 16543 } 16544 16545 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 16546 /// bitwise 'and'. 16547 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 16548 SDValue N1, SDValue N2, SDValue N3, 16549 ISD::CondCode CC) { 16550 // If this is a select where the false operand is zero and the compare is a 16551 // check of the sign bit, see if we can perform the "gzip trick": 16552 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 16553 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 16554 EVT XType = N0.getValueType(); 16555 EVT AType = N2.getValueType(); 16556 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 16557 return SDValue(); 16558 16559 // If the comparison is testing for a positive value, we have to invert 16560 // the sign bit mask, so only do that transform if the target has a bitwise 16561 // 'and not' instruction (the invert is free). 16562 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 16563 // (X > -1) ? A : 0 16564 // (X > 0) ? X : 0 <-- This is canonical signed max. 16565 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 16566 return SDValue(); 16567 } else if (CC == ISD::SETLT) { 16568 // (X < 0) ? A : 0 16569 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 16570 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 16571 return SDValue(); 16572 } else { 16573 return SDValue(); 16574 } 16575 16576 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 16577 // constant. 16578 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 16579 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16580 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 16581 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 16582 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 16583 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16584 AddToWorklist(Shift.getNode()); 16585 16586 if (XType.bitsGT(AType)) { 16587 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16588 AddToWorklist(Shift.getNode()); 16589 } 16590 16591 if (CC == ISD::SETGT) 16592 Shift = DAG.getNOT(DL, Shift, AType); 16593 16594 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16595 } 16596 16597 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16598 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16599 AddToWorklist(Shift.getNode()); 16600 16601 if (XType.bitsGT(AType)) { 16602 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16603 AddToWorklist(Shift.getNode()); 16604 } 16605 16606 if (CC == ISD::SETGT) 16607 Shift = DAG.getNOT(DL, Shift, AType); 16608 16609 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16610 } 16611 16612 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16613 /// where 'cond' is the comparison specified by CC. 16614 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16615 SDValue N2, SDValue N3, ISD::CondCode CC, 16616 bool NotExtCompare) { 16617 // (x ? y : y) -> y. 16618 if (N2 == N3) return N2; 16619 16620 EVT VT = N2.getValueType(); 16621 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16622 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16623 16624 // Determine if the condition we're dealing with is constant 16625 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16626 N0, N1, CC, DL, false); 16627 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16628 16629 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16630 // fold select_cc true, x, y -> x 16631 // fold select_cc false, x, y -> y 16632 return !SCCC->isNullValue() ? N2 : N3; 16633 } 16634 16635 // Check to see if we can simplify the select into an fabs node 16636 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16637 // Allow either -0.0 or 0.0 16638 if (CFP->isZero()) { 16639 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16640 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16641 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16642 N2 == N3.getOperand(0)) 16643 return DAG.getNode(ISD::FABS, DL, VT, N0); 16644 16645 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16646 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16647 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16648 N2.getOperand(0) == N3) 16649 return DAG.getNode(ISD::FABS, DL, VT, N3); 16650 } 16651 } 16652 16653 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16654 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16655 // in it. This is a win when the constant is not otherwise available because 16656 // it replaces two constant pool loads with one. We only do this if the FP 16657 // type is known to be legal, because if it isn't, then we are before legalize 16658 // types an we want the other legalization to happen first (e.g. to avoid 16659 // messing with soft float) and if the ConstantFP is not legal, because if 16660 // it is legal, we may not need to store the FP constant in a constant pool. 16661 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16662 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16663 if (TLI.isTypeLegal(N2.getValueType()) && 16664 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16665 TargetLowering::Legal && 16666 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16667 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16668 // If both constants have multiple uses, then we won't need to do an 16669 // extra load, they are likely around in registers for other users. 16670 (TV->hasOneUse() || FV->hasOneUse())) { 16671 Constant *Elts[] = { 16672 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16673 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16674 }; 16675 Type *FPTy = Elts[0]->getType(); 16676 const DataLayout &TD = DAG.getDataLayout(); 16677 16678 // Create a ConstantArray of the two constants. 16679 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16680 SDValue CPIdx = 16681 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16682 TD.getPrefTypeAlignment(FPTy)); 16683 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16684 16685 // Get the offsets to the 0 and 1 element of the array so that we can 16686 // select between them. 16687 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16688 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16689 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16690 16691 SDValue Cond = DAG.getSetCC(DL, 16692 getSetCCResultType(N0.getValueType()), 16693 N0, N1, CC); 16694 AddToWorklist(Cond.getNode()); 16695 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16696 Cond, One, Zero); 16697 AddToWorklist(CstOffset.getNode()); 16698 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16699 CstOffset); 16700 AddToWorklist(CPIdx.getNode()); 16701 return DAG.getLoad( 16702 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16703 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16704 Alignment); 16705 } 16706 } 16707 16708 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16709 return V; 16710 16711 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16712 // where y is has a single bit set. 16713 // A plaintext description would be, we can turn the SELECT_CC into an AND 16714 // when the condition can be materialized as an all-ones register. Any 16715 // single bit-test can be materialized as an all-ones register with 16716 // shift-left and shift-right-arith. 16717 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16718 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16719 SDValue AndLHS = N0->getOperand(0); 16720 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16721 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16722 // Shift the tested bit over the sign bit. 16723 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16724 SDValue ShlAmt = 16725 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16726 getShiftAmountTy(AndLHS.getValueType())); 16727 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 16728 16729 // Now arithmetic right shift it all the way over, so the result is either 16730 // all-ones, or zero. 16731 SDValue ShrAmt = 16732 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 16733 getShiftAmountTy(Shl.getValueType())); 16734 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 16735 16736 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 16737 } 16738 } 16739 16740 // fold select C, 16, 0 -> shl C, 4 16741 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 16742 TLI.getBooleanContents(N0.getValueType()) == 16743 TargetLowering::ZeroOrOneBooleanContent) { 16744 16745 // If the caller doesn't want us to simplify this into a zext of a compare, 16746 // don't do it. 16747 if (NotExtCompare && N2C->isOne()) 16748 return SDValue(); 16749 16750 // Get a SetCC of the condition 16751 // NOTE: Don't create a SETCC if it's not legal on this target. 16752 if (!LegalOperations || 16753 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 16754 SDValue Temp, SCC; 16755 // cast from setcc result type to select result type 16756 if (LegalTypes) { 16757 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 16758 N0, N1, CC); 16759 if (N2.getValueType().bitsLT(SCC.getValueType())) 16760 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 16761 N2.getValueType()); 16762 else 16763 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16764 N2.getValueType(), SCC); 16765 } else { 16766 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 16767 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16768 N2.getValueType(), SCC); 16769 } 16770 16771 AddToWorklist(SCC.getNode()); 16772 AddToWorklist(Temp.getNode()); 16773 16774 if (N2C->isOne()) 16775 return Temp; 16776 16777 // shl setcc result by log2 n2c 16778 return DAG.getNode( 16779 ISD::SHL, DL, N2.getValueType(), Temp, 16780 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 16781 getShiftAmountTy(Temp.getValueType()))); 16782 } 16783 } 16784 16785 // Check to see if this is an integer abs. 16786 // select_cc setg[te] X, 0, X, -X -> 16787 // select_cc setgt X, -1, X, -X -> 16788 // select_cc setl[te] X, 0, -X, X -> 16789 // select_cc setlt X, 1, -X, X -> 16790 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 16791 if (N1C) { 16792 ConstantSDNode *SubC = nullptr; 16793 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 16794 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 16795 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 16796 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 16797 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 16798 (N1C->isOne() && CC == ISD::SETLT)) && 16799 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 16800 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 16801 16802 EVT XType = N0.getValueType(); 16803 if (SubC && SubC->isNullValue() && XType.isInteger()) { 16804 SDLoc DL(N0); 16805 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 16806 N0, 16807 DAG.getConstant(XType.getSizeInBits() - 1, DL, 16808 getShiftAmountTy(N0.getValueType()))); 16809 SDValue Add = DAG.getNode(ISD::ADD, DL, 16810 XType, N0, Shift); 16811 AddToWorklist(Shift.getNode()); 16812 AddToWorklist(Add.getNode()); 16813 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 16814 } 16815 } 16816 16817 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 16818 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 16819 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 16820 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 16821 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 16822 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 16823 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 16824 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 16825 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 16826 SDValue ValueOnZero = N2; 16827 SDValue Count = N3; 16828 // If the condition is NE instead of E, swap the operands. 16829 if (CC == ISD::SETNE) 16830 std::swap(ValueOnZero, Count); 16831 // Check if the value on zero is a constant equal to the bits in the type. 16832 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 16833 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 16834 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 16835 // legal, combine to just cttz. 16836 if ((Count.getOpcode() == ISD::CTTZ || 16837 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 16838 N0 == Count.getOperand(0) && 16839 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 16840 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 16841 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 16842 // legal, combine to just ctlz. 16843 if ((Count.getOpcode() == ISD::CTLZ || 16844 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 16845 N0 == Count.getOperand(0) && 16846 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 16847 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 16848 } 16849 } 16850 } 16851 16852 return SDValue(); 16853 } 16854 16855 /// This is a stub for TargetLowering::SimplifySetCC. 16856 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 16857 ISD::CondCode Cond, const SDLoc &DL, 16858 bool foldBooleans) { 16859 TargetLowering::DAGCombinerInfo 16860 DagCombineInfo(DAG, Level, false, this); 16861 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 16862 } 16863 16864 /// Given an ISD::SDIV node expressing a divide by constant, return 16865 /// a DAG expression to select that will generate the same value by multiplying 16866 /// by a magic number. 16867 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16868 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 16869 // when optimising for minimum size, we don't want to expand a div to a mul 16870 // and a shift. 16871 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16872 return SDValue(); 16873 16874 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16875 if (!C) 16876 return SDValue(); 16877 16878 // Avoid division by zero. 16879 if (C->isNullValue()) 16880 return SDValue(); 16881 16882 std::vector<SDNode *> Built; 16883 SDValue S = 16884 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16885 16886 for (SDNode *N : Built) 16887 AddToWorklist(N); 16888 return S; 16889 } 16890 16891 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 16892 /// DAG expression that will generate the same value by right shifting. 16893 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 16894 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16895 if (!C) 16896 return SDValue(); 16897 16898 // Avoid division by zero. 16899 if (C->isNullValue()) 16900 return SDValue(); 16901 16902 std::vector<SDNode *> Built; 16903 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 16904 16905 for (SDNode *N : Built) 16906 AddToWorklist(N); 16907 return S; 16908 } 16909 16910 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 16911 /// expression that will generate the same value by multiplying by a magic 16912 /// number. 16913 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16914 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 16915 // when optimising for minimum size, we don't want to expand a div to a mul 16916 // and a shift. 16917 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16918 return SDValue(); 16919 16920 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16921 if (!C) 16922 return SDValue(); 16923 16924 // Avoid division by zero. 16925 if (C->isNullValue()) 16926 return SDValue(); 16927 16928 std::vector<SDNode *> Built; 16929 SDValue S = 16930 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16931 16932 for (SDNode *N : Built) 16933 AddToWorklist(N); 16934 return S; 16935 } 16936 16937 /// Determines the LogBase2 value for a non-null input value using the 16938 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 16939 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 16940 EVT VT = V.getValueType(); 16941 unsigned EltBits = VT.getScalarSizeInBits(); 16942 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 16943 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 16944 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 16945 return LogBase2; 16946 } 16947 16948 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16949 /// For the reciprocal, we need to find the zero of the function: 16950 /// F(X) = A X - 1 [which has a zero at X = 1/A] 16951 /// => 16952 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 16953 /// does not require additional intermediate precision] 16954 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 16955 if (Level >= AfterLegalizeDAG) 16956 return SDValue(); 16957 16958 // TODO: Handle half and/or extended types? 16959 EVT VT = Op.getValueType(); 16960 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16961 return SDValue(); 16962 16963 // If estimates are explicitly disabled for this function, we're done. 16964 MachineFunction &MF = DAG.getMachineFunction(); 16965 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 16966 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16967 return SDValue(); 16968 16969 // Estimates may be explicitly enabled for this type with a custom number of 16970 // refinement steps. 16971 int Iterations = TLI.getDivRefinementSteps(VT, MF); 16972 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 16973 AddToWorklist(Est.getNode()); 16974 16975 if (Iterations) { 16976 EVT VT = Op.getValueType(); 16977 SDLoc DL(Op); 16978 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 16979 16980 // Newton iterations: Est = Est + Est (1 - Arg * Est) 16981 for (int i = 0; i < Iterations; ++i) { 16982 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 16983 AddToWorklist(NewEst.getNode()); 16984 16985 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 16986 AddToWorklist(NewEst.getNode()); 16987 16988 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16989 AddToWorklist(NewEst.getNode()); 16990 16991 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 16992 AddToWorklist(Est.getNode()); 16993 } 16994 } 16995 return Est; 16996 } 16997 16998 return SDValue(); 16999 } 17000 17001 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17002 /// For the reciprocal sqrt, we need to find the zero of the function: 17003 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17004 /// => 17005 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 17006 /// As a result, we precompute A/2 prior to the iteration loop. 17007 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 17008 unsigned Iterations, 17009 SDNodeFlags Flags, bool Reciprocal) { 17010 EVT VT = Arg.getValueType(); 17011 SDLoc DL(Arg); 17012 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 17013 17014 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 17015 // this entire sequence requires only one FP constant. 17016 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 17017 AddToWorklist(HalfArg.getNode()); 17018 17019 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 17020 AddToWorklist(HalfArg.getNode()); 17021 17022 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 17023 for (unsigned i = 0; i < Iterations; ++i) { 17024 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 17025 AddToWorklist(NewEst.getNode()); 17026 17027 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 17028 AddToWorklist(NewEst.getNode()); 17029 17030 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 17031 AddToWorklist(NewEst.getNode()); 17032 17033 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 17034 AddToWorklist(Est.getNode()); 17035 } 17036 17037 // If non-reciprocal square root is requested, multiply the result by Arg. 17038 if (!Reciprocal) { 17039 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 17040 AddToWorklist(Est.getNode()); 17041 } 17042 17043 return Est; 17044 } 17045 17046 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 17047 /// For the reciprocal sqrt, we need to find the zero of the function: 17048 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 17049 /// => 17050 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 17051 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 17052 unsigned Iterations, 17053 SDNodeFlags Flags, bool Reciprocal) { 17054 EVT VT = Arg.getValueType(); 17055 SDLoc DL(Arg); 17056 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 17057 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 17058 17059 // This routine must enter the loop below to work correctly 17060 // when (Reciprocal == false). 17061 assert(Iterations > 0); 17062 17063 // Newton iterations for reciprocal square root: 17064 // E = (E * -0.5) * ((A * E) * E + -3.0) 17065 for (unsigned i = 0; i < Iterations; ++i) { 17066 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 17067 AddToWorklist(AE.getNode()); 17068 17069 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 17070 AddToWorklist(AEE.getNode()); 17071 17072 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 17073 AddToWorklist(RHS.getNode()); 17074 17075 // When calculating a square root at the last iteration build: 17076 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 17077 // (notice a common subexpression) 17078 SDValue LHS; 17079 if (Reciprocal || (i + 1) < Iterations) { 17080 // RSQRT: LHS = (E * -0.5) 17081 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 17082 } else { 17083 // SQRT: LHS = (A * E) * -0.5 17084 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 17085 } 17086 AddToWorklist(LHS.getNode()); 17087 17088 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 17089 AddToWorklist(Est.getNode()); 17090 } 17091 17092 return Est; 17093 } 17094 17095 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 17096 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 17097 /// Op can be zero. 17098 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 17099 bool Reciprocal) { 17100 if (Level >= AfterLegalizeDAG) 17101 return SDValue(); 17102 17103 // TODO: Handle half and/or extended types? 17104 EVT VT = Op.getValueType(); 17105 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 17106 return SDValue(); 17107 17108 // If estimates are explicitly disabled for this function, we're done. 17109 MachineFunction &MF = DAG.getMachineFunction(); 17110 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 17111 if (Enabled == TLI.ReciprocalEstimate::Disabled) 17112 return SDValue(); 17113 17114 // Estimates may be explicitly enabled for this type with a custom number of 17115 // refinement steps. 17116 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 17117 17118 bool UseOneConstNR = false; 17119 if (SDValue Est = 17120 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 17121 Reciprocal)) { 17122 AddToWorklist(Est.getNode()); 17123 17124 if (Iterations) { 17125 Est = UseOneConstNR 17126 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 17127 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 17128 17129 if (!Reciprocal) { 17130 // Unfortunately, Est is now NaN if the input was exactly 0.0. 17131 // Select out this case and force the answer to 0.0. 17132 EVT VT = Op.getValueType(); 17133 SDLoc DL(Op); 17134 17135 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 17136 EVT CCVT = getSetCCResultType(VT); 17137 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 17138 AddToWorklist(ZeroCmp.getNode()); 17139 17140 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 17141 ZeroCmp, FPZero, Est); 17142 AddToWorklist(Est.getNode()); 17143 } 17144 } 17145 return Est; 17146 } 17147 17148 return SDValue(); 17149 } 17150 17151 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17152 return buildSqrtEstimateImpl(Op, Flags, true); 17153 } 17154 17155 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 17156 return buildSqrtEstimateImpl(Op, Flags, false); 17157 } 17158 17159 /// Return true if base is a frame index, which is known not to alias with 17160 /// anything but itself. Provides base object and offset as results. 17161 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 17162 const GlobalValue *&GV, const void *&CV) { 17163 // Assume it is a primitive operation. 17164 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 17165 17166 // If it's an adding a simple constant then integrate the offset. 17167 if (Base.getOpcode() == ISD::ADD) { 17168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 17169 Base = Base.getOperand(0); 17170 Offset += C->getSExtValue(); 17171 } 17172 } 17173 17174 // Return the underlying GlobalValue, and update the Offset. Return false 17175 // for GlobalAddressSDNode since the same GlobalAddress may be represented 17176 // by multiple nodes with different offsets. 17177 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 17178 GV = G->getGlobal(); 17179 Offset += G->getOffset(); 17180 return false; 17181 } 17182 17183 // Return the underlying Constant value, and update the Offset. Return false 17184 // for ConstantSDNodes since the same constant pool entry may be represented 17185 // by multiple nodes with different offsets. 17186 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 17187 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 17188 : (const void *)C->getConstVal(); 17189 Offset += C->getOffset(); 17190 return false; 17191 } 17192 // If it's any of the following then it can't alias with anything but itself. 17193 return isa<FrameIndexSDNode>(Base); 17194 } 17195 17196 /// Return true if there is any possibility that the two addresses overlap. 17197 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 17198 // If they are the same then they must be aliases. 17199 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 17200 17201 // If they are both volatile then they cannot be reordered. 17202 if (Op0->isVolatile() && Op1->isVolatile()) return true; 17203 17204 // If one operation reads from invariant memory, and the other may store, they 17205 // cannot alias. These should really be checking the equivalent of mayWrite, 17206 // but it only matters for memory nodes other than load /store. 17207 if (Op0->isInvariant() && Op1->writeMem()) 17208 return false; 17209 17210 if (Op1->isInvariant() && Op0->writeMem()) 17211 return false; 17212 17213 unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize(); 17214 unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize(); 17215 17216 // Check for BaseIndexOffset matching. 17217 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 17218 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 17219 int64_t PtrDiff; 17220 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) 17221 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0)); 17222 17223 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be 17224 // able to calculate their relative offset if at least one arises 17225 // from an alloca. However, these allocas cannot overlap and we 17226 // can infer there is no alias. 17227 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase())) 17228 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) { 17229 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17230 // If the base are the same frame index but the we couldn't find a 17231 // constant offset, (indices are different) be conservative. 17232 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) || 17233 !MFI.isFixedObjectIndex(B->getIndex()))) 17234 return false; 17235 } 17236 17237 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis 17238 // modified to use BaseIndexOffset. 17239 17240 // Gather base node and offset information. 17241 SDValue Base0, Base1; 17242 int64_t Offset0, Offset1; 17243 const GlobalValue *GV0, *GV1; 17244 const void *CV0, *CV1; 17245 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(), 17246 Base0, Offset0, GV0, CV0); 17247 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(), 17248 Base1, Offset1, GV1, CV1); 17249 17250 // If they have the same base address, then check to see if they overlap. 17251 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1))) 17252 return !((Offset0 + NumBytes0) <= Offset1 || 17253 (Offset1 + NumBytes1) <= Offset0); 17254 17255 // It is possible for different frame indices to alias each other, mostly 17256 // when tail call optimization reuses return address slots for arguments. 17257 // To catch this case, look up the actual index of frame indices to compute 17258 // the real alias relationship. 17259 if (IsFrameIndex0 && IsFrameIndex1) { 17260 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17261 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex()); 17262 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 17263 return !((Offset0 + NumBytes0) <= Offset1 || 17264 (Offset1 + NumBytes1) <= Offset0); 17265 } 17266 17267 // Otherwise, if we know what the bases are, and they aren't identical, then 17268 // we know they cannot alias. 17269 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1)) 17270 return false; 17271 17272 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 17273 // compared to the size and offset of the access, we may be able to prove they 17274 // do not alias. This check is conservative for now to catch cases created by 17275 // splitting vector types. 17276 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 17277 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 17278 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 17279 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 17280 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 17281 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 17282 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 17283 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 17284 17285 // There is no overlap between these relatively aligned accesses of similar 17286 // size. Return no alias. 17287 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 17288 (OffAlign1 + NumBytes1) <= OffAlign0) 17289 return false; 17290 } 17291 17292 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 17293 ? CombinerGlobalAA 17294 : DAG.getSubtarget().useAA(); 17295 #ifndef NDEBUG 17296 if (CombinerAAOnlyFunc.getNumOccurrences() && 17297 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 17298 UseAA = false; 17299 #endif 17300 17301 if (UseAA && AA && 17302 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 17303 // Use alias analysis information. 17304 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 17305 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 17306 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 17307 AliasResult AAResult = 17308 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 17309 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 17310 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 17311 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 17312 if (AAResult == NoAlias) 17313 return false; 17314 } 17315 17316 // Otherwise we have to assume they alias. 17317 return true; 17318 } 17319 17320 /// Walk up chain skipping non-aliasing memory nodes, 17321 /// looking for aliasing nodes and adding them to the Aliases vector. 17322 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 17323 SmallVectorImpl<SDValue> &Aliases) { 17324 SmallVector<SDValue, 8> Chains; // List of chains to visit. 17325 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 17326 17327 // Get alias information for node. 17328 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 17329 17330 // Starting off. 17331 Chains.push_back(OriginalChain); 17332 unsigned Depth = 0; 17333 17334 // Look at each chain and determine if it is an alias. If so, add it to the 17335 // aliases list. If not, then continue up the chain looking for the next 17336 // candidate. 17337 while (!Chains.empty()) { 17338 SDValue Chain = Chains.pop_back_val(); 17339 17340 // For TokenFactor nodes, look at each operand and only continue up the 17341 // chain until we reach the depth limit. 17342 // 17343 // FIXME: The depth check could be made to return the last non-aliasing 17344 // chain we found before we hit a tokenfactor rather than the original 17345 // chain. 17346 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 17347 Aliases.clear(); 17348 Aliases.push_back(OriginalChain); 17349 return; 17350 } 17351 17352 // Don't bother if we've been before. 17353 if (!Visited.insert(Chain.getNode()).second) 17354 continue; 17355 17356 switch (Chain.getOpcode()) { 17357 case ISD::EntryToken: 17358 // Entry token is ideal chain operand, but handled in FindBetterChain. 17359 break; 17360 17361 case ISD::LOAD: 17362 case ISD::STORE: { 17363 // Get alias information for Chain. 17364 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 17365 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 17366 17367 // If chain is alias then stop here. 17368 if (!(IsLoad && IsOpLoad) && 17369 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 17370 Aliases.push_back(Chain); 17371 } else { 17372 // Look further up the chain. 17373 Chains.push_back(Chain.getOperand(0)); 17374 ++Depth; 17375 } 17376 break; 17377 } 17378 17379 case ISD::TokenFactor: 17380 // We have to check each of the operands of the token factor for "small" 17381 // token factors, so we queue them up. Adding the operands to the queue 17382 // (stack) in reverse order maintains the original order and increases the 17383 // likelihood that getNode will find a matching token factor (CSE.) 17384 if (Chain.getNumOperands() > 16) { 17385 Aliases.push_back(Chain); 17386 break; 17387 } 17388 for (unsigned n = Chain.getNumOperands(); n;) 17389 Chains.push_back(Chain.getOperand(--n)); 17390 ++Depth; 17391 break; 17392 17393 case ISD::CopyFromReg: 17394 // Forward past CopyFromReg. 17395 Chains.push_back(Chain.getOperand(0)); 17396 ++Depth; 17397 break; 17398 17399 default: 17400 // For all other instructions we will just have to take what we can get. 17401 Aliases.push_back(Chain); 17402 break; 17403 } 17404 } 17405 } 17406 17407 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 17408 /// (aliasing node.) 17409 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 17410 if (OptLevel == CodeGenOpt::None) 17411 return OldChain; 17412 17413 // Ops for replacing token factor. 17414 SmallVector<SDValue, 8> Aliases; 17415 17416 // Accumulate all the aliases to this node. 17417 GatherAllAliases(N, OldChain, Aliases); 17418 17419 // If no operands then chain to entry token. 17420 if (Aliases.size() == 0) 17421 return DAG.getEntryNode(); 17422 17423 // If a single operand then chain to it. We don't need to revisit it. 17424 if (Aliases.size() == 1) 17425 return Aliases[0]; 17426 17427 // Construct a custom tailored token factor. 17428 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 17429 } 17430 17431 // This function tries to collect a bunch of potentially interesting 17432 // nodes to improve the chains of, all at once. This might seem 17433 // redundant, as this function gets called when visiting every store 17434 // node, so why not let the work be done on each store as it's visited? 17435 // 17436 // I believe this is mainly important because MergeConsecutiveStores 17437 // is unable to deal with merging stores of different sizes, so unless 17438 // we improve the chains of all the potential candidates up-front 17439 // before running MergeConsecutiveStores, it might only see some of 17440 // the nodes that will eventually be candidates, and then not be able 17441 // to go from a partially-merged state to the desired final 17442 // fully-merged state. 17443 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 17444 if (OptLevel == CodeGenOpt::None) 17445 return false; 17446 17447 // This holds the base pointer, index, and the offset in bytes from the base 17448 // pointer. 17449 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 17450 17451 // We must have a base and an offset. 17452 if (!BasePtr.getBase().getNode()) 17453 return false; 17454 17455 // Do not handle stores to undef base pointers. 17456 if (BasePtr.getBase().isUndef()) 17457 return false; 17458 17459 SmallVector<StoreSDNode *, 8> ChainedStores; 17460 ChainedStores.push_back(St); 17461 17462 // Walk up the chain and look for nodes with offsets from the same 17463 // base pointer. Stop when reaching an instruction with a different kind 17464 // or instruction which has a different base pointer. 17465 StoreSDNode *Index = St; 17466 while (Index) { 17467 // If the chain has more than one use, then we can't reorder the mem ops. 17468 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 17469 break; 17470 17471 if (Index->isVolatile() || Index->isIndexed()) 17472 break; 17473 17474 // Find the base pointer and offset for this memory node. 17475 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 17476 17477 // Check that the base pointer is the same as the original one. 17478 if (!BasePtr.equalBaseIndex(Ptr, DAG)) 17479 break; 17480 17481 // Walk up the chain to find the next store node, ignoring any 17482 // intermediate loads. Any other kind of node will halt the loop. 17483 SDNode *NextInChain = Index->getChain().getNode(); 17484 while (true) { 17485 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 17486 // We found a store node. Use it for the next iteration. 17487 if (STn->isVolatile() || STn->isIndexed()) { 17488 Index = nullptr; 17489 break; 17490 } 17491 ChainedStores.push_back(STn); 17492 Index = STn; 17493 break; 17494 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 17495 NextInChain = Ldn->getChain().getNode(); 17496 continue; 17497 } else { 17498 Index = nullptr; 17499 break; 17500 } 17501 } // end while 17502 } 17503 17504 // At this point, ChainedStores lists all of the Store nodes 17505 // reachable by iterating up through chain nodes matching the above 17506 // conditions. For each such store identified, try to find an 17507 // earlier chain to attach the store to which won't violate the 17508 // required ordering. 17509 bool MadeChangeToSt = false; 17510 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 17511 17512 for (StoreSDNode *ChainedStore : ChainedStores) { 17513 SDValue Chain = ChainedStore->getChain(); 17514 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 17515 17516 if (Chain != BetterChain) { 17517 if (ChainedStore == St) 17518 MadeChangeToSt = true; 17519 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 17520 } 17521 } 17522 17523 // Do all replacements after finding the replacements to make to avoid making 17524 // the chains more complicated by introducing new TokenFactors. 17525 for (auto Replacement : BetterChains) 17526 replaceStoreChain(Replacement.first, Replacement.second); 17527 17528 return MadeChangeToSt; 17529 } 17530 17531 /// This is the entry point for the file. 17532 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 17533 CodeGenOpt::Level OptLevel) { 17534 /// This is the main entry point to this class. 17535 DAGCombiner(*this, AA, OptLevel).Run(Level); 17536 } 17537