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/SetVector.h" 20 #include "llvm/ADT/SmallBitVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/SelectionDAG.h" 28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/KnownBits.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetLowering.h" 40 #include "llvm/Target/TargetOptions.h" 41 #include "llvm/Target/TargetRegisterInfo.h" 42 #include "llvm/Target/TargetSubtargetInfo.h" 43 #include <algorithm> 44 using namespace llvm; 45 46 #define DEBUG_TYPE "dagcombine" 47 48 STATISTIC(NodesCombined , "Number of dag nodes combined"); 49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 51 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 52 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 53 STATISTIC(SlicedLoads, "Number of load sliced"); 54 55 namespace { 56 static cl::opt<bool> 57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 58 cl::desc("Enable DAG combiner's use of IR alias analysis")); 59 60 static cl::opt<bool> 61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 62 cl::desc("Enable DAG combiner's use of TBAA")); 63 64 #ifndef NDEBUG 65 static cl::opt<std::string> 66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 67 cl::desc("Only use DAG-combiner alias analysis in this" 68 " function")); 69 #endif 70 71 /// Hidden option to stress test load slicing, i.e., when this option 72 /// is enabled, load slicing bypasses most of its profitability guards. 73 static cl::opt<bool> 74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 75 cl::desc("Bypass the profitability model of load " 76 "slicing"), 77 cl::init(false)); 78 79 static cl::opt<bool> 80 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 81 cl::desc("DAG combiner may split indexing from loads")); 82 83 //------------------------------ DAGCombiner ---------------------------------// 84 85 class DAGCombiner { 86 SelectionDAG &DAG; 87 const TargetLowering &TLI; 88 CombineLevel Level; 89 CodeGenOpt::Level OptLevel; 90 bool LegalOperations; 91 bool LegalTypes; 92 bool ForCodeSize; 93 94 /// \brief Worklist of all of the nodes that need to be simplified. 95 /// 96 /// This must behave as a stack -- new nodes to process are pushed onto the 97 /// back and when processing we pop off of the back. 98 /// 99 /// The worklist will not contain duplicates but may contain null entries 100 /// due to nodes being deleted from the underlying DAG. 101 SmallVector<SDNode *, 64> Worklist; 102 103 /// \brief Mapping from an SDNode to its position on the worklist. 104 /// 105 /// This is used to find and remove nodes from the worklist (by nulling 106 /// them) when they are deleted from the underlying DAG. It relies on 107 /// stable indices of nodes within the worklist. 108 DenseMap<SDNode *, unsigned> WorklistMap; 109 110 /// \brief Set of nodes which have been combined (at least once). 111 /// 112 /// This is used to allow us to reliably add any operands of a DAG node 113 /// which have not yet been combined to the worklist. 114 SmallPtrSet<SDNode *, 32> CombinedNodes; 115 116 // AA - Used for DAG load/store alias analysis. 117 AliasAnalysis *AA; 118 119 /// When an instruction is simplified, add all users of the instruction to 120 /// the work lists because they might get more simplified now. 121 void AddUsersToWorklist(SDNode *N) { 122 for (SDNode *Node : N->uses()) 123 AddToWorklist(Node); 124 } 125 126 /// Call the node-specific routine that folds each particular type of node. 127 SDValue visit(SDNode *N); 128 129 public: 130 /// Add to the worklist making sure its instance is at the back (next to be 131 /// processed.) 132 void AddToWorklist(SDNode *N) { 133 assert(N->getOpcode() != ISD::DELETED_NODE && 134 "Deleted Node added to Worklist"); 135 136 // Skip handle nodes as they can't usefully be combined and confuse the 137 // zero-use deletion strategy. 138 if (N->getOpcode() == ISD::HANDLENODE) 139 return; 140 141 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 142 Worklist.push_back(N); 143 } 144 145 /// Remove all instances of N from the worklist. 146 void removeFromWorklist(SDNode *N) { 147 CombinedNodes.erase(N); 148 149 auto It = WorklistMap.find(N); 150 if (It == WorklistMap.end()) 151 return; // Not in the worklist. 152 153 // Null out the entry rather than erasing it to avoid a linear operation. 154 Worklist[It->second] = nullptr; 155 WorklistMap.erase(It); 156 } 157 158 void deleteAndRecombine(SDNode *N); 159 bool recursivelyDeleteUnusedNodes(SDNode *N); 160 161 /// Replaces all uses of the results of one DAG node with new values. 162 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 163 bool AddTo = true); 164 165 /// Replaces all uses of the results of one DAG node with new values. 166 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 167 return CombineTo(N, &Res, 1, AddTo); 168 } 169 170 /// Replaces all uses of the results of one DAG node with new values. 171 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 172 bool AddTo = true) { 173 SDValue To[] = { Res0, Res1 }; 174 return CombineTo(N, To, 2, AddTo); 175 } 176 177 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 178 179 private: 180 unsigned MaximumLegalStoreInBits; 181 182 /// Check the specified integer node value to see if it can be simplified or 183 /// if things it uses can be simplified by bit propagation. 184 /// If so, return true. 185 bool SimplifyDemandedBits(SDValue Op) { 186 unsigned BitWidth = Op.getScalarValueSizeInBits(); 187 APInt Demanded = APInt::getAllOnesValue(BitWidth); 188 return SimplifyDemandedBits(Op, Demanded); 189 } 190 191 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 192 193 bool CombineToPreIndexedLoadStore(SDNode *N); 194 bool CombineToPostIndexedLoadStore(SDNode *N); 195 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 196 bool SliceUpLoad(SDNode *N); 197 198 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 199 /// load. 200 /// 201 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 202 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 203 /// \param EltNo index of the vector element to load. 204 /// \param OriginalLoad load that EVE came from to be replaced. 205 /// \returns EVE on success SDValue() on failure. 206 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 207 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 208 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 209 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 210 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 211 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 212 SDValue PromoteIntBinOp(SDValue Op); 213 SDValue PromoteIntShiftOp(SDValue Op); 214 SDValue PromoteExtend(SDValue Op); 215 bool PromoteLoad(SDValue Op); 216 217 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 218 SDValue ExtLoad, const SDLoc &DL, 219 ISD::NodeType ExtType); 220 221 /// Call the node-specific routine that knows how to fold each 222 /// particular type of node. If that doesn't do anything, try the 223 /// target-specific DAG combines. 224 SDValue combine(SDNode *N); 225 226 // Visitation implementation - Implement dag node combining for different 227 // node types. The semantics are as follows: 228 // Return Value: 229 // SDValue.getNode() == 0 - No change was made 230 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 231 // otherwise - N should be replaced by the returned Operand. 232 // 233 SDValue visitTokenFactor(SDNode *N); 234 SDValue visitMERGE_VALUES(SDNode *N); 235 SDValue visitADD(SDNode *N); 236 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 237 SDValue visitSUB(SDNode *N); 238 SDValue visitADDC(SDNode *N); 239 SDValue visitUADDO(SDNode *N); 240 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 241 SDValue visitSUBC(SDNode *N); 242 SDValue visitUSUBO(SDNode *N); 243 SDValue visitADDE(SDNode *N); 244 SDValue visitADDCARRY(SDNode *N); 245 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 246 SDValue visitSUBE(SDNode *N); 247 SDValue visitSUBCARRY(SDNode *N); 248 SDValue visitMUL(SDNode *N); 249 SDValue useDivRem(SDNode *N); 250 SDValue visitSDIV(SDNode *N); 251 SDValue visitUDIV(SDNode *N); 252 SDValue visitREM(SDNode *N); 253 SDValue visitMULHU(SDNode *N); 254 SDValue visitMULHS(SDNode *N); 255 SDValue visitSMUL_LOHI(SDNode *N); 256 SDValue visitUMUL_LOHI(SDNode *N); 257 SDValue visitSMULO(SDNode *N); 258 SDValue visitUMULO(SDNode *N); 259 SDValue visitIMINMAX(SDNode *N); 260 SDValue visitAND(SDNode *N); 261 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 262 SDValue visitOR(SDNode *N); 263 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 264 SDValue visitXOR(SDNode *N); 265 SDValue SimplifyVBinOp(SDNode *N); 266 SDValue visitSHL(SDNode *N); 267 SDValue visitSRA(SDNode *N); 268 SDValue visitSRL(SDNode *N); 269 SDValue visitRotate(SDNode *N); 270 SDValue visitABS(SDNode *N); 271 SDValue visitBSWAP(SDNode *N); 272 SDValue visitBITREVERSE(SDNode *N); 273 SDValue visitCTLZ(SDNode *N); 274 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 275 SDValue visitCTTZ(SDNode *N); 276 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 277 SDValue visitCTPOP(SDNode *N); 278 SDValue visitSELECT(SDNode *N); 279 SDValue visitVSELECT(SDNode *N); 280 SDValue visitSELECT_CC(SDNode *N); 281 SDValue visitSETCC(SDNode *N); 282 SDValue visitSETCCE(SDNode *N); 283 SDValue visitSETCCCARRY(SDNode *N); 284 SDValue visitSIGN_EXTEND(SDNode *N); 285 SDValue visitZERO_EXTEND(SDNode *N); 286 SDValue visitANY_EXTEND(SDNode *N); 287 SDValue visitAssertZext(SDNode *N); 288 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 289 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 290 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 291 SDValue visitTRUNCATE(SDNode *N); 292 SDValue visitBITCAST(SDNode *N); 293 SDValue visitBUILD_PAIR(SDNode *N); 294 SDValue visitFADD(SDNode *N); 295 SDValue visitFSUB(SDNode *N); 296 SDValue visitFMUL(SDNode *N); 297 SDValue visitFMA(SDNode *N); 298 SDValue visitFDIV(SDNode *N); 299 SDValue visitFREM(SDNode *N); 300 SDValue visitFSQRT(SDNode *N); 301 SDValue visitFCOPYSIGN(SDNode *N); 302 SDValue visitSINT_TO_FP(SDNode *N); 303 SDValue visitUINT_TO_FP(SDNode *N); 304 SDValue visitFP_TO_SINT(SDNode *N); 305 SDValue visitFP_TO_UINT(SDNode *N); 306 SDValue visitFP_ROUND(SDNode *N); 307 SDValue visitFP_ROUND_INREG(SDNode *N); 308 SDValue visitFP_EXTEND(SDNode *N); 309 SDValue visitFNEG(SDNode *N); 310 SDValue visitFABS(SDNode *N); 311 SDValue visitFCEIL(SDNode *N); 312 SDValue visitFTRUNC(SDNode *N); 313 SDValue visitFFLOOR(SDNode *N); 314 SDValue visitFMINNUM(SDNode *N); 315 SDValue visitFMAXNUM(SDNode *N); 316 SDValue visitBRCOND(SDNode *N); 317 SDValue visitBR_CC(SDNode *N); 318 SDValue visitLOAD(SDNode *N); 319 320 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 321 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 322 323 SDValue visitSTORE(SDNode *N); 324 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 325 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 326 SDValue visitBUILD_VECTOR(SDNode *N); 327 SDValue visitCONCAT_VECTORS(SDNode *N); 328 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 329 SDValue visitVECTOR_SHUFFLE(SDNode *N); 330 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 331 SDValue visitINSERT_SUBVECTOR(SDNode *N); 332 SDValue visitMLOAD(SDNode *N); 333 SDValue visitMSTORE(SDNode *N); 334 SDValue visitMGATHER(SDNode *N); 335 SDValue visitMSCATTER(SDNode *N); 336 SDValue visitFP_TO_FP16(SDNode *N); 337 SDValue visitFP16_TO_FP(SDNode *N); 338 339 SDValue visitFADDForFMACombine(SDNode *N); 340 SDValue visitFSUBForFMACombine(SDNode *N); 341 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 342 343 SDValue XformToShuffleWithZero(SDNode *N); 344 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 345 SDValue RHS); 346 347 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 348 349 SDValue foldSelectOfConstants(SDNode *N); 350 SDValue foldBinOpIntoSelect(SDNode *BO); 351 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 352 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 353 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 354 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 355 SDValue N2, SDValue N3, ISD::CondCode CC, 356 bool NotExtCompare = false); 357 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 358 SDValue N2, SDValue N3, ISD::CondCode CC); 359 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 360 const SDLoc &DL); 361 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 362 const SDLoc &DL, bool foldBooleans = true); 363 364 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 365 SDValue &CC) const; 366 bool isOneUseSetCC(SDValue N) const; 367 368 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 369 unsigned HiOp); 370 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 371 SDValue CombineExtLoad(SDNode *N); 372 SDValue combineRepeatedFPDivisors(SDNode *N); 373 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 374 SDValue BuildSDIV(SDNode *N); 375 SDValue BuildSDIVPow2(SDNode *N); 376 SDValue BuildUDIV(SDNode *N); 377 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 378 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 379 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 380 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 381 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 382 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 383 SDNodeFlags Flags, bool Reciprocal); 384 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 385 SDNodeFlags Flags, bool Reciprocal); 386 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 387 bool DemandHighBits = true); 388 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 389 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 390 SDValue InnerPos, SDValue InnerNeg, 391 unsigned PosOpcode, unsigned NegOpcode, 392 const SDLoc &DL); 393 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 394 SDValue MatchLoadCombine(SDNode *N); 395 SDValue ReduceLoadWidth(SDNode *N); 396 SDValue ReduceLoadOpStoreWidth(SDNode *N); 397 SDValue splitMergedValStore(StoreSDNode *ST); 398 SDValue TransformFPLoadStorePair(SDNode *N); 399 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 400 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 401 SDValue reduceBuildVecToShuffle(SDNode *N); 402 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 403 ArrayRef<int> VectorMask, SDValue VecIn1, 404 SDValue VecIn2, unsigned LeftIdx); 405 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 406 407 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 408 409 /// Walk up chain skipping non-aliasing memory nodes, 410 /// looking for aliasing nodes and adding them to the Aliases vector. 411 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 412 SmallVectorImpl<SDValue> &Aliases); 413 414 /// Return true if there is any possibility that the two addresses overlap. 415 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 416 417 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 418 /// chain (aliasing node.) 419 SDValue FindBetterChain(SDNode *N, SDValue Chain); 420 421 /// Try to replace a store and any possibly adjacent stores on 422 /// consecutive chains with better chains. Return true only if St is 423 /// replaced. 424 /// 425 /// Notice that other chains may still be replaced even if the function 426 /// returns false. 427 bool findBetterNeighborChains(StoreSDNode *St); 428 429 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 430 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 431 432 /// Holds a pointer to an LSBaseSDNode as well as information on where it 433 /// is located in a sequence of memory operations connected by a chain. 434 struct MemOpLink { 435 MemOpLink(LSBaseSDNode *N, int64_t Offset) 436 : MemNode(N), OffsetFromBase(Offset) {} 437 // Ptr to the mem node. 438 LSBaseSDNode *MemNode; 439 // Offset from the base ptr. 440 int64_t OffsetFromBase; 441 }; 442 443 /// This is a helper function for visitMUL to check the profitability 444 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 445 /// MulNode is the original multiply, AddNode is (add x, c1), 446 /// and ConstNode is c2. 447 bool isMulAddWithConstProfitable(SDNode *MulNode, 448 SDValue &AddNode, 449 SDValue &ConstNode); 450 451 452 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 453 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 454 /// the type of the loaded value to be extended. LoadedVT returns the type 455 /// of the original loaded value. NarrowLoad returns whether the load would 456 /// need to be narrowed in order to match. 457 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 458 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 459 bool &NarrowLoad); 460 461 /// Helper function for MergeConsecutiveStores which merges the 462 /// component store chains. 463 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 464 unsigned NumStores); 465 466 /// This is a helper function for MergeConsecutiveStores. When the source 467 /// elements of the consecutive stores are all constants or all extracted 468 /// vector elements, try to merge them into one larger store. 469 /// \return True if a merged store was created. 470 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 471 EVT MemVT, unsigned NumStores, 472 bool IsConstantSrc, bool UseVector, 473 bool UseTrunc); 474 475 /// This is a helper function for MergeConsecutiveStores. 476 /// Stores that may be merged are placed in StoreNodes. 477 void getStoreMergeCandidates(StoreSDNode *St, 478 SmallVectorImpl<MemOpLink> &StoreNodes); 479 480 /// Helper function for MergeConsecutiveStores. Checks if 481 /// Candidate stores have indirect dependency through their 482 /// operands. \return True if safe to merge 483 bool checkMergeStoreCandidatesForDependencies( 484 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 485 486 /// Merge consecutive store operations into a wide store. 487 /// This optimization uses wide integers or vectors when possible. 488 /// \return number of stores that were merged into a merged store (the 489 /// affected nodes are stored as a prefix in \p StoreNodes). 490 bool MergeConsecutiveStores(StoreSDNode *N); 491 492 /// \brief Try to transform a truncation where C is a constant: 493 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 494 /// 495 /// \p N needs to be a truncation and its first operand an AND. Other 496 /// requirements are checked by the function (e.g. that trunc is 497 /// single-use) and if missed an empty SDValue is returned. 498 SDValue distributeTruncateThroughAnd(SDNode *N); 499 500 public: 501 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 502 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 503 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) { 504 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 505 506 MaximumLegalStoreInBits = 0; 507 for (MVT VT : MVT::all_valuetypes()) 508 if (EVT(VT).isSimple() && VT != MVT::Other && 509 TLI.isTypeLegal(EVT(VT)) && 510 VT.getSizeInBits() >= MaximumLegalStoreInBits) 511 MaximumLegalStoreInBits = VT.getSizeInBits(); 512 } 513 514 /// Runs the dag combiner on all nodes in the work list 515 void Run(CombineLevel AtLevel); 516 517 SelectionDAG &getDAG() const { return DAG; } 518 519 /// Returns a type large enough to hold any valid shift amount - before type 520 /// legalization these can be huge. 521 EVT getShiftAmountTy(EVT LHSTy) { 522 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 523 if (LHSTy.isVector()) 524 return LHSTy; 525 auto &DL = DAG.getDataLayout(); 526 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 527 : TLI.getPointerTy(DL); 528 } 529 530 /// This method returns true if we are running before type legalization or 531 /// if the specified VT is legal. 532 bool isTypeLegal(const EVT &VT) { 533 if (!LegalTypes) return true; 534 return TLI.isTypeLegal(VT); 535 } 536 537 /// Convenience wrapper around TargetLowering::getSetCCResultType 538 EVT getSetCCResultType(EVT VT) const { 539 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 540 } 541 }; 542 } 543 544 545 namespace { 546 /// This class is a DAGUpdateListener that removes any deleted 547 /// nodes from the worklist. 548 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 549 DAGCombiner &DC; 550 public: 551 explicit WorklistRemover(DAGCombiner &dc) 552 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 553 554 void NodeDeleted(SDNode *N, SDNode *E) override { 555 DC.removeFromWorklist(N); 556 } 557 }; 558 } 559 560 //===----------------------------------------------------------------------===// 561 // TargetLowering::DAGCombinerInfo implementation 562 //===----------------------------------------------------------------------===// 563 564 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 565 ((DAGCombiner*)DC)->AddToWorklist(N); 566 } 567 568 SDValue TargetLowering::DAGCombinerInfo:: 569 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 570 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 571 } 572 573 SDValue TargetLowering::DAGCombinerInfo:: 574 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 575 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 576 } 577 578 579 SDValue TargetLowering::DAGCombinerInfo:: 580 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 581 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 582 } 583 584 void TargetLowering::DAGCombinerInfo:: 585 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 586 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 587 } 588 589 //===----------------------------------------------------------------------===// 590 // Helper Functions 591 //===----------------------------------------------------------------------===// 592 593 void DAGCombiner::deleteAndRecombine(SDNode *N) { 594 removeFromWorklist(N); 595 596 // If the operands of this node are only used by the node, they will now be 597 // dead. Make sure to re-visit them and recursively delete dead nodes. 598 for (const SDValue &Op : N->ops()) 599 // For an operand generating multiple values, one of the values may 600 // become dead allowing further simplification (e.g. split index 601 // arithmetic from an indexed load). 602 if (Op->hasOneUse() || Op->getNumValues() > 1) 603 AddToWorklist(Op.getNode()); 604 605 DAG.DeleteNode(N); 606 } 607 608 /// Return 1 if we can compute the negated form of the specified expression for 609 /// the same cost as the expression itself, or 2 if we can compute the negated 610 /// form more cheaply than the expression itself. 611 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 612 const TargetLowering &TLI, 613 const TargetOptions *Options, 614 unsigned Depth = 0) { 615 // fneg is removable even if it has multiple uses. 616 if (Op.getOpcode() == ISD::FNEG) return 2; 617 618 // Don't allow anything with multiple uses. 619 if (!Op.hasOneUse()) return 0; 620 621 // Don't recurse exponentially. 622 if (Depth > 6) return 0; 623 624 switch (Op.getOpcode()) { 625 default: return false; 626 case ISD::ConstantFP: { 627 if (!LegalOperations) 628 return 1; 629 630 // Don't invert constant FP values after legalization unless the target says 631 // the negated constant is legal. 632 EVT VT = Op.getValueType(); 633 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 634 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 635 } 636 case ISD::FADD: 637 // FIXME: determine better conditions for this xform. 638 if (!Options->UnsafeFPMath) return 0; 639 640 // After operation legalization, it might not be legal to create new FSUBs. 641 if (LegalOperations && 642 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 643 return 0; 644 645 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 646 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 647 Options, Depth + 1)) 648 return V; 649 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 650 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 651 Depth + 1); 652 case ISD::FSUB: 653 // We can't turn -(A-B) into B-A when we honor signed zeros. 654 if (!Options->NoSignedZerosFPMath && 655 !Op.getNode()->getFlags().hasNoSignedZeros()) 656 return 0; 657 658 // fold (fneg (fsub A, B)) -> (fsub B, A) 659 return 1; 660 661 case ISD::FMUL: 662 case ISD::FDIV: 663 if (Options->HonorSignDependentRoundingFPMath()) return 0; 664 665 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 666 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 667 Options, Depth + 1)) 668 return V; 669 670 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 671 Depth + 1); 672 673 case ISD::FP_EXTEND: 674 case ISD::FP_ROUND: 675 case ISD::FSIN: 676 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 677 Depth + 1); 678 } 679 } 680 681 /// If isNegatibleForFree returns true, return the newly negated expression. 682 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 683 bool LegalOperations, unsigned Depth = 0) { 684 const TargetOptions &Options = DAG.getTarget().Options; 685 // fneg is removable even if it has multiple uses. 686 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 687 688 // Don't allow anything with multiple uses. 689 assert(Op.hasOneUse() && "Unknown reuse!"); 690 691 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 692 693 const SDNodeFlags Flags = Op.getNode()->getFlags(); 694 695 switch (Op.getOpcode()) { 696 default: llvm_unreachable("Unknown code"); 697 case ISD::ConstantFP: { 698 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 699 V.changeSign(); 700 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 701 } 702 case ISD::FADD: 703 // FIXME: determine better conditions for this xform. 704 assert(Options.UnsafeFPMath); 705 706 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 707 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 708 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 709 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 710 GetNegatedExpression(Op.getOperand(0), DAG, 711 LegalOperations, Depth+1), 712 Op.getOperand(1), Flags); 713 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 714 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 715 GetNegatedExpression(Op.getOperand(1), DAG, 716 LegalOperations, Depth+1), 717 Op.getOperand(0), Flags); 718 case ISD::FSUB: 719 // fold (fneg (fsub 0, B)) -> B 720 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 721 if (N0CFP->isZero()) 722 return Op.getOperand(1); 723 724 // fold (fneg (fsub A, B)) -> (fsub B, A) 725 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 726 Op.getOperand(1), Op.getOperand(0), Flags); 727 728 case ISD::FMUL: 729 case ISD::FDIV: 730 assert(!Options.HonorSignDependentRoundingFPMath()); 731 732 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 733 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 734 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 735 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 736 GetNegatedExpression(Op.getOperand(0), DAG, 737 LegalOperations, Depth+1), 738 Op.getOperand(1), Flags); 739 740 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 741 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 742 Op.getOperand(0), 743 GetNegatedExpression(Op.getOperand(1), DAG, 744 LegalOperations, Depth+1), Flags); 745 746 case ISD::FP_EXTEND: 747 case ISD::FSIN: 748 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 749 GetNegatedExpression(Op.getOperand(0), DAG, 750 LegalOperations, Depth+1)); 751 case ISD::FP_ROUND: 752 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 753 GetNegatedExpression(Op.getOperand(0), DAG, 754 LegalOperations, Depth+1), 755 Op.getOperand(1)); 756 } 757 } 758 759 // APInts must be the same size for most operations, this helper 760 // function zero extends the shorter of the pair so that they match. 761 // We provide an Offset so that we can create bitwidths that won't overflow. 762 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 763 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 764 LHS = LHS.zextOrSelf(Bits); 765 RHS = RHS.zextOrSelf(Bits); 766 } 767 768 // Return true if this node is a setcc, or is a select_cc 769 // that selects between the target values used for true and false, making it 770 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 771 // the appropriate nodes based on the type of node we are checking. This 772 // simplifies life a bit for the callers. 773 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 774 SDValue &CC) const { 775 if (N.getOpcode() == ISD::SETCC) { 776 LHS = N.getOperand(0); 777 RHS = N.getOperand(1); 778 CC = N.getOperand(2); 779 return true; 780 } 781 782 if (N.getOpcode() != ISD::SELECT_CC || 783 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 784 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 785 return false; 786 787 if (TLI.getBooleanContents(N.getValueType()) == 788 TargetLowering::UndefinedBooleanContent) 789 return false; 790 791 LHS = N.getOperand(0); 792 RHS = N.getOperand(1); 793 CC = N.getOperand(4); 794 return true; 795 } 796 797 /// Return true if this is a SetCC-equivalent operation with only one use. 798 /// If this is true, it allows the users to invert the operation for free when 799 /// it is profitable to do so. 800 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 801 SDValue N0, N1, N2; 802 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 803 return true; 804 return false; 805 } 806 807 // \brief Returns the SDNode if it is a constant float BuildVector 808 // or constant float. 809 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 810 if (isa<ConstantFPSDNode>(N)) 811 return N.getNode(); 812 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 813 return N.getNode(); 814 return nullptr; 815 } 816 817 // Determines if it is a constant integer or a build vector of constant 818 // integers (and undefs). 819 // Do not permit build vector implicit truncation. 820 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 821 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 822 return !(Const->isOpaque() && NoOpaques); 823 if (N.getOpcode() != ISD::BUILD_VECTOR) 824 return false; 825 unsigned BitWidth = N.getScalarValueSizeInBits(); 826 for (const SDValue &Op : N->op_values()) { 827 if (Op.isUndef()) 828 continue; 829 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 830 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 831 (Const->isOpaque() && NoOpaques)) 832 return false; 833 } 834 return true; 835 } 836 837 // Determines if it is a constant null integer or a splatted vector of a 838 // constant null integer (with no undefs). 839 // Build vector implicit truncation is not an issue for null values. 840 static bool isNullConstantOrNullSplatConstant(SDValue N) { 841 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 842 return Splat->isNullValue(); 843 return false; 844 } 845 846 // Determines if it is a constant integer of one or a splatted vector of a 847 // constant integer of one (with no undefs). 848 // Do not permit build vector implicit truncation. 849 static bool isOneConstantOrOneSplatConstant(SDValue N) { 850 unsigned BitWidth = N.getScalarValueSizeInBits(); 851 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 852 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 853 return false; 854 } 855 856 // Determines if it is a constant integer of all ones or a splatted vector of a 857 // constant integer of all ones (with no undefs). 858 // Do not permit build vector implicit truncation. 859 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 860 unsigned BitWidth = N.getScalarValueSizeInBits(); 861 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 862 return Splat->isAllOnesValue() && 863 Splat->getAPIntValue().getBitWidth() == BitWidth; 864 return false; 865 } 866 867 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 868 // undef's. 869 static bool isAnyConstantBuildVector(const SDNode *N) { 870 return ISD::isBuildVectorOfConstantSDNodes(N) || 871 ISD::isBuildVectorOfConstantFPSDNodes(N); 872 } 873 874 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 875 SDValue N1) { 876 EVT VT = N0.getValueType(); 877 if (N0.getOpcode() == Opc) { 878 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 879 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 880 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 881 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 882 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 883 return SDValue(); 884 } 885 if (N0.hasOneUse()) { 886 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 887 // use 888 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 889 if (!OpNode.getNode()) 890 return SDValue(); 891 AddToWorklist(OpNode.getNode()); 892 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 893 } 894 } 895 } 896 897 if (N1.getOpcode() == Opc) { 898 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 899 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 900 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 901 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 902 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 903 return SDValue(); 904 } 905 if (N1.hasOneUse()) { 906 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 907 // use 908 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 909 if (!OpNode.getNode()) 910 return SDValue(); 911 AddToWorklist(OpNode.getNode()); 912 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 913 } 914 } 915 } 916 917 return SDValue(); 918 } 919 920 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 921 bool AddTo) { 922 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 923 ++NodesCombined; 924 DEBUG(dbgs() << "\nReplacing.1 "; 925 N->dump(&DAG); 926 dbgs() << "\nWith: "; 927 To[0].getNode()->dump(&DAG); 928 dbgs() << " and " << NumTo-1 << " other values\n"); 929 for (unsigned i = 0, e = NumTo; i != e; ++i) 930 assert((!To[i].getNode() || 931 N->getValueType(i) == To[i].getValueType()) && 932 "Cannot combine value to value of different type!"); 933 934 WorklistRemover DeadNodes(*this); 935 DAG.ReplaceAllUsesWith(N, To); 936 if (AddTo) { 937 // Push the new nodes and any users onto the worklist 938 for (unsigned i = 0, e = NumTo; i != e; ++i) { 939 if (To[i].getNode()) { 940 AddToWorklist(To[i].getNode()); 941 AddUsersToWorklist(To[i].getNode()); 942 } 943 } 944 } 945 946 // Finally, if the node is now dead, remove it from the graph. The node 947 // may not be dead if the replacement process recursively simplified to 948 // something else needing this node. 949 if (N->use_empty()) 950 deleteAndRecombine(N); 951 return SDValue(N, 0); 952 } 953 954 void DAGCombiner:: 955 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 956 // Replace all uses. If any nodes become isomorphic to other nodes and 957 // are deleted, make sure to remove them from our worklist. 958 WorklistRemover DeadNodes(*this); 959 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 960 961 // Push the new node and any (possibly new) users onto the worklist. 962 AddToWorklist(TLO.New.getNode()); 963 AddUsersToWorklist(TLO.New.getNode()); 964 965 // Finally, if the node is now dead, remove it from the graph. The node 966 // may not be dead if the replacement process recursively simplified to 967 // something else needing this node. 968 if (TLO.Old.getNode()->use_empty()) 969 deleteAndRecombine(TLO.Old.getNode()); 970 } 971 972 /// Check the specified integer node value to see if it can be simplified or if 973 /// things it uses can be simplified by bit propagation. If so, return true. 974 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 975 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 976 KnownBits Known; 977 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 978 return false; 979 980 // Revisit the node. 981 AddToWorklist(Op.getNode()); 982 983 // Replace the old value with the new one. 984 ++NodesCombined; 985 DEBUG(dbgs() << "\nReplacing.2 "; 986 TLO.Old.getNode()->dump(&DAG); 987 dbgs() << "\nWith: "; 988 TLO.New.getNode()->dump(&DAG); 989 dbgs() << '\n'); 990 991 CommitTargetLoweringOpt(TLO); 992 return true; 993 } 994 995 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 996 SDLoc DL(Load); 997 EVT VT = Load->getValueType(0); 998 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 999 1000 DEBUG(dbgs() << "\nReplacing.9 "; 1001 Load->dump(&DAG); 1002 dbgs() << "\nWith: "; 1003 Trunc.getNode()->dump(&DAG); 1004 dbgs() << '\n'); 1005 WorklistRemover DeadNodes(*this); 1006 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1007 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1008 deleteAndRecombine(Load); 1009 AddToWorklist(Trunc.getNode()); 1010 } 1011 1012 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1013 Replace = false; 1014 SDLoc DL(Op); 1015 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1016 LoadSDNode *LD = cast<LoadSDNode>(Op); 1017 EVT MemVT = LD->getMemoryVT(); 1018 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1019 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1020 : ISD::EXTLOAD) 1021 : LD->getExtensionType(); 1022 Replace = true; 1023 return DAG.getExtLoad(ExtType, DL, PVT, 1024 LD->getChain(), LD->getBasePtr(), 1025 MemVT, LD->getMemOperand()); 1026 } 1027 1028 unsigned Opc = Op.getOpcode(); 1029 switch (Opc) { 1030 default: break; 1031 case ISD::AssertSext: 1032 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1033 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1034 break; 1035 case ISD::AssertZext: 1036 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1037 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1038 break; 1039 case ISD::Constant: { 1040 unsigned ExtOpc = 1041 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1042 return DAG.getNode(ExtOpc, DL, PVT, Op); 1043 } 1044 } 1045 1046 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1047 return SDValue(); 1048 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1049 } 1050 1051 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1052 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1053 return SDValue(); 1054 EVT OldVT = Op.getValueType(); 1055 SDLoc DL(Op); 1056 bool Replace = false; 1057 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1058 if (!NewOp.getNode()) 1059 return SDValue(); 1060 AddToWorklist(NewOp.getNode()); 1061 1062 if (Replace) 1063 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1064 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1065 DAG.getValueType(OldVT)); 1066 } 1067 1068 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1069 EVT OldVT = Op.getValueType(); 1070 SDLoc DL(Op); 1071 bool Replace = false; 1072 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1073 if (!NewOp.getNode()) 1074 return SDValue(); 1075 AddToWorklist(NewOp.getNode()); 1076 1077 if (Replace) 1078 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1079 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1080 } 1081 1082 /// Promote the specified integer binary operation if the target indicates it is 1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1084 /// i32 since i16 instructions are longer. 1085 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1086 if (!LegalOperations) 1087 return SDValue(); 1088 1089 EVT VT = Op.getValueType(); 1090 if (VT.isVector() || !VT.isInteger()) 1091 return SDValue(); 1092 1093 // If operation type is 'undesirable', e.g. i16 on x86, consider 1094 // promoting it. 1095 unsigned Opc = Op.getOpcode(); 1096 if (TLI.isTypeDesirableForOp(Opc, VT)) 1097 return SDValue(); 1098 1099 EVT PVT = VT; 1100 // Consult target whether it is a good idea to promote this operation and 1101 // what's the right type to promote it to. 1102 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1103 assert(PVT != VT && "Don't know what type to promote to!"); 1104 1105 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1106 1107 bool Replace0 = false; 1108 SDValue N0 = Op.getOperand(0); 1109 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1110 1111 bool Replace1 = false; 1112 SDValue N1 = Op.getOperand(1); 1113 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1114 SDLoc DL(Op); 1115 1116 SDValue RV = 1117 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1118 1119 // New replace instances of N0 and N1 1120 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 && 1121 NN0.getOpcode() != ISD::DELETED_NODE) { 1122 AddToWorklist(NN0.getNode()); 1123 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1124 } 1125 1126 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 && 1127 NN1.getOpcode() != ISD::DELETED_NODE) { 1128 AddToWorklist(NN1.getNode()); 1129 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1130 } 1131 1132 // Deal with Op being deleted. 1133 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1134 return RV; 1135 } 1136 return SDValue(); 1137 } 1138 1139 /// Promote the specified integer shift operation if the target indicates it is 1140 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1141 /// i32 since i16 instructions are longer. 1142 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1143 if (!LegalOperations) 1144 return SDValue(); 1145 1146 EVT VT = Op.getValueType(); 1147 if (VT.isVector() || !VT.isInteger()) 1148 return SDValue(); 1149 1150 // If operation type is 'undesirable', e.g. i16 on x86, consider 1151 // promoting it. 1152 unsigned Opc = Op.getOpcode(); 1153 if (TLI.isTypeDesirableForOp(Opc, VT)) 1154 return SDValue(); 1155 1156 EVT PVT = VT; 1157 // Consult target whether it is a good idea to promote this operation and 1158 // what's the right type to promote it to. 1159 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1160 assert(PVT != VT && "Don't know what type to promote to!"); 1161 1162 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1163 1164 bool Replace = false; 1165 SDValue N0 = Op.getOperand(0); 1166 SDValue N1 = Op.getOperand(1); 1167 if (Opc == ISD::SRA) 1168 N0 = SExtPromoteOperand(N0, PVT); 1169 else if (Opc == ISD::SRL) 1170 N0 = ZExtPromoteOperand(N0, PVT); 1171 else 1172 N0 = PromoteOperand(N0, PVT, Replace); 1173 1174 if (!N0.getNode()) 1175 return SDValue(); 1176 1177 SDLoc DL(Op); 1178 SDValue RV = 1179 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1180 1181 AddToWorklist(N0.getNode()); 1182 if (Replace) 1183 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1184 1185 // Deal with Op being deleted. 1186 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1187 return RV; 1188 } 1189 return SDValue(); 1190 } 1191 1192 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1193 if (!LegalOperations) 1194 return SDValue(); 1195 1196 EVT VT = Op.getValueType(); 1197 if (VT.isVector() || !VT.isInteger()) 1198 return SDValue(); 1199 1200 // If operation type is 'undesirable', e.g. i16 on x86, consider 1201 // promoting it. 1202 unsigned Opc = Op.getOpcode(); 1203 if (TLI.isTypeDesirableForOp(Opc, VT)) 1204 return SDValue(); 1205 1206 EVT PVT = VT; 1207 // Consult target whether it is a good idea to promote this operation and 1208 // what's the right type to promote it to. 1209 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1210 assert(PVT != VT && "Don't know what type to promote to!"); 1211 // fold (aext (aext x)) -> (aext x) 1212 // fold (aext (zext x)) -> (zext x) 1213 // fold (aext (sext x)) -> (sext x) 1214 DEBUG(dbgs() << "\nPromoting "; 1215 Op.getNode()->dump(&DAG)); 1216 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1217 } 1218 return SDValue(); 1219 } 1220 1221 bool DAGCombiner::PromoteLoad(SDValue Op) { 1222 if (!LegalOperations) 1223 return false; 1224 1225 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1226 return false; 1227 1228 EVT VT = Op.getValueType(); 1229 if (VT.isVector() || !VT.isInteger()) 1230 return false; 1231 1232 // If operation type is 'undesirable', e.g. i16 on x86, consider 1233 // promoting it. 1234 unsigned Opc = Op.getOpcode(); 1235 if (TLI.isTypeDesirableForOp(Opc, VT)) 1236 return false; 1237 1238 EVT PVT = VT; 1239 // Consult target whether it is a good idea to promote this operation and 1240 // what's the right type to promote it to. 1241 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1242 assert(PVT != VT && "Don't know what type to promote to!"); 1243 1244 SDLoc DL(Op); 1245 SDNode *N = Op.getNode(); 1246 LoadSDNode *LD = cast<LoadSDNode>(N); 1247 EVT MemVT = LD->getMemoryVT(); 1248 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1249 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1250 : ISD::EXTLOAD) 1251 : LD->getExtensionType(); 1252 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1253 LD->getChain(), LD->getBasePtr(), 1254 MemVT, LD->getMemOperand()); 1255 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1256 1257 DEBUG(dbgs() << "\nPromoting "; 1258 N->dump(&DAG); 1259 dbgs() << "\nTo: "; 1260 Result.getNode()->dump(&DAG); 1261 dbgs() << '\n'); 1262 WorklistRemover DeadNodes(*this); 1263 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1264 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1265 deleteAndRecombine(N); 1266 AddToWorklist(Result.getNode()); 1267 return true; 1268 } 1269 return false; 1270 } 1271 1272 /// \brief Recursively delete a node which has no uses and any operands for 1273 /// which it is the only use. 1274 /// 1275 /// Note that this both deletes the nodes and removes them from the worklist. 1276 /// It also adds any nodes who have had a user deleted to the worklist as they 1277 /// may now have only one use and subject to other combines. 1278 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1279 if (!N->use_empty()) 1280 return false; 1281 1282 SmallSetVector<SDNode *, 16> Nodes; 1283 Nodes.insert(N); 1284 do { 1285 N = Nodes.pop_back_val(); 1286 if (!N) 1287 continue; 1288 1289 if (N->use_empty()) { 1290 for (const SDValue &ChildN : N->op_values()) 1291 Nodes.insert(ChildN.getNode()); 1292 1293 removeFromWorklist(N); 1294 DAG.DeleteNode(N); 1295 } else { 1296 AddToWorklist(N); 1297 } 1298 } while (!Nodes.empty()); 1299 return true; 1300 } 1301 1302 //===----------------------------------------------------------------------===// 1303 // Main DAG Combiner implementation 1304 //===----------------------------------------------------------------------===// 1305 1306 void DAGCombiner::Run(CombineLevel AtLevel) { 1307 // set the instance variables, so that the various visit routines may use it. 1308 Level = AtLevel; 1309 LegalOperations = Level >= AfterLegalizeVectorOps; 1310 LegalTypes = Level >= AfterLegalizeTypes; 1311 1312 // Add all the dag nodes to the worklist. 1313 for (SDNode &Node : DAG.allnodes()) 1314 AddToWorklist(&Node); 1315 1316 // Create a dummy node (which is not added to allnodes), that adds a reference 1317 // to the root node, preventing it from being deleted, and tracking any 1318 // changes of the root. 1319 HandleSDNode Dummy(DAG.getRoot()); 1320 1321 // While the worklist isn't empty, find a node and try to combine it. 1322 while (!WorklistMap.empty()) { 1323 SDNode *N; 1324 // The Worklist holds the SDNodes in order, but it may contain null entries. 1325 do { 1326 N = Worklist.pop_back_val(); 1327 } while (!N); 1328 1329 bool GoodWorklistEntry = WorklistMap.erase(N); 1330 (void)GoodWorklistEntry; 1331 assert(GoodWorklistEntry && 1332 "Found a worklist entry without a corresponding map entry!"); 1333 1334 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1335 // N is deleted from the DAG, since they too may now be dead or may have a 1336 // reduced number of uses, allowing other xforms. 1337 if (recursivelyDeleteUnusedNodes(N)) 1338 continue; 1339 1340 WorklistRemover DeadNodes(*this); 1341 1342 // If this combine is running after legalizing the DAG, re-legalize any 1343 // nodes pulled off the worklist. 1344 if (Level == AfterLegalizeDAG) { 1345 SmallSetVector<SDNode *, 16> UpdatedNodes; 1346 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1347 1348 for (SDNode *LN : UpdatedNodes) { 1349 AddToWorklist(LN); 1350 AddUsersToWorklist(LN); 1351 } 1352 if (!NIsValid) 1353 continue; 1354 } 1355 1356 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1357 1358 // Add any operands of the new node which have not yet been combined to the 1359 // worklist as well. Because the worklist uniques things already, this 1360 // won't repeatedly process the same operand. 1361 CombinedNodes.insert(N); 1362 for (const SDValue &ChildN : N->op_values()) 1363 if (!CombinedNodes.count(ChildN.getNode())) 1364 AddToWorklist(ChildN.getNode()); 1365 1366 SDValue RV = combine(N); 1367 1368 if (!RV.getNode()) 1369 continue; 1370 1371 ++NodesCombined; 1372 1373 // If we get back the same node we passed in, rather than a new node or 1374 // zero, we know that the node must have defined multiple values and 1375 // CombineTo was used. Since CombineTo takes care of the worklist 1376 // mechanics for us, we have no work to do in this case. 1377 if (RV.getNode() == N) 1378 continue; 1379 1380 assert(N->getOpcode() != ISD::DELETED_NODE && 1381 RV.getOpcode() != ISD::DELETED_NODE && 1382 "Node was deleted but visit returned new node!"); 1383 1384 DEBUG(dbgs() << " ... into: "; 1385 RV.getNode()->dump(&DAG)); 1386 1387 if (N->getNumValues() == RV.getNode()->getNumValues()) 1388 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1389 else { 1390 assert(N->getValueType(0) == RV.getValueType() && 1391 N->getNumValues() == 1 && "Type mismatch"); 1392 DAG.ReplaceAllUsesWith(N, &RV); 1393 } 1394 1395 // Push the new node and any users onto the worklist 1396 AddToWorklist(RV.getNode()); 1397 AddUsersToWorklist(RV.getNode()); 1398 1399 // Finally, if the node is now dead, remove it from the graph. The node 1400 // may not be dead if the replacement process recursively simplified to 1401 // something else needing this node. This will also take care of adding any 1402 // operands which have lost a user to the worklist. 1403 recursivelyDeleteUnusedNodes(N); 1404 } 1405 1406 // If the root changed (e.g. it was a dead load, update the root). 1407 DAG.setRoot(Dummy.getValue()); 1408 DAG.RemoveDeadNodes(); 1409 } 1410 1411 SDValue DAGCombiner::visit(SDNode *N) { 1412 switch (N->getOpcode()) { 1413 default: break; 1414 case ISD::TokenFactor: return visitTokenFactor(N); 1415 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1416 case ISD::ADD: return visitADD(N); 1417 case ISD::SUB: return visitSUB(N); 1418 case ISD::ADDC: return visitADDC(N); 1419 case ISD::UADDO: return visitUADDO(N); 1420 case ISD::SUBC: return visitSUBC(N); 1421 case ISD::USUBO: return visitUSUBO(N); 1422 case ISD::ADDE: return visitADDE(N); 1423 case ISD::ADDCARRY: return visitADDCARRY(N); 1424 case ISD::SUBE: return visitSUBE(N); 1425 case ISD::SUBCARRY: return visitSUBCARRY(N); 1426 case ISD::MUL: return visitMUL(N); 1427 case ISD::SDIV: return visitSDIV(N); 1428 case ISD::UDIV: return visitUDIV(N); 1429 case ISD::SREM: 1430 case ISD::UREM: return visitREM(N); 1431 case ISD::MULHU: return visitMULHU(N); 1432 case ISD::MULHS: return visitMULHS(N); 1433 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1434 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1435 case ISD::SMULO: return visitSMULO(N); 1436 case ISD::UMULO: return visitUMULO(N); 1437 case ISD::SMIN: 1438 case ISD::SMAX: 1439 case ISD::UMIN: 1440 case ISD::UMAX: return visitIMINMAX(N); 1441 case ISD::AND: return visitAND(N); 1442 case ISD::OR: return visitOR(N); 1443 case ISD::XOR: return visitXOR(N); 1444 case ISD::SHL: return visitSHL(N); 1445 case ISD::SRA: return visitSRA(N); 1446 case ISD::SRL: return visitSRL(N); 1447 case ISD::ROTR: 1448 case ISD::ROTL: return visitRotate(N); 1449 case ISD::ABS: return visitABS(N); 1450 case ISD::BSWAP: return visitBSWAP(N); 1451 case ISD::BITREVERSE: return visitBITREVERSE(N); 1452 case ISD::CTLZ: return visitCTLZ(N); 1453 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1454 case ISD::CTTZ: return visitCTTZ(N); 1455 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1456 case ISD::CTPOP: return visitCTPOP(N); 1457 case ISD::SELECT: return visitSELECT(N); 1458 case ISD::VSELECT: return visitVSELECT(N); 1459 case ISD::SELECT_CC: return visitSELECT_CC(N); 1460 case ISD::SETCC: return visitSETCC(N); 1461 case ISD::SETCCE: return visitSETCCE(N); 1462 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1463 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1464 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1465 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1466 case ISD::AssertZext: return visitAssertZext(N); 1467 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1468 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1469 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1470 case ISD::TRUNCATE: return visitTRUNCATE(N); 1471 case ISD::BITCAST: return visitBITCAST(N); 1472 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1473 case ISD::FADD: return visitFADD(N); 1474 case ISD::FSUB: return visitFSUB(N); 1475 case ISD::FMUL: return visitFMUL(N); 1476 case ISD::FMA: return visitFMA(N); 1477 case ISD::FDIV: return visitFDIV(N); 1478 case ISD::FREM: return visitFREM(N); 1479 case ISD::FSQRT: return visitFSQRT(N); 1480 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1481 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1482 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1483 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1484 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1485 case ISD::FP_ROUND: return visitFP_ROUND(N); 1486 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1487 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1488 case ISD::FNEG: return visitFNEG(N); 1489 case ISD::FABS: return visitFABS(N); 1490 case ISD::FFLOOR: return visitFFLOOR(N); 1491 case ISD::FMINNUM: return visitFMINNUM(N); 1492 case ISD::FMAXNUM: return visitFMAXNUM(N); 1493 case ISD::FCEIL: return visitFCEIL(N); 1494 case ISD::FTRUNC: return visitFTRUNC(N); 1495 case ISD::BRCOND: return visitBRCOND(N); 1496 case ISD::BR_CC: return visitBR_CC(N); 1497 case ISD::LOAD: return visitLOAD(N); 1498 case ISD::STORE: return visitSTORE(N); 1499 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1500 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1501 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1502 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1503 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1504 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1505 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1506 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1507 case ISD::MGATHER: return visitMGATHER(N); 1508 case ISD::MLOAD: return visitMLOAD(N); 1509 case ISD::MSCATTER: return visitMSCATTER(N); 1510 case ISD::MSTORE: return visitMSTORE(N); 1511 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1512 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1513 } 1514 return SDValue(); 1515 } 1516 1517 SDValue DAGCombiner::combine(SDNode *N) { 1518 SDValue RV = visit(N); 1519 1520 // If nothing happened, try a target-specific DAG combine. 1521 if (!RV.getNode()) { 1522 assert(N->getOpcode() != ISD::DELETED_NODE && 1523 "Node was deleted but visit returned NULL!"); 1524 1525 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1526 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1527 1528 // Expose the DAG combiner to the target combiner impls. 1529 TargetLowering::DAGCombinerInfo 1530 DagCombineInfo(DAG, Level, false, this); 1531 1532 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1533 } 1534 } 1535 1536 // If nothing happened still, try promoting the operation. 1537 if (!RV.getNode()) { 1538 switch (N->getOpcode()) { 1539 default: break; 1540 case ISD::ADD: 1541 case ISD::SUB: 1542 case ISD::MUL: 1543 case ISD::AND: 1544 case ISD::OR: 1545 case ISD::XOR: 1546 RV = PromoteIntBinOp(SDValue(N, 0)); 1547 break; 1548 case ISD::SHL: 1549 case ISD::SRA: 1550 case ISD::SRL: 1551 RV = PromoteIntShiftOp(SDValue(N, 0)); 1552 break; 1553 case ISD::SIGN_EXTEND: 1554 case ISD::ZERO_EXTEND: 1555 case ISD::ANY_EXTEND: 1556 RV = PromoteExtend(SDValue(N, 0)); 1557 break; 1558 case ISD::LOAD: 1559 if (PromoteLoad(SDValue(N, 0))) 1560 RV = SDValue(N, 0); 1561 break; 1562 } 1563 } 1564 1565 // If N is a commutative binary node, try commuting it to enable more 1566 // sdisel CSE. 1567 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1568 N->getNumValues() == 1) { 1569 SDValue N0 = N->getOperand(0); 1570 SDValue N1 = N->getOperand(1); 1571 1572 // Constant operands are canonicalized to RHS. 1573 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1574 SDValue Ops[] = {N1, N0}; 1575 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1576 N->getFlags()); 1577 if (CSENode) 1578 return SDValue(CSENode, 0); 1579 } 1580 } 1581 1582 return RV; 1583 } 1584 1585 /// Given a node, return its input chain if it has one, otherwise return a null 1586 /// sd operand. 1587 static SDValue getInputChainForNode(SDNode *N) { 1588 if (unsigned NumOps = N->getNumOperands()) { 1589 if (N->getOperand(0).getValueType() == MVT::Other) 1590 return N->getOperand(0); 1591 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1592 return N->getOperand(NumOps-1); 1593 for (unsigned i = 1; i < NumOps-1; ++i) 1594 if (N->getOperand(i).getValueType() == MVT::Other) 1595 return N->getOperand(i); 1596 } 1597 return SDValue(); 1598 } 1599 1600 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1601 // If N has two operands, where one has an input chain equal to the other, 1602 // the 'other' chain is redundant. 1603 if (N->getNumOperands() == 2) { 1604 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1605 return N->getOperand(0); 1606 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1607 return N->getOperand(1); 1608 } 1609 1610 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1611 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1612 SmallPtrSet<SDNode*, 16> SeenOps; 1613 bool Changed = false; // If we should replace this token factor. 1614 1615 // Start out with this token factor. 1616 TFs.push_back(N); 1617 1618 // Iterate through token factors. The TFs grows when new token factors are 1619 // encountered. 1620 for (unsigned i = 0; i < TFs.size(); ++i) { 1621 SDNode *TF = TFs[i]; 1622 1623 // Check each of the operands. 1624 for (const SDValue &Op : TF->op_values()) { 1625 1626 switch (Op.getOpcode()) { 1627 case ISD::EntryToken: 1628 // Entry tokens don't need to be added to the list. They are 1629 // redundant. 1630 Changed = true; 1631 break; 1632 1633 case ISD::TokenFactor: 1634 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1635 // Queue up for processing. 1636 TFs.push_back(Op.getNode()); 1637 // Clean up in case the token factor is removed. 1638 AddToWorklist(Op.getNode()); 1639 Changed = true; 1640 break; 1641 } 1642 LLVM_FALLTHROUGH; 1643 1644 default: 1645 // Only add if it isn't already in the list. 1646 if (SeenOps.insert(Op.getNode()).second) 1647 Ops.push_back(Op); 1648 else 1649 Changed = true; 1650 break; 1651 } 1652 } 1653 } 1654 1655 // Remove Nodes that are chained to another node in the list. Do so 1656 // by walking up chains breath-first stopping when we've seen 1657 // another operand. In general we must climb to the EntryNode, but we can exit 1658 // early if we find all remaining work is associated with just one operand as 1659 // no further pruning is possible. 1660 1661 // List of nodes to search through and original Ops from which they originate. 1662 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1663 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1664 SmallPtrSet<SDNode *, 16> SeenChains; 1665 bool DidPruneOps = false; 1666 1667 unsigned NumLeftToConsider = 0; 1668 for (const SDValue &Op : Ops) { 1669 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1670 OpWorkCount.push_back(1); 1671 } 1672 1673 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1674 // If this is an Op, we can remove the op from the list. Remark any 1675 // search associated with it as from the current OpNumber. 1676 if (SeenOps.count(Op) != 0) { 1677 Changed = true; 1678 DidPruneOps = true; 1679 unsigned OrigOpNumber = 0; 1680 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1681 OrigOpNumber++; 1682 assert((OrigOpNumber != Ops.size()) && 1683 "expected to find TokenFactor Operand"); 1684 // Re-mark worklist from OrigOpNumber to OpNumber 1685 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1686 if (Worklist[i].second == OrigOpNumber) { 1687 Worklist[i].second = OpNumber; 1688 } 1689 } 1690 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1691 OpWorkCount[OrigOpNumber] = 0; 1692 NumLeftToConsider--; 1693 } 1694 // Add if it's a new chain 1695 if (SeenChains.insert(Op).second) { 1696 OpWorkCount[OpNumber]++; 1697 Worklist.push_back(std::make_pair(Op, OpNumber)); 1698 } 1699 }; 1700 1701 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1702 // We need at least be consider at least 2 Ops to prune. 1703 if (NumLeftToConsider <= 1) 1704 break; 1705 auto CurNode = Worklist[i].first; 1706 auto CurOpNumber = Worklist[i].second; 1707 assert((OpWorkCount[CurOpNumber] > 0) && 1708 "Node should not appear in worklist"); 1709 switch (CurNode->getOpcode()) { 1710 case ISD::EntryToken: 1711 // Hitting EntryToken is the only way for the search to terminate without 1712 // hitting 1713 // another operand's search. Prevent us from marking this operand 1714 // considered. 1715 NumLeftToConsider++; 1716 break; 1717 case ISD::TokenFactor: 1718 for (const SDValue &Op : CurNode->op_values()) 1719 AddToWorklist(i, Op.getNode(), CurOpNumber); 1720 break; 1721 case ISD::CopyFromReg: 1722 case ISD::CopyToReg: 1723 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1724 break; 1725 default: 1726 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1727 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1728 break; 1729 } 1730 OpWorkCount[CurOpNumber]--; 1731 if (OpWorkCount[CurOpNumber] == 0) 1732 NumLeftToConsider--; 1733 } 1734 1735 // If we've changed things around then replace token factor. 1736 if (Changed) { 1737 SDValue Result; 1738 if (Ops.empty()) { 1739 // The entry token is the only possible outcome. 1740 Result = DAG.getEntryNode(); 1741 } else { 1742 if (DidPruneOps) { 1743 SmallVector<SDValue, 8> PrunedOps; 1744 // 1745 for (const SDValue &Op : Ops) { 1746 if (SeenChains.count(Op.getNode()) == 0) 1747 PrunedOps.push_back(Op); 1748 } 1749 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1750 } else { 1751 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1752 } 1753 } 1754 return Result; 1755 } 1756 return SDValue(); 1757 } 1758 1759 /// MERGE_VALUES can always be eliminated. 1760 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1761 WorklistRemover DeadNodes(*this); 1762 // Replacing results may cause a different MERGE_VALUES to suddenly 1763 // be CSE'd with N, and carry its uses with it. Iterate until no 1764 // uses remain, to ensure that the node can be safely deleted. 1765 // First add the users of this node to the work list so that they 1766 // can be tried again once they have new operands. 1767 AddUsersToWorklist(N); 1768 do { 1769 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1770 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1771 } while (!N->use_empty()); 1772 deleteAndRecombine(N); 1773 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1774 } 1775 1776 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1777 /// ConstantSDNode pointer else nullptr. 1778 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1779 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1780 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1781 } 1782 1783 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1784 auto BinOpcode = BO->getOpcode(); 1785 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1786 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1787 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1788 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1789 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1790 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1791 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1792 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1793 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1794 "Unexpected binary operator"); 1795 1796 // Bail out if any constants are opaque because we can't constant fold those. 1797 SDValue C1 = BO->getOperand(1); 1798 if (!isConstantOrConstantVector(C1, true) && 1799 !isConstantFPBuildVectorOrConstantFP(C1)) 1800 return SDValue(); 1801 1802 // Don't do this unless the old select is going away. We want to eliminate the 1803 // binary operator, not replace a binop with a select. 1804 // TODO: Handle ISD::SELECT_CC. 1805 SDValue Sel = BO->getOperand(0); 1806 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1807 return SDValue(); 1808 1809 SDValue CT = Sel.getOperand(1); 1810 if (!isConstantOrConstantVector(CT, true) && 1811 !isConstantFPBuildVectorOrConstantFP(CT)) 1812 return SDValue(); 1813 1814 SDValue CF = Sel.getOperand(2); 1815 if (!isConstantOrConstantVector(CF, true) && 1816 !isConstantFPBuildVectorOrConstantFP(CF)) 1817 return SDValue(); 1818 1819 // We have a select-of-constants followed by a binary operator with a 1820 // constant. Eliminate the binop by pulling the constant math into the select. 1821 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1822 EVT VT = Sel.getValueType(); 1823 SDLoc DL(Sel); 1824 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1825 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) || 1826 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1827 "Failed to constant fold a binop with constant operands"); 1828 1829 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1830 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) || 1831 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1832 "Failed to constant fold a binop with constant operands"); 1833 1834 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1835 } 1836 1837 SDValue DAGCombiner::visitADD(SDNode *N) { 1838 SDValue N0 = N->getOperand(0); 1839 SDValue N1 = N->getOperand(1); 1840 EVT VT = N0.getValueType(); 1841 SDLoc DL(N); 1842 1843 // fold vector ops 1844 if (VT.isVector()) { 1845 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1846 return FoldedVOp; 1847 1848 // fold (add x, 0) -> x, vector edition 1849 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1850 return N0; 1851 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1852 return N1; 1853 } 1854 1855 // fold (add x, undef) -> undef 1856 if (N0.isUndef()) 1857 return N0; 1858 1859 if (N1.isUndef()) 1860 return N1; 1861 1862 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1863 // canonicalize constant to RHS 1864 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1865 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1866 // fold (add c1, c2) -> c1+c2 1867 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1868 N1.getNode()); 1869 } 1870 1871 // fold (add x, 0) -> x 1872 if (isNullConstant(N1)) 1873 return N0; 1874 1875 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1876 // fold ((c1-A)+c2) -> (c1+c2)-A 1877 if (N0.getOpcode() == ISD::SUB && 1878 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1879 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1880 return DAG.getNode(ISD::SUB, DL, VT, 1881 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1882 N0.getOperand(1)); 1883 } 1884 1885 // add (sext i1 X), 1 -> zext (not i1 X) 1886 // We don't transform this pattern: 1887 // add (zext i1 X), -1 -> sext (not i1 X) 1888 // because most (?) targets generate better code for the zext form. 1889 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1890 isOneConstantOrOneSplatConstant(N1)) { 1891 SDValue X = N0.getOperand(0); 1892 if ((!LegalOperations || 1893 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1894 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1895 X.getScalarValueSizeInBits() == 1) { 1896 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1897 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1898 } 1899 } 1900 } 1901 1902 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1903 return NewSel; 1904 1905 // reassociate add 1906 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1907 return RADD; 1908 1909 // fold ((0-A) + B) -> B-A 1910 if (N0.getOpcode() == ISD::SUB && 1911 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1912 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1913 1914 // fold (A + (0-B)) -> A-B 1915 if (N1.getOpcode() == ISD::SUB && 1916 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1917 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1918 1919 // fold (A+(B-A)) -> B 1920 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1921 return N1.getOperand(0); 1922 1923 // fold ((B-A)+A) -> B 1924 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1925 return N0.getOperand(0); 1926 1927 // fold (A+(B-(A+C))) to (B-C) 1928 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1929 N0 == N1.getOperand(1).getOperand(0)) 1930 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1931 N1.getOperand(1).getOperand(1)); 1932 1933 // fold (A+(B-(C+A))) to (B-C) 1934 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1935 N0 == N1.getOperand(1).getOperand(1)) 1936 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1937 N1.getOperand(1).getOperand(0)); 1938 1939 // fold (A+((B-A)+or-C)) to (B+or-C) 1940 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1941 N1.getOperand(0).getOpcode() == ISD::SUB && 1942 N0 == N1.getOperand(0).getOperand(1)) 1943 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1944 N1.getOperand(1)); 1945 1946 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1947 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1948 SDValue N00 = N0.getOperand(0); 1949 SDValue N01 = N0.getOperand(1); 1950 SDValue N10 = N1.getOperand(0); 1951 SDValue N11 = N1.getOperand(1); 1952 1953 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1954 return DAG.getNode(ISD::SUB, DL, VT, 1955 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1956 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1957 } 1958 1959 if (SimplifyDemandedBits(SDValue(N, 0))) 1960 return SDValue(N, 0); 1961 1962 // fold (a+b) -> (a|b) iff a and b share no bits. 1963 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1964 DAG.haveNoCommonBitsSet(N0, N1)) 1965 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1966 1967 if (SDValue Combined = visitADDLike(N0, N1, N)) 1968 return Combined; 1969 1970 if (SDValue Combined = visitADDLike(N1, N0, N)) 1971 return Combined; 1972 1973 return SDValue(); 1974 } 1975 1976 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 1977 bool Masked = false; 1978 1979 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 1980 while (true) { 1981 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 1982 V = V.getOperand(0); 1983 continue; 1984 } 1985 1986 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 1987 Masked = true; 1988 V = V.getOperand(0); 1989 continue; 1990 } 1991 1992 break; 1993 } 1994 1995 // If this is not a carry, return. 1996 if (V.getResNo() != 1) 1997 return SDValue(); 1998 1999 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2000 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2001 return SDValue(); 2002 2003 // If the result is masked, then no matter what kind of bool it is we can 2004 // return. If it isn't, then we need to make sure the bool type is either 0 or 2005 // 1 and not other values. 2006 if (Masked || 2007 TLI.getBooleanContents(V.getValueType()) == 2008 TargetLoweringBase::ZeroOrOneBooleanContent) 2009 return V; 2010 2011 return SDValue(); 2012 } 2013 2014 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 2015 EVT VT = N0.getValueType(); 2016 SDLoc DL(LocReference); 2017 2018 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2019 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2020 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 2021 return DAG.getNode(ISD::SUB, DL, VT, N0, 2022 DAG.getNode(ISD::SHL, DL, VT, 2023 N1.getOperand(0).getOperand(1), 2024 N1.getOperand(1))); 2025 2026 if (N1.getOpcode() == ISD::AND) { 2027 SDValue AndOp0 = N1.getOperand(0); 2028 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 2029 unsigned DestBits = VT.getScalarSizeInBits(); 2030 2031 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 2032 // and similar xforms where the inner op is either ~0 or 0. 2033 if (NumSignBits == DestBits && 2034 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 2035 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2036 } 2037 2038 // add (sext i1), X -> sub X, (zext i1) 2039 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2040 N0.getOperand(0).getValueType() == MVT::i1 && 2041 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2042 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2043 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2044 } 2045 2046 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2047 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2048 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2049 if (TN->getVT() == MVT::i1) { 2050 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2051 DAG.getConstant(1, DL, VT)); 2052 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2053 } 2054 } 2055 2056 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2057 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) 2058 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2059 N0, N1.getOperand(0), N1.getOperand(2)); 2060 2061 // (add X, Carry) -> (addcarry X, 0, Carry) 2062 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2063 if (SDValue Carry = getAsCarry(TLI, N1)) 2064 return DAG.getNode(ISD::ADDCARRY, DL, 2065 DAG.getVTList(VT, Carry.getValueType()), N0, 2066 DAG.getConstant(0, DL, VT), Carry); 2067 2068 return SDValue(); 2069 } 2070 2071 SDValue DAGCombiner::visitADDC(SDNode *N) { 2072 SDValue N0 = N->getOperand(0); 2073 SDValue N1 = N->getOperand(1); 2074 EVT VT = N0.getValueType(); 2075 SDLoc DL(N); 2076 2077 // If the flag result is dead, turn this into an ADD. 2078 if (!N->hasAnyUseOfValue(1)) 2079 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2080 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2081 2082 // canonicalize constant to RHS. 2083 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2084 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2085 if (N0C && !N1C) 2086 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2087 2088 // fold (addc x, 0) -> x + no carry out 2089 if (isNullConstant(N1)) 2090 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2091 DL, MVT::Glue)); 2092 2093 // If it cannot overflow, transform into an add. 2094 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2095 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2096 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2097 2098 return SDValue(); 2099 } 2100 2101 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2102 SDValue N0 = N->getOperand(0); 2103 SDValue N1 = N->getOperand(1); 2104 EVT VT = N0.getValueType(); 2105 if (VT.isVector()) 2106 return SDValue(); 2107 2108 EVT CarryVT = N->getValueType(1); 2109 SDLoc DL(N); 2110 2111 // If the flag result is dead, turn this into an ADD. 2112 if (!N->hasAnyUseOfValue(1)) 2113 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2114 DAG.getUNDEF(CarryVT)); 2115 2116 // canonicalize constant to RHS. 2117 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2118 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2119 if (N0C && !N1C) 2120 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2121 2122 // fold (uaddo x, 0) -> x + no carry out 2123 if (isNullConstant(N1)) 2124 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2125 2126 // If it cannot overflow, transform into an add. 2127 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2128 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2129 DAG.getConstant(0, DL, CarryVT)); 2130 2131 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2132 return Combined; 2133 2134 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2135 return Combined; 2136 2137 return SDValue(); 2138 } 2139 2140 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2141 auto VT = N0.getValueType(); 2142 2143 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2144 // If Y + 1 cannot overflow. 2145 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2146 SDValue Y = N1.getOperand(0); 2147 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2148 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2149 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2150 N1.getOperand(2)); 2151 } 2152 2153 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2154 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2155 if (SDValue Carry = getAsCarry(TLI, N1)) 2156 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2157 DAG.getConstant(0, SDLoc(N), VT), Carry); 2158 2159 return SDValue(); 2160 } 2161 2162 SDValue DAGCombiner::visitADDE(SDNode *N) { 2163 SDValue N0 = N->getOperand(0); 2164 SDValue N1 = N->getOperand(1); 2165 SDValue CarryIn = N->getOperand(2); 2166 2167 // canonicalize constant to RHS 2168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2170 if (N0C && !N1C) 2171 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2172 N1, N0, CarryIn); 2173 2174 // fold (adde x, y, false) -> (addc x, y) 2175 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2176 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2177 2178 return SDValue(); 2179 } 2180 2181 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2182 SDValue N0 = N->getOperand(0); 2183 SDValue N1 = N->getOperand(1); 2184 SDValue CarryIn = N->getOperand(2); 2185 SDLoc DL(N); 2186 2187 // canonicalize constant to RHS 2188 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2189 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2190 if (N0C && !N1C) 2191 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2192 2193 // fold (addcarry x, y, false) -> (uaddo x, y) 2194 if (isNullConstant(CarryIn)) 2195 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2196 2197 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2198 if (isNullConstant(N0) && isNullConstant(N1)) { 2199 EVT VT = N0.getValueType(); 2200 EVT CarryVT = CarryIn.getValueType(); 2201 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2202 AddToWorklist(CarryExt.getNode()); 2203 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2204 DAG.getConstant(1, DL, VT)), 2205 DAG.getConstant(0, DL, CarryVT)); 2206 } 2207 2208 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2209 return Combined; 2210 2211 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2212 return Combined; 2213 2214 return SDValue(); 2215 } 2216 2217 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2218 SDNode *N) { 2219 // Iff the flag result is dead: 2220 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2221 if ((N0.getOpcode() == ISD::ADD || 2222 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2223 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2224 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2225 N0.getOperand(0), N0.getOperand(1), CarryIn); 2226 2227 /** 2228 * When one of the addcarry argument is itself a carry, we may be facing 2229 * a diamond carry propagation. In which case we try to transform the DAG 2230 * to ensure linear carry propagation if that is possible. 2231 * 2232 * We are trying to get: 2233 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2234 */ 2235 if (auto Y = getAsCarry(TLI, N1)) { 2236 /** 2237 * (uaddo A, B) 2238 * / \ 2239 * Carry Sum 2240 * | \ 2241 * | (addcarry *, 0, Z) 2242 * | / 2243 * \ Carry 2244 * | / 2245 * (addcarry X, *, *) 2246 */ 2247 if (Y.getOpcode() == ISD::UADDO && 2248 CarryIn.getResNo() == 1 && 2249 CarryIn.getOpcode() == ISD::ADDCARRY && 2250 isNullConstant(CarryIn.getOperand(1)) && 2251 CarryIn.getOperand(0) == Y.getValue(0)) { 2252 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2253 Y.getOperand(0), Y.getOperand(1), 2254 CarryIn.getOperand(2)); 2255 AddToWorklist(NewY.getNode()); 2256 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2257 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2258 NewY.getValue(1)); 2259 } 2260 } 2261 2262 return SDValue(); 2263 } 2264 2265 // Since it may not be valid to emit a fold to zero for vector initializers 2266 // check if we can before folding. 2267 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2268 SelectionDAG &DAG, bool LegalOperations, 2269 bool LegalTypes) { 2270 if (!VT.isVector()) 2271 return DAG.getConstant(0, DL, VT); 2272 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2273 return DAG.getConstant(0, DL, VT); 2274 return SDValue(); 2275 } 2276 2277 SDValue DAGCombiner::visitSUB(SDNode *N) { 2278 SDValue N0 = N->getOperand(0); 2279 SDValue N1 = N->getOperand(1); 2280 EVT VT = N0.getValueType(); 2281 SDLoc DL(N); 2282 2283 // fold vector ops 2284 if (VT.isVector()) { 2285 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2286 return FoldedVOp; 2287 2288 // fold (sub x, 0) -> x, vector edition 2289 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2290 return N0; 2291 } 2292 2293 // fold (sub x, x) -> 0 2294 // FIXME: Refactor this and xor and other similar operations together. 2295 if (N0 == N1) 2296 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2297 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2298 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2299 // fold (sub c1, c2) -> c1-c2 2300 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2301 N1.getNode()); 2302 } 2303 2304 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2305 return NewSel; 2306 2307 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2308 2309 // fold (sub x, c) -> (add x, -c) 2310 if (N1C) { 2311 return DAG.getNode(ISD::ADD, DL, VT, N0, 2312 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2313 } 2314 2315 if (isNullConstantOrNullSplatConstant(N0)) { 2316 unsigned BitWidth = VT.getScalarSizeInBits(); 2317 // Right-shifting everything out but the sign bit followed by negation is 2318 // the same as flipping arithmetic/logical shift type without the negation: 2319 // -(X >>u 31) -> (X >>s 31) 2320 // -(X >>s 31) -> (X >>u 31) 2321 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2322 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2323 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2324 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2325 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2326 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2327 } 2328 } 2329 2330 // 0 - X --> 0 if the sub is NUW. 2331 if (N->getFlags().hasNoUnsignedWrap()) 2332 return N0; 2333 2334 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2335 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2336 // N1 must be 0 because negating the minimum signed value is undefined. 2337 if (N->getFlags().hasNoSignedWrap()) 2338 return N0; 2339 2340 // 0 - X --> X if X is 0 or the minimum signed value. 2341 return N1; 2342 } 2343 } 2344 2345 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2346 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2347 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2348 2349 // fold A-(A-B) -> B 2350 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2351 return N1.getOperand(1); 2352 2353 // fold (A+B)-A -> B 2354 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2355 return N0.getOperand(1); 2356 2357 // fold (A+B)-B -> A 2358 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2359 return N0.getOperand(0); 2360 2361 // fold C2-(A+C1) -> (C2-C1)-A 2362 if (N1.getOpcode() == ISD::ADD) { 2363 SDValue N11 = N1.getOperand(1); 2364 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2365 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2366 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2367 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2368 } 2369 } 2370 2371 // fold ((A+(B+or-C))-B) -> A+or-C 2372 if (N0.getOpcode() == ISD::ADD && 2373 (N0.getOperand(1).getOpcode() == ISD::SUB || 2374 N0.getOperand(1).getOpcode() == ISD::ADD) && 2375 N0.getOperand(1).getOperand(0) == N1) 2376 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2377 N0.getOperand(1).getOperand(1)); 2378 2379 // fold ((A+(C+B))-B) -> A+C 2380 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2381 N0.getOperand(1).getOperand(1) == N1) 2382 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2383 N0.getOperand(1).getOperand(0)); 2384 2385 // fold ((A-(B-C))-C) -> A-B 2386 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2387 N0.getOperand(1).getOperand(1) == N1) 2388 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2389 N0.getOperand(1).getOperand(0)); 2390 2391 // If either operand of a sub is undef, the result is undef 2392 if (N0.isUndef()) 2393 return N0; 2394 if (N1.isUndef()) 2395 return N1; 2396 2397 // If the relocation model supports it, consider symbol offsets. 2398 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2399 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2400 // fold (sub Sym, c) -> Sym-c 2401 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2402 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2403 GA->getOffset() - 2404 (uint64_t)N1C->getSExtValue()); 2405 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2406 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2407 if (GA->getGlobal() == GB->getGlobal()) 2408 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2409 DL, VT); 2410 } 2411 2412 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2413 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2414 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2415 if (TN->getVT() == MVT::i1) { 2416 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2417 DAG.getConstant(1, DL, VT)); 2418 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2419 } 2420 } 2421 2422 return SDValue(); 2423 } 2424 2425 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2426 SDValue N0 = N->getOperand(0); 2427 SDValue N1 = N->getOperand(1); 2428 EVT VT = N0.getValueType(); 2429 SDLoc DL(N); 2430 2431 // If the flag result is dead, turn this into an SUB. 2432 if (!N->hasAnyUseOfValue(1)) 2433 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2434 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2435 2436 // fold (subc x, x) -> 0 + no borrow 2437 if (N0 == N1) 2438 return CombineTo(N, DAG.getConstant(0, DL, VT), 2439 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2440 2441 // fold (subc x, 0) -> x + no borrow 2442 if (isNullConstant(N1)) 2443 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2444 2445 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2446 if (isAllOnesConstant(N0)) 2447 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2448 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2449 2450 return SDValue(); 2451 } 2452 2453 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2454 SDValue N0 = N->getOperand(0); 2455 SDValue N1 = N->getOperand(1); 2456 EVT VT = N0.getValueType(); 2457 if (VT.isVector()) 2458 return SDValue(); 2459 2460 EVT CarryVT = N->getValueType(1); 2461 SDLoc DL(N); 2462 2463 // If the flag result is dead, turn this into an SUB. 2464 if (!N->hasAnyUseOfValue(1)) 2465 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2466 DAG.getUNDEF(CarryVT)); 2467 2468 // fold (usubo x, x) -> 0 + no borrow 2469 if (N0 == N1) 2470 return CombineTo(N, DAG.getConstant(0, DL, VT), 2471 DAG.getConstant(0, DL, CarryVT)); 2472 2473 // fold (usubo x, 0) -> x + no borrow 2474 if (isNullConstant(N1)) 2475 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2476 2477 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2478 if (isAllOnesConstant(N0)) 2479 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2480 DAG.getConstant(0, DL, CarryVT)); 2481 2482 return SDValue(); 2483 } 2484 2485 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2486 SDValue N0 = N->getOperand(0); 2487 SDValue N1 = N->getOperand(1); 2488 SDValue CarryIn = N->getOperand(2); 2489 2490 // fold (sube x, y, false) -> (subc x, y) 2491 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2492 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2493 2494 return SDValue(); 2495 } 2496 2497 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2498 SDValue N0 = N->getOperand(0); 2499 SDValue N1 = N->getOperand(1); 2500 SDValue CarryIn = N->getOperand(2); 2501 2502 // fold (subcarry x, y, false) -> (usubo x, y) 2503 if (isNullConstant(CarryIn)) 2504 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2505 2506 return SDValue(); 2507 } 2508 2509 SDValue DAGCombiner::visitMUL(SDNode *N) { 2510 SDValue N0 = N->getOperand(0); 2511 SDValue N1 = N->getOperand(1); 2512 EVT VT = N0.getValueType(); 2513 2514 // fold (mul x, undef) -> 0 2515 if (N0.isUndef() || N1.isUndef()) 2516 return DAG.getConstant(0, SDLoc(N), VT); 2517 2518 bool N0IsConst = false; 2519 bool N1IsConst = false; 2520 bool N1IsOpaqueConst = false; 2521 bool N0IsOpaqueConst = false; 2522 APInt ConstValue0, ConstValue1; 2523 // fold vector ops 2524 if (VT.isVector()) { 2525 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2526 return FoldedVOp; 2527 2528 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2529 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2530 } else { 2531 N0IsConst = isa<ConstantSDNode>(N0); 2532 if (N0IsConst) { 2533 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2534 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2535 } 2536 N1IsConst = isa<ConstantSDNode>(N1); 2537 if (N1IsConst) { 2538 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2539 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2540 } 2541 } 2542 2543 // fold (mul c1, c2) -> c1*c2 2544 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2545 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2546 N0.getNode(), N1.getNode()); 2547 2548 // canonicalize constant to RHS (vector doesn't have to splat) 2549 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2550 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2551 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2552 // fold (mul x, 0) -> 0 2553 if (N1IsConst && ConstValue1.isNullValue()) 2554 return N1; 2555 // We require a splat of the entire scalar bit width for non-contiguous 2556 // bit patterns. 2557 bool IsFullSplat = 2558 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2559 // fold (mul x, 1) -> x 2560 if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat) 2561 return N0; 2562 2563 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2564 return NewSel; 2565 2566 // fold (mul x, -1) -> 0-x 2567 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2568 SDLoc DL(N); 2569 return DAG.getNode(ISD::SUB, DL, VT, 2570 DAG.getConstant(0, DL, VT), N0); 2571 } 2572 // fold (mul x, (1 << c)) -> x << c 2573 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2574 IsFullSplat) { 2575 SDLoc DL(N); 2576 return DAG.getNode(ISD::SHL, DL, VT, N0, 2577 DAG.getConstant(ConstValue1.logBase2(), DL, 2578 getShiftAmountTy(N0.getValueType()))); 2579 } 2580 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2581 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2582 IsFullSplat) { 2583 unsigned Log2Val = (-ConstValue1).logBase2(); 2584 SDLoc DL(N); 2585 // FIXME: If the input is something that is easily negated (e.g. a 2586 // single-use add), we should put the negate there. 2587 return DAG.getNode(ISD::SUB, DL, VT, 2588 DAG.getConstant(0, DL, VT), 2589 DAG.getNode(ISD::SHL, DL, VT, N0, 2590 DAG.getConstant(Log2Val, DL, 2591 getShiftAmountTy(N0.getValueType())))); 2592 } 2593 2594 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2595 if (N0.getOpcode() == ISD::SHL && 2596 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2597 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2598 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2599 if (isConstantOrConstantVector(C3)) 2600 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2601 } 2602 2603 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2604 // use. 2605 { 2606 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2607 2608 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2609 if (N0.getOpcode() == ISD::SHL && 2610 isConstantOrConstantVector(N0.getOperand(1)) && 2611 N0.getNode()->hasOneUse()) { 2612 Sh = N0; Y = N1; 2613 } else if (N1.getOpcode() == ISD::SHL && 2614 isConstantOrConstantVector(N1.getOperand(1)) && 2615 N1.getNode()->hasOneUse()) { 2616 Sh = N1; Y = N0; 2617 } 2618 2619 if (Sh.getNode()) { 2620 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2621 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2622 } 2623 } 2624 2625 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2626 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2627 N0.getOpcode() == ISD::ADD && 2628 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2629 isMulAddWithConstProfitable(N, N0, N1)) 2630 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2631 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2632 N0.getOperand(0), N1), 2633 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2634 N0.getOperand(1), N1)); 2635 2636 // reassociate mul 2637 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2638 return RMUL; 2639 2640 return SDValue(); 2641 } 2642 2643 /// Return true if divmod libcall is available. 2644 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2645 const TargetLowering &TLI) { 2646 RTLIB::Libcall LC; 2647 EVT NodeType = Node->getValueType(0); 2648 if (!NodeType.isSimple()) 2649 return false; 2650 switch (NodeType.getSimpleVT().SimpleTy) { 2651 default: return false; // No libcall for vector types. 2652 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2653 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2654 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2655 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2656 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2657 } 2658 2659 return TLI.getLibcallName(LC) != nullptr; 2660 } 2661 2662 /// Issue divrem if both quotient and remainder are needed. 2663 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2664 if (Node->use_empty()) 2665 return SDValue(); // This is a dead node, leave it alone. 2666 2667 unsigned Opcode = Node->getOpcode(); 2668 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2669 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2670 2671 // DivMod lib calls can still work on non-legal types if using lib-calls. 2672 EVT VT = Node->getValueType(0); 2673 if (VT.isVector() || !VT.isInteger()) 2674 return SDValue(); 2675 2676 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2677 return SDValue(); 2678 2679 // If DIVREM is going to get expanded into a libcall, 2680 // but there is no libcall available, then don't combine. 2681 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2682 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2683 return SDValue(); 2684 2685 // If div is legal, it's better to do the normal expansion 2686 unsigned OtherOpcode = 0; 2687 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2688 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2689 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2690 return SDValue(); 2691 } else { 2692 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2693 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2694 return SDValue(); 2695 } 2696 2697 SDValue Op0 = Node->getOperand(0); 2698 SDValue Op1 = Node->getOperand(1); 2699 SDValue combined; 2700 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2701 UE = Op0.getNode()->use_end(); UI != UE;) { 2702 SDNode *User = *UI++; 2703 if (User == Node || User->use_empty()) 2704 continue; 2705 // Convert the other matching node(s), too; 2706 // otherwise, the DIVREM may get target-legalized into something 2707 // target-specific that we won't be able to recognize. 2708 unsigned UserOpc = User->getOpcode(); 2709 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2710 User->getOperand(0) == Op0 && 2711 User->getOperand(1) == Op1) { 2712 if (!combined) { 2713 if (UserOpc == OtherOpcode) { 2714 SDVTList VTs = DAG.getVTList(VT, VT); 2715 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2716 } else if (UserOpc == DivRemOpc) { 2717 combined = SDValue(User, 0); 2718 } else { 2719 assert(UserOpc == Opcode); 2720 continue; 2721 } 2722 } 2723 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2724 CombineTo(User, combined); 2725 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2726 CombineTo(User, combined.getValue(1)); 2727 } 2728 } 2729 return combined; 2730 } 2731 2732 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2733 SDValue N0 = N->getOperand(0); 2734 SDValue N1 = N->getOperand(1); 2735 EVT VT = N->getValueType(0); 2736 SDLoc DL(N); 2737 2738 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2739 return DAG.getUNDEF(VT); 2740 2741 // undef / X -> 0 2742 // undef % X -> 0 2743 if (N0.isUndef()) 2744 return DAG.getConstant(0, DL, VT); 2745 2746 return SDValue(); 2747 } 2748 2749 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2750 SDValue N0 = N->getOperand(0); 2751 SDValue N1 = N->getOperand(1); 2752 EVT VT = N->getValueType(0); 2753 2754 // fold vector ops 2755 if (VT.isVector()) 2756 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2757 return FoldedVOp; 2758 2759 SDLoc DL(N); 2760 2761 // fold (sdiv c1, c2) -> c1/c2 2762 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2763 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2764 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2765 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2766 // fold (sdiv X, 1) -> X 2767 if (N1C && N1C->isOne()) 2768 return N0; 2769 // fold (sdiv X, -1) -> 0-X 2770 if (N1C && N1C->isAllOnesValue()) 2771 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2772 2773 if (SDValue V = simplifyDivRem(N, DAG)) 2774 return V; 2775 2776 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2777 return NewSel; 2778 2779 // If we know the sign bits of both operands are zero, strength reduce to a 2780 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2781 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2782 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2783 2784 // fold (sdiv X, pow2) -> simple ops after legalize 2785 // FIXME: We check for the exact bit here because the generic lowering gives 2786 // better results in that case. The target-specific lowering should learn how 2787 // to handle exact sdivs efficiently. 2788 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2789 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2790 (-N1C->getAPIntValue()).isPowerOf2())) { 2791 // Target-specific implementation of sdiv x, pow2. 2792 if (SDValue Res = BuildSDIVPow2(N)) 2793 return Res; 2794 2795 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2796 2797 // Splat the sign bit into the register 2798 SDValue SGN = 2799 DAG.getNode(ISD::SRA, DL, VT, N0, 2800 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2801 getShiftAmountTy(N0.getValueType()))); 2802 AddToWorklist(SGN.getNode()); 2803 2804 // Add (N0 < 0) ? abs2 - 1 : 0; 2805 SDValue SRL = 2806 DAG.getNode(ISD::SRL, DL, VT, SGN, 2807 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2808 getShiftAmountTy(SGN.getValueType()))); 2809 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2810 AddToWorklist(SRL.getNode()); 2811 AddToWorklist(ADD.getNode()); // Divide by pow2 2812 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2813 DAG.getConstant(lg2, DL, 2814 getShiftAmountTy(ADD.getValueType()))); 2815 2816 // If we're dividing by a positive value, we're done. Otherwise, we must 2817 // negate the result. 2818 if (N1C->getAPIntValue().isNonNegative()) 2819 return SRA; 2820 2821 AddToWorklist(SRA.getNode()); 2822 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2823 } 2824 2825 // If integer divide is expensive and we satisfy the requirements, emit an 2826 // alternate sequence. Targets may check function attributes for size/speed 2827 // trade-offs. 2828 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2829 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2830 if (SDValue Op = BuildSDIV(N)) 2831 return Op; 2832 2833 // sdiv, srem -> sdivrem 2834 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2835 // true. Otherwise, we break the simplification logic in visitREM(). 2836 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2837 if (SDValue DivRem = useDivRem(N)) 2838 return DivRem; 2839 2840 return SDValue(); 2841 } 2842 2843 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2844 SDValue N0 = N->getOperand(0); 2845 SDValue N1 = N->getOperand(1); 2846 EVT VT = N->getValueType(0); 2847 2848 // fold vector ops 2849 if (VT.isVector()) 2850 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2851 return FoldedVOp; 2852 2853 SDLoc DL(N); 2854 2855 // fold (udiv c1, c2) -> c1/c2 2856 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2857 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2858 if (N0C && N1C) 2859 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2860 N0C, N1C)) 2861 return Folded; 2862 2863 if (SDValue V = simplifyDivRem(N, DAG)) 2864 return V; 2865 2866 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2867 return NewSel; 2868 2869 // fold (udiv x, (1 << c)) -> x >>u c 2870 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2871 DAG.isKnownToBeAPowerOfTwo(N1)) { 2872 SDValue LogBase2 = BuildLogBase2(N1, DL); 2873 AddToWorklist(LogBase2.getNode()); 2874 2875 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2876 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2877 AddToWorklist(Trunc.getNode()); 2878 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2879 } 2880 2881 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2882 if (N1.getOpcode() == ISD::SHL) { 2883 SDValue N10 = N1.getOperand(0); 2884 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2885 DAG.isKnownToBeAPowerOfTwo(N10)) { 2886 SDValue LogBase2 = BuildLogBase2(N10, DL); 2887 AddToWorklist(LogBase2.getNode()); 2888 2889 EVT ADDVT = N1.getOperand(1).getValueType(); 2890 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2891 AddToWorklist(Trunc.getNode()); 2892 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2893 AddToWorklist(Add.getNode()); 2894 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2895 } 2896 } 2897 2898 // fold (udiv x, c) -> alternate 2899 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2900 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2901 if (SDValue Op = BuildUDIV(N)) 2902 return Op; 2903 2904 // sdiv, srem -> sdivrem 2905 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2906 // true. Otherwise, we break the simplification logic in visitREM(). 2907 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2908 if (SDValue DivRem = useDivRem(N)) 2909 return DivRem; 2910 2911 return SDValue(); 2912 } 2913 2914 // handles ISD::SREM and ISD::UREM 2915 SDValue DAGCombiner::visitREM(SDNode *N) { 2916 unsigned Opcode = N->getOpcode(); 2917 SDValue N0 = N->getOperand(0); 2918 SDValue N1 = N->getOperand(1); 2919 EVT VT = N->getValueType(0); 2920 bool isSigned = (Opcode == ISD::SREM); 2921 SDLoc DL(N); 2922 2923 // fold (rem c1, c2) -> c1%c2 2924 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2925 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2926 if (N0C && N1C) 2927 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2928 return Folded; 2929 2930 if (SDValue V = simplifyDivRem(N, DAG)) 2931 return V; 2932 2933 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2934 return NewSel; 2935 2936 if (isSigned) { 2937 // If we know the sign bits of both operands are zero, strength reduce to a 2938 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2939 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2940 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2941 } else { 2942 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2943 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2944 // fold (urem x, pow2) -> (and x, pow2-1) 2945 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2946 AddToWorklist(Add.getNode()); 2947 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2948 } 2949 if (N1.getOpcode() == ISD::SHL && 2950 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2951 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2952 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2953 AddToWorklist(Add.getNode()); 2954 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2955 } 2956 } 2957 2958 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2959 2960 // If X/C can be simplified by the division-by-constant logic, lower 2961 // X%C to the equivalent of X-X/C*C. 2962 // To avoid mangling nodes, this simplification requires that the combine() 2963 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2964 // against this by skipping the simplification if isIntDivCheap(). When 2965 // div is not cheap, combine will not return a DIVREM. Regardless, 2966 // checking cheapness here makes sense since the simplification results in 2967 // fatter code. 2968 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2969 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2970 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2971 AddToWorklist(Div.getNode()); 2972 SDValue OptimizedDiv = combine(Div.getNode()); 2973 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2974 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2975 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2976 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2977 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2978 AddToWorklist(Mul.getNode()); 2979 return Sub; 2980 } 2981 } 2982 2983 // sdiv, srem -> sdivrem 2984 if (SDValue DivRem = useDivRem(N)) 2985 return DivRem.getValue(1); 2986 2987 return SDValue(); 2988 } 2989 2990 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2991 SDValue N0 = N->getOperand(0); 2992 SDValue N1 = N->getOperand(1); 2993 EVT VT = N->getValueType(0); 2994 SDLoc DL(N); 2995 2996 // fold (mulhs x, 0) -> 0 2997 if (isNullConstant(N1)) 2998 return N1; 2999 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3000 if (isOneConstant(N1)) { 3001 SDLoc DL(N); 3002 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3003 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3004 getShiftAmountTy(N0.getValueType()))); 3005 } 3006 // fold (mulhs x, undef) -> 0 3007 if (N0.isUndef() || N1.isUndef()) 3008 return DAG.getConstant(0, SDLoc(N), VT); 3009 3010 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3011 // plus a shift. 3012 if (VT.isSimple() && !VT.isVector()) { 3013 MVT Simple = VT.getSimpleVT(); 3014 unsigned SimpleSize = Simple.getSizeInBits(); 3015 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3016 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3017 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3018 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3019 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3020 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3021 DAG.getConstant(SimpleSize, DL, 3022 getShiftAmountTy(N1.getValueType()))); 3023 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3024 } 3025 } 3026 3027 return SDValue(); 3028 } 3029 3030 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3031 SDValue N0 = N->getOperand(0); 3032 SDValue N1 = N->getOperand(1); 3033 EVT VT = N->getValueType(0); 3034 SDLoc DL(N); 3035 3036 // fold (mulhu x, 0) -> 0 3037 if (isNullConstant(N1)) 3038 return N1; 3039 // fold (mulhu x, 1) -> 0 3040 if (isOneConstant(N1)) 3041 return DAG.getConstant(0, DL, N0.getValueType()); 3042 // fold (mulhu x, undef) -> 0 3043 if (N0.isUndef() || N1.isUndef()) 3044 return DAG.getConstant(0, DL, VT); 3045 3046 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3047 // plus a shift. 3048 if (VT.isSimple() && !VT.isVector()) { 3049 MVT Simple = VT.getSimpleVT(); 3050 unsigned SimpleSize = Simple.getSizeInBits(); 3051 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3052 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3053 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3054 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3055 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3056 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3057 DAG.getConstant(SimpleSize, DL, 3058 getShiftAmountTy(N1.getValueType()))); 3059 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3060 } 3061 } 3062 3063 return SDValue(); 3064 } 3065 3066 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3067 /// give the opcodes for the two computations that are being performed. Return 3068 /// true if a simplification was made. 3069 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3070 unsigned HiOp) { 3071 // If the high half is not needed, just compute the low half. 3072 bool HiExists = N->hasAnyUseOfValue(1); 3073 if (!HiExists && 3074 (!LegalOperations || 3075 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3076 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3077 return CombineTo(N, Res, Res); 3078 } 3079 3080 // If the low half is not needed, just compute the high half. 3081 bool LoExists = N->hasAnyUseOfValue(0); 3082 if (!LoExists && 3083 (!LegalOperations || 3084 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 3085 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3086 return CombineTo(N, Res, Res); 3087 } 3088 3089 // If both halves are used, return as it is. 3090 if (LoExists && HiExists) 3091 return SDValue(); 3092 3093 // If the two computed results can be simplified separately, separate them. 3094 if (LoExists) { 3095 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3096 AddToWorklist(Lo.getNode()); 3097 SDValue LoOpt = combine(Lo.getNode()); 3098 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3099 (!LegalOperations || 3100 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3101 return CombineTo(N, LoOpt, LoOpt); 3102 } 3103 3104 if (HiExists) { 3105 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3106 AddToWorklist(Hi.getNode()); 3107 SDValue HiOpt = combine(Hi.getNode()); 3108 if (HiOpt.getNode() && HiOpt != Hi && 3109 (!LegalOperations || 3110 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3111 return CombineTo(N, HiOpt, HiOpt); 3112 } 3113 3114 return SDValue(); 3115 } 3116 3117 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3118 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3119 return Res; 3120 3121 EVT VT = N->getValueType(0); 3122 SDLoc DL(N); 3123 3124 // If the type is twice as wide is legal, transform the mulhu to a wider 3125 // multiply plus a shift. 3126 if (VT.isSimple() && !VT.isVector()) { 3127 MVT Simple = VT.getSimpleVT(); 3128 unsigned SimpleSize = Simple.getSizeInBits(); 3129 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3130 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3131 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3132 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3133 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3134 // Compute the high part as N1. 3135 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3136 DAG.getConstant(SimpleSize, DL, 3137 getShiftAmountTy(Lo.getValueType()))); 3138 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3139 // Compute the low part as N0. 3140 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3141 return CombineTo(N, Lo, Hi); 3142 } 3143 } 3144 3145 return SDValue(); 3146 } 3147 3148 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3149 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3150 return Res; 3151 3152 EVT VT = N->getValueType(0); 3153 SDLoc DL(N); 3154 3155 // If the type is twice as wide is legal, transform the mulhu to a wider 3156 // multiply plus a shift. 3157 if (VT.isSimple() && !VT.isVector()) { 3158 MVT Simple = VT.getSimpleVT(); 3159 unsigned SimpleSize = Simple.getSizeInBits(); 3160 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3161 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3162 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3163 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3164 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3165 // Compute the high part as N1. 3166 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3167 DAG.getConstant(SimpleSize, DL, 3168 getShiftAmountTy(Lo.getValueType()))); 3169 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3170 // Compute the low part as N0. 3171 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3172 return CombineTo(N, Lo, Hi); 3173 } 3174 } 3175 3176 return SDValue(); 3177 } 3178 3179 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3180 // (smulo x, 2) -> (saddo x, x) 3181 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3182 if (C2->getAPIntValue() == 2) 3183 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3184 N->getOperand(0), N->getOperand(0)); 3185 3186 return SDValue(); 3187 } 3188 3189 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3190 // (umulo x, 2) -> (uaddo x, x) 3191 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3192 if (C2->getAPIntValue() == 2) 3193 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3194 N->getOperand(0), N->getOperand(0)); 3195 3196 return SDValue(); 3197 } 3198 3199 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3200 SDValue N0 = N->getOperand(0); 3201 SDValue N1 = N->getOperand(1); 3202 EVT VT = N0.getValueType(); 3203 3204 // fold vector ops 3205 if (VT.isVector()) 3206 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3207 return FoldedVOp; 3208 3209 // fold (add c1, c2) -> c1+c2 3210 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3211 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3212 if (N0C && N1C) 3213 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3214 3215 // canonicalize constant to RHS 3216 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3217 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3218 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3219 3220 return SDValue(); 3221 } 3222 3223 /// If this is a binary operator with two operands of the same opcode, try to 3224 /// simplify it. 3225 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3226 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3227 EVT VT = N0.getValueType(); 3228 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3229 3230 // Bail early if none of these transforms apply. 3231 if (N0.getNumOperands() == 0) return SDValue(); 3232 3233 // For each of OP in AND/OR/XOR: 3234 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3235 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3236 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3237 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3238 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3239 // 3240 // do not sink logical op inside of a vector extend, since it may combine 3241 // into a vsetcc. 3242 EVT Op0VT = N0.getOperand(0).getValueType(); 3243 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3244 N0.getOpcode() == ISD::SIGN_EXTEND || 3245 N0.getOpcode() == ISD::BSWAP || 3246 // Avoid infinite looping with PromoteIntBinOp. 3247 (N0.getOpcode() == ISD::ANY_EXTEND && 3248 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3249 (N0.getOpcode() == ISD::TRUNCATE && 3250 (!TLI.isZExtFree(VT, Op0VT) || 3251 !TLI.isTruncateFree(Op0VT, VT)) && 3252 TLI.isTypeLegal(Op0VT))) && 3253 !VT.isVector() && 3254 Op0VT == N1.getOperand(0).getValueType() && 3255 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3256 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3257 N0.getOperand(0).getValueType(), 3258 N0.getOperand(0), N1.getOperand(0)); 3259 AddToWorklist(ORNode.getNode()); 3260 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3261 } 3262 3263 // For each of OP in SHL/SRL/SRA/AND... 3264 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3265 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3266 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3267 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3268 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3269 N0.getOperand(1) == N1.getOperand(1)) { 3270 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3271 N0.getOperand(0).getValueType(), 3272 N0.getOperand(0), N1.getOperand(0)); 3273 AddToWorklist(ORNode.getNode()); 3274 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3275 ORNode, N0.getOperand(1)); 3276 } 3277 3278 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3279 // Only perform this optimization up until type legalization, before 3280 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3281 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3282 // we don't want to undo this promotion. 3283 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3284 // on scalars. 3285 if ((N0.getOpcode() == ISD::BITCAST || 3286 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3287 Level <= AfterLegalizeTypes) { 3288 SDValue In0 = N0.getOperand(0); 3289 SDValue In1 = N1.getOperand(0); 3290 EVT In0Ty = In0.getValueType(); 3291 EVT In1Ty = In1.getValueType(); 3292 SDLoc DL(N); 3293 // If both incoming values are integers, and the original types are the 3294 // same. 3295 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3296 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3297 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3298 AddToWorklist(Op.getNode()); 3299 return BC; 3300 } 3301 } 3302 3303 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3304 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3305 // If both shuffles use the same mask, and both shuffle within a single 3306 // vector, then it is worthwhile to move the swizzle after the operation. 3307 // The type-legalizer generates this pattern when loading illegal 3308 // vector types from memory. In many cases this allows additional shuffle 3309 // optimizations. 3310 // There are other cases where moving the shuffle after the xor/and/or 3311 // is profitable even if shuffles don't perform a swizzle. 3312 // If both shuffles use the same mask, and both shuffles have the same first 3313 // or second operand, then it might still be profitable to move the shuffle 3314 // after the xor/and/or operation. 3315 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3316 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3317 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3318 3319 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3320 "Inputs to shuffles are not the same type"); 3321 3322 // Check that both shuffles use the same mask. The masks are known to be of 3323 // the same length because the result vector type is the same. 3324 // Check also that shuffles have only one use to avoid introducing extra 3325 // instructions. 3326 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3327 SVN0->getMask().equals(SVN1->getMask())) { 3328 SDValue ShOp = N0->getOperand(1); 3329 3330 // Don't try to fold this node if it requires introducing a 3331 // build vector of all zeros that might be illegal at this stage. 3332 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3333 if (!LegalTypes) 3334 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3335 else 3336 ShOp = SDValue(); 3337 } 3338 3339 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3340 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3341 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3342 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3343 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3344 N0->getOperand(0), N1->getOperand(0)); 3345 AddToWorklist(NewNode.getNode()); 3346 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3347 SVN0->getMask()); 3348 } 3349 3350 // Don't try to fold this node if it requires introducing a 3351 // build vector of all zeros that might be illegal at this stage. 3352 ShOp = N0->getOperand(0); 3353 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3354 if (!LegalTypes) 3355 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3356 else 3357 ShOp = SDValue(); 3358 } 3359 3360 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3361 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3362 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3363 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3364 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3365 N0->getOperand(1), N1->getOperand(1)); 3366 AddToWorklist(NewNode.getNode()); 3367 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3368 SVN0->getMask()); 3369 } 3370 } 3371 } 3372 3373 return SDValue(); 3374 } 3375 3376 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3377 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3378 const SDLoc &DL) { 3379 SDValue LL, LR, RL, RR, N0CC, N1CC; 3380 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3381 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3382 return SDValue(); 3383 3384 assert(N0.getValueType() == N1.getValueType() && 3385 "Unexpected operand types for bitwise logic op"); 3386 assert(LL.getValueType() == LR.getValueType() && 3387 RL.getValueType() == RR.getValueType() && 3388 "Unexpected operand types for setcc"); 3389 3390 // If we're here post-legalization or the logic op type is not i1, the logic 3391 // op type must match a setcc result type. Also, all folds require new 3392 // operations on the left and right operands, so those types must match. 3393 EVT VT = N0.getValueType(); 3394 EVT OpVT = LL.getValueType(); 3395 if (LegalOperations || VT != MVT::i1) 3396 if (VT != getSetCCResultType(OpVT)) 3397 return SDValue(); 3398 if (OpVT != RL.getValueType()) 3399 return SDValue(); 3400 3401 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3402 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3403 bool IsInteger = OpVT.isInteger(); 3404 if (LR == RR && CC0 == CC1 && IsInteger) { 3405 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3406 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3407 3408 // All bits clear? 3409 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3410 // All sign bits clear? 3411 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3412 // Any bits set? 3413 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3414 // Any sign bits set? 3415 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3416 3417 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3418 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3419 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3420 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3421 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3422 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3423 AddToWorklist(Or.getNode()); 3424 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3425 } 3426 3427 // All bits set? 3428 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3429 // All sign bits set? 3430 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3431 // Any bits clear? 3432 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3433 // Any sign bits clear? 3434 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3435 3436 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3437 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3438 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3439 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3440 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3441 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3442 AddToWorklist(And.getNode()); 3443 return DAG.getSetCC(DL, VT, And, LR, CC1); 3444 } 3445 } 3446 3447 // TODO: What is the 'or' equivalent of this fold? 3448 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3449 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE && 3450 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3451 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3452 SDValue One = DAG.getConstant(1, DL, OpVT); 3453 SDValue Two = DAG.getConstant(2, DL, OpVT); 3454 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3455 AddToWorklist(Add.getNode()); 3456 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3457 } 3458 3459 // Try more general transforms if the predicates match and the only user of 3460 // the compares is the 'and' or 'or'. 3461 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3462 N0.hasOneUse() && N1.hasOneUse()) { 3463 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3464 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3465 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3466 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3467 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3468 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3469 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3470 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3471 } 3472 } 3473 3474 // Canonicalize equivalent operands to LL == RL. 3475 if (LL == RR && LR == RL) { 3476 CC1 = ISD::getSetCCSwappedOperands(CC1); 3477 std::swap(RL, RR); 3478 } 3479 3480 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3481 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3482 if (LL == RL && LR == RR) { 3483 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3484 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3485 if (NewCC != ISD::SETCC_INVALID && 3486 (!LegalOperations || 3487 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3488 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3489 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3490 } 3491 3492 return SDValue(); 3493 } 3494 3495 /// This contains all DAGCombine rules which reduce two values combined by 3496 /// an And operation to a single value. This makes them reusable in the context 3497 /// of visitSELECT(). Rules involving constants are not included as 3498 /// visitSELECT() already handles those cases. 3499 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3500 EVT VT = N1.getValueType(); 3501 SDLoc DL(N); 3502 3503 // fold (and x, undef) -> 0 3504 if (N0.isUndef() || N1.isUndef()) 3505 return DAG.getConstant(0, DL, VT); 3506 3507 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3508 return V; 3509 3510 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3511 VT.getSizeInBits() <= 64) { 3512 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3513 APInt ADDC = ADDI->getAPIntValue(); 3514 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3515 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3516 // immediate for an add, but it is legal if its top c2 bits are set, 3517 // transform the ADD so the immediate doesn't need to be materialized 3518 // in a register. 3519 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3520 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3521 SRLI->getZExtValue()); 3522 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3523 ADDC |= Mask; 3524 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3525 SDLoc DL0(N0); 3526 SDValue NewAdd = 3527 DAG.getNode(ISD::ADD, DL0, VT, 3528 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3529 CombineTo(N0.getNode(), NewAdd); 3530 // Return N so it doesn't get rechecked! 3531 return SDValue(N, 0); 3532 } 3533 } 3534 } 3535 } 3536 } 3537 } 3538 3539 // Reduce bit extract of low half of an integer to the narrower type. 3540 // (and (srl i64:x, K), KMask) -> 3541 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3542 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3543 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3544 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3545 unsigned Size = VT.getSizeInBits(); 3546 const APInt &AndMask = CAnd->getAPIntValue(); 3547 unsigned ShiftBits = CShift->getZExtValue(); 3548 3549 // Bail out, this node will probably disappear anyway. 3550 if (ShiftBits == 0) 3551 return SDValue(); 3552 3553 unsigned MaskBits = AndMask.countTrailingOnes(); 3554 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3555 3556 if (AndMask.isMask() && 3557 // Required bits must not span the two halves of the integer and 3558 // must fit in the half size type. 3559 (ShiftBits + MaskBits <= Size / 2) && 3560 TLI.isNarrowingProfitable(VT, HalfVT) && 3561 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3562 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3563 TLI.isTruncateFree(VT, HalfVT) && 3564 TLI.isZExtFree(HalfVT, VT)) { 3565 // The isNarrowingProfitable is to avoid regressions on PPC and 3566 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3567 // on downstream users of this. Those patterns could probably be 3568 // extended to handle extensions mixed in. 3569 3570 SDValue SL(N0); 3571 assert(MaskBits <= Size); 3572 3573 // Extracting the highest bit of the low half. 3574 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3575 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3576 N0.getOperand(0)); 3577 3578 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3579 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3580 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3581 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3582 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3583 } 3584 } 3585 } 3586 } 3587 3588 return SDValue(); 3589 } 3590 3591 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3592 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3593 bool &NarrowLoad) { 3594 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3595 3596 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits)) 3597 return false; 3598 3599 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3600 LoadedVT = LoadN->getMemoryVT(); 3601 3602 if (ExtVT == LoadedVT && 3603 (!LegalOperations || 3604 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3605 // ZEXTLOAD will match without needing to change the size of the value being 3606 // loaded. 3607 NarrowLoad = false; 3608 return true; 3609 } 3610 3611 // Do not change the width of a volatile load. 3612 if (LoadN->isVolatile()) 3613 return false; 3614 3615 // Do not generate loads of non-round integer types since these can 3616 // be expensive (and would be wrong if the type is not byte sized). 3617 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3618 return false; 3619 3620 if (LegalOperations && 3621 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3622 return false; 3623 3624 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3625 return false; 3626 3627 NarrowLoad = true; 3628 return true; 3629 } 3630 3631 SDValue DAGCombiner::visitAND(SDNode *N) { 3632 SDValue N0 = N->getOperand(0); 3633 SDValue N1 = N->getOperand(1); 3634 EVT VT = N1.getValueType(); 3635 3636 // x & x --> x 3637 if (N0 == N1) 3638 return N0; 3639 3640 // fold vector ops 3641 if (VT.isVector()) { 3642 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3643 return FoldedVOp; 3644 3645 // fold (and x, 0) -> 0, vector edition 3646 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3647 // do not return N0, because undef node may exist in N0 3648 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3649 SDLoc(N), N0.getValueType()); 3650 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3651 // do not return N1, because undef node may exist in N1 3652 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3653 SDLoc(N), N1.getValueType()); 3654 3655 // fold (and x, -1) -> x, vector edition 3656 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3657 return N1; 3658 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3659 return N0; 3660 } 3661 3662 // fold (and c1, c2) -> c1&c2 3663 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3664 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3665 if (N0C && N1C && !N1C->isOpaque()) 3666 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3667 // canonicalize constant to RHS 3668 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3669 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3670 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3671 // fold (and x, -1) -> x 3672 if (isAllOnesConstant(N1)) 3673 return N0; 3674 // if (and x, c) is known to be zero, return 0 3675 unsigned BitWidth = VT.getScalarSizeInBits(); 3676 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3677 APInt::getAllOnesValue(BitWidth))) 3678 return DAG.getConstant(0, SDLoc(N), VT); 3679 3680 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3681 return NewSel; 3682 3683 // reassociate and 3684 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3685 return RAND; 3686 // fold (and (or x, C), D) -> D if (C & D) == D 3687 if (N1C && N0.getOpcode() == ISD::OR) 3688 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3689 if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue())) 3690 return N1; 3691 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3692 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3693 SDValue N0Op0 = N0.getOperand(0); 3694 APInt Mask = ~N1C->getAPIntValue(); 3695 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3696 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3697 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3698 N0.getValueType(), N0Op0); 3699 3700 // Replace uses of the AND with uses of the Zero extend node. 3701 CombineTo(N, Zext); 3702 3703 // We actually want to replace all uses of the any_extend with the 3704 // zero_extend, to avoid duplicating things. This will later cause this 3705 // AND to be folded. 3706 CombineTo(N0.getNode(), Zext); 3707 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3708 } 3709 } 3710 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3711 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3712 // already be zero by virtue of the width of the base type of the load. 3713 // 3714 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3715 // more cases. 3716 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3717 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3718 N0.getOperand(0).getOpcode() == ISD::LOAD && 3719 N0.getOperand(0).getResNo() == 0) || 3720 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3721 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3722 N0 : N0.getOperand(0) ); 3723 3724 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3725 // This can be a pure constant or a vector splat, in which case we treat the 3726 // vector as a scalar and use the splat value. 3727 APInt Constant = APInt::getNullValue(1); 3728 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3729 Constant = C->getAPIntValue(); 3730 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3731 APInt SplatValue, SplatUndef; 3732 unsigned SplatBitSize; 3733 bool HasAnyUndefs; 3734 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3735 SplatBitSize, HasAnyUndefs); 3736 if (IsSplat) { 3737 // Undef bits can contribute to a possible optimisation if set, so 3738 // set them. 3739 SplatValue |= SplatUndef; 3740 3741 // The splat value may be something like "0x00FFFFFF", which means 0 for 3742 // the first vector value and FF for the rest, repeating. We need a mask 3743 // that will apply equally to all members of the vector, so AND all the 3744 // lanes of the constant together. 3745 EVT VT = Vector->getValueType(0); 3746 unsigned BitWidth = VT.getScalarSizeInBits(); 3747 3748 // If the splat value has been compressed to a bitlength lower 3749 // than the size of the vector lane, we need to re-expand it to 3750 // the lane size. 3751 if (BitWidth > SplatBitSize) 3752 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3753 SplatBitSize < BitWidth; 3754 SplatBitSize = SplatBitSize * 2) 3755 SplatValue |= SplatValue.shl(SplatBitSize); 3756 3757 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3758 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3759 if (SplatBitSize % BitWidth == 0) { 3760 Constant = APInt::getAllOnesValue(BitWidth); 3761 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3762 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3763 } 3764 } 3765 } 3766 3767 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3768 // actually legal and isn't going to get expanded, else this is a false 3769 // optimisation. 3770 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3771 Load->getValueType(0), 3772 Load->getMemoryVT()); 3773 3774 // Resize the constant to the same size as the original memory access before 3775 // extension. If it is still the AllOnesValue then this AND is completely 3776 // unneeded. 3777 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3778 3779 bool B; 3780 switch (Load->getExtensionType()) { 3781 default: B = false; break; 3782 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3783 case ISD::ZEXTLOAD: 3784 case ISD::NON_EXTLOAD: B = true; break; 3785 } 3786 3787 if (B && Constant.isAllOnesValue()) { 3788 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3789 // preserve semantics once we get rid of the AND. 3790 SDValue NewLoad(Load, 0); 3791 3792 // Fold the AND away. NewLoad may get replaced immediately. 3793 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3794 3795 if (Load->getExtensionType() == ISD::EXTLOAD) { 3796 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3797 Load->getValueType(0), SDLoc(Load), 3798 Load->getChain(), Load->getBasePtr(), 3799 Load->getOffset(), Load->getMemoryVT(), 3800 Load->getMemOperand()); 3801 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3802 if (Load->getNumValues() == 3) { 3803 // PRE/POST_INC loads have 3 values. 3804 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3805 NewLoad.getValue(2) }; 3806 CombineTo(Load, To, 3, true); 3807 } else { 3808 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3809 } 3810 } 3811 3812 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3813 } 3814 } 3815 3816 // fold (and (load x), 255) -> (zextload x, i8) 3817 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3818 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3819 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3820 (N0.getOpcode() == ISD::ANY_EXTEND && 3821 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3822 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3823 LoadSDNode *LN0 = HasAnyExt 3824 ? cast<LoadSDNode>(N0.getOperand(0)) 3825 : cast<LoadSDNode>(N0); 3826 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3827 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3828 auto NarrowLoad = false; 3829 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3830 EVT ExtVT, LoadedVT; 3831 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3832 NarrowLoad)) { 3833 if (!NarrowLoad) { 3834 SDValue NewLoad = 3835 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3836 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3837 LN0->getMemOperand()); 3838 AddToWorklist(N); 3839 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3840 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3841 } else { 3842 EVT PtrType = LN0->getOperand(1).getValueType(); 3843 3844 unsigned Alignment = LN0->getAlignment(); 3845 SDValue NewPtr = LN0->getBasePtr(); 3846 3847 // For big endian targets, we need to add an offset to the pointer 3848 // to load the correct bytes. For little endian systems, we merely 3849 // need to read fewer bytes from the same pointer. 3850 if (DAG.getDataLayout().isBigEndian()) { 3851 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3852 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3853 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3854 SDLoc DL(LN0); 3855 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3856 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3857 Alignment = MinAlign(Alignment, PtrOff); 3858 } 3859 3860 AddToWorklist(NewPtr.getNode()); 3861 3862 SDValue Load = DAG.getExtLoad( 3863 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3864 LN0->getPointerInfo(), ExtVT, Alignment, 3865 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3866 AddToWorklist(N); 3867 CombineTo(LN0, Load, Load.getValue(1)); 3868 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3869 } 3870 } 3871 } 3872 } 3873 3874 if (SDValue Combined = visitANDLike(N0, N1, N)) 3875 return Combined; 3876 3877 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3878 if (N0.getOpcode() == N1.getOpcode()) 3879 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3880 return Tmp; 3881 3882 // Masking the negated extension of a boolean is just the zero-extended 3883 // boolean: 3884 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3885 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3886 // 3887 // Note: the SimplifyDemandedBits fold below can make an information-losing 3888 // transform, and then we have no way to find this better fold. 3889 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3890 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3891 SDValue SubRHS = N0.getOperand(1); 3892 if (SubLHS && SubLHS->isNullValue()) { 3893 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3894 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3895 return SubRHS; 3896 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3897 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3898 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3899 } 3900 } 3901 3902 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3903 // fold (and (sra)) -> (and (srl)) when possible. 3904 if (SimplifyDemandedBits(SDValue(N, 0))) 3905 return SDValue(N, 0); 3906 3907 // fold (zext_inreg (extload x)) -> (zextload x) 3908 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3909 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3910 EVT MemVT = LN0->getMemoryVT(); 3911 // If we zero all the possible extended bits, then we can turn this into 3912 // a zextload if we are running before legalize or the operation is legal. 3913 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3914 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3915 BitWidth - MemVT.getScalarSizeInBits())) && 3916 ((!LegalOperations && !LN0->isVolatile()) || 3917 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3918 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3919 LN0->getChain(), LN0->getBasePtr(), 3920 MemVT, LN0->getMemOperand()); 3921 AddToWorklist(N); 3922 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3923 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3924 } 3925 } 3926 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3927 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3928 N0.hasOneUse()) { 3929 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3930 EVT MemVT = LN0->getMemoryVT(); 3931 // If we zero all the possible extended bits, then we can turn this into 3932 // a zextload if we are running before legalize or the operation is legal. 3933 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3934 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3935 BitWidth - MemVT.getScalarSizeInBits())) && 3936 ((!LegalOperations && !LN0->isVolatile()) || 3937 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3938 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3939 LN0->getChain(), LN0->getBasePtr(), 3940 MemVT, LN0->getMemOperand()); 3941 AddToWorklist(N); 3942 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3943 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3944 } 3945 } 3946 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3947 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3948 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3949 N0.getOperand(1), false)) 3950 return BSwap; 3951 } 3952 3953 return SDValue(); 3954 } 3955 3956 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3957 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3958 bool DemandHighBits) { 3959 if (!LegalOperations) 3960 return SDValue(); 3961 3962 EVT VT = N->getValueType(0); 3963 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3964 return SDValue(); 3965 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 3966 return SDValue(); 3967 3968 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3969 bool LookPassAnd0 = false; 3970 bool LookPassAnd1 = false; 3971 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3972 std::swap(N0, N1); 3973 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3974 std::swap(N0, N1); 3975 if (N0.getOpcode() == ISD::AND) { 3976 if (!N0.getNode()->hasOneUse()) 3977 return SDValue(); 3978 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3979 if (!N01C || N01C->getZExtValue() != 0xFF00) 3980 return SDValue(); 3981 N0 = N0.getOperand(0); 3982 LookPassAnd0 = true; 3983 } 3984 3985 if (N1.getOpcode() == ISD::AND) { 3986 if (!N1.getNode()->hasOneUse()) 3987 return SDValue(); 3988 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3989 if (!N11C || N11C->getZExtValue() != 0xFF) 3990 return SDValue(); 3991 N1 = N1.getOperand(0); 3992 LookPassAnd1 = true; 3993 } 3994 3995 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3996 std::swap(N0, N1); 3997 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3998 return SDValue(); 3999 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 4000 return SDValue(); 4001 4002 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4003 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 4004 if (!N01C || !N11C) 4005 return SDValue(); 4006 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 4007 return SDValue(); 4008 4009 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 4010 SDValue N00 = N0->getOperand(0); 4011 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 4012 if (!N00.getNode()->hasOneUse()) 4013 return SDValue(); 4014 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 4015 if (!N001C || N001C->getZExtValue() != 0xFF) 4016 return SDValue(); 4017 N00 = N00.getOperand(0); 4018 LookPassAnd0 = true; 4019 } 4020 4021 SDValue N10 = N1->getOperand(0); 4022 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 4023 if (!N10.getNode()->hasOneUse()) 4024 return SDValue(); 4025 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 4026 if (!N101C || N101C->getZExtValue() != 0xFF00) 4027 return SDValue(); 4028 N10 = N10.getOperand(0); 4029 LookPassAnd1 = true; 4030 } 4031 4032 if (N00 != N10) 4033 return SDValue(); 4034 4035 // Make sure everything beyond the low halfword gets set to zero since the SRL 4036 // 16 will clear the top bits. 4037 unsigned OpSizeInBits = VT.getSizeInBits(); 4038 if (DemandHighBits && OpSizeInBits > 16) { 4039 // If the left-shift isn't masked out then the only way this is a bswap is 4040 // if all bits beyond the low 8 are 0. In that case the entire pattern 4041 // reduces to a left shift anyway: leave it for other parts of the combiner. 4042 if (!LookPassAnd0) 4043 return SDValue(); 4044 4045 // However, if the right shift isn't masked out then it might be because 4046 // it's not needed. See if we can spot that too. 4047 if (!LookPassAnd1 && 4048 !DAG.MaskedValueIsZero( 4049 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 4050 return SDValue(); 4051 } 4052 4053 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 4054 if (OpSizeInBits > 16) { 4055 SDLoc DL(N); 4056 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 4057 DAG.getConstant(OpSizeInBits - 16, DL, 4058 getShiftAmountTy(VT))); 4059 } 4060 return Res; 4061 } 4062 4063 /// Return true if the specified node is an element that makes up a 32-bit 4064 /// packed halfword byteswap. 4065 /// ((x & 0x000000ff) << 8) | 4066 /// ((x & 0x0000ff00) >> 8) | 4067 /// ((x & 0x00ff0000) << 8) | 4068 /// ((x & 0xff000000) >> 8) 4069 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 4070 if (!N.getNode()->hasOneUse()) 4071 return false; 4072 4073 unsigned Opc = N.getOpcode(); 4074 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 4075 return false; 4076 4077 SDValue N0 = N.getOperand(0); 4078 unsigned Opc0 = N0.getOpcode(); 4079 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 4080 return false; 4081 4082 ConstantSDNode *N1C = nullptr; 4083 // SHL or SRL: look upstream for AND mask operand 4084 if (Opc == ISD::AND) 4085 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4086 else if (Opc0 == ISD::AND) 4087 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4088 if (!N1C) 4089 return false; 4090 4091 unsigned MaskByteOffset; 4092 switch (N1C->getZExtValue()) { 4093 default: 4094 return false; 4095 case 0xFF: MaskByteOffset = 0; break; 4096 case 0xFF00: MaskByteOffset = 1; break; 4097 case 0xFF0000: MaskByteOffset = 2; break; 4098 case 0xFF000000: MaskByteOffset = 3; break; 4099 } 4100 4101 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4102 if (Opc == ISD::AND) { 4103 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4104 // (x >> 8) & 0xff 4105 // (x >> 8) & 0xff0000 4106 if (Opc0 != ISD::SRL) 4107 return false; 4108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4109 if (!C || C->getZExtValue() != 8) 4110 return false; 4111 } else { 4112 // (x << 8) & 0xff00 4113 // (x << 8) & 0xff000000 4114 if (Opc0 != ISD::SHL) 4115 return false; 4116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4117 if (!C || C->getZExtValue() != 8) 4118 return false; 4119 } 4120 } else if (Opc == ISD::SHL) { 4121 // (x & 0xff) << 8 4122 // (x & 0xff0000) << 8 4123 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4124 return false; 4125 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4126 if (!C || C->getZExtValue() != 8) 4127 return false; 4128 } else { // Opc == ISD::SRL 4129 // (x & 0xff00) >> 8 4130 // (x & 0xff000000) >> 8 4131 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4132 return false; 4133 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4134 if (!C || C->getZExtValue() != 8) 4135 return false; 4136 } 4137 4138 if (Parts[MaskByteOffset]) 4139 return false; 4140 4141 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4142 return true; 4143 } 4144 4145 /// Match a 32-bit packed halfword bswap. That is 4146 /// ((x & 0x000000ff) << 8) | 4147 /// ((x & 0x0000ff00) >> 8) | 4148 /// ((x & 0x00ff0000) << 8) | 4149 /// ((x & 0xff000000) >> 8) 4150 /// => (rotl (bswap x), 16) 4151 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4152 if (!LegalOperations) 4153 return SDValue(); 4154 4155 EVT VT = N->getValueType(0); 4156 if (VT != MVT::i32) 4157 return SDValue(); 4158 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4159 return SDValue(); 4160 4161 // Look for either 4162 // (or (or (and), (and)), (or (and), (and))) 4163 // (or (or (or (and), (and)), (and)), (and)) 4164 if (N0.getOpcode() != ISD::OR) 4165 return SDValue(); 4166 SDValue N00 = N0.getOperand(0); 4167 SDValue N01 = N0.getOperand(1); 4168 SDNode *Parts[4] = {}; 4169 4170 if (N1.getOpcode() == ISD::OR && 4171 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4172 // (or (or (and), (and)), (or (and), (and))) 4173 if (!isBSwapHWordElement(N00, Parts)) 4174 return SDValue(); 4175 4176 if (!isBSwapHWordElement(N01, Parts)) 4177 return SDValue(); 4178 SDValue N10 = N1.getOperand(0); 4179 if (!isBSwapHWordElement(N10, Parts)) 4180 return SDValue(); 4181 SDValue N11 = N1.getOperand(1); 4182 if (!isBSwapHWordElement(N11, Parts)) 4183 return SDValue(); 4184 } else { 4185 // (or (or (or (and), (and)), (and)), (and)) 4186 if (!isBSwapHWordElement(N1, Parts)) 4187 return SDValue(); 4188 if (!isBSwapHWordElement(N01, Parts)) 4189 return SDValue(); 4190 if (N00.getOpcode() != ISD::OR) 4191 return SDValue(); 4192 SDValue N000 = N00.getOperand(0); 4193 if (!isBSwapHWordElement(N000, Parts)) 4194 return SDValue(); 4195 SDValue N001 = N00.getOperand(1); 4196 if (!isBSwapHWordElement(N001, Parts)) 4197 return SDValue(); 4198 } 4199 4200 // Make sure the parts are all coming from the same node. 4201 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4202 return SDValue(); 4203 4204 SDLoc DL(N); 4205 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4206 SDValue(Parts[0], 0)); 4207 4208 // Result of the bswap should be rotated by 16. If it's not legal, then 4209 // do (x << 16) | (x >> 16). 4210 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4211 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4212 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4213 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4214 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4215 return DAG.getNode(ISD::OR, DL, VT, 4216 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4217 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4218 } 4219 4220 /// This contains all DAGCombine rules which reduce two values combined by 4221 /// an Or operation to a single value \see visitANDLike(). 4222 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4223 EVT VT = N1.getValueType(); 4224 SDLoc DL(N); 4225 4226 // fold (or x, undef) -> -1 4227 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4228 return DAG.getAllOnesConstant(DL, VT); 4229 4230 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4231 return V; 4232 4233 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4234 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4235 // Don't increase # computations. 4236 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4237 // We can only do this xform if we know that bits from X that are set in C2 4238 // but not in C1 are already zero. Likewise for Y. 4239 if (const ConstantSDNode *N0O1C = 4240 getAsNonOpaqueConstant(N0.getOperand(1))) { 4241 if (const ConstantSDNode *N1O1C = 4242 getAsNonOpaqueConstant(N1.getOperand(1))) { 4243 // We can only do this xform if we know that bits from X that are set in 4244 // C2 but not in C1 are already zero. Likewise for Y. 4245 const APInt &LHSMask = N0O1C->getAPIntValue(); 4246 const APInt &RHSMask = N1O1C->getAPIntValue(); 4247 4248 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4249 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4250 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4251 N0.getOperand(0), N1.getOperand(0)); 4252 return DAG.getNode(ISD::AND, DL, VT, X, 4253 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4254 } 4255 } 4256 } 4257 } 4258 4259 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4260 if (N0.getOpcode() == ISD::AND && 4261 N1.getOpcode() == ISD::AND && 4262 N0.getOperand(0) == N1.getOperand(0) && 4263 // Don't increase # computations. 4264 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4265 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4266 N0.getOperand(1), N1.getOperand(1)); 4267 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4268 } 4269 4270 return SDValue(); 4271 } 4272 4273 SDValue DAGCombiner::visitOR(SDNode *N) { 4274 SDValue N0 = N->getOperand(0); 4275 SDValue N1 = N->getOperand(1); 4276 EVT VT = N1.getValueType(); 4277 4278 // x | x --> x 4279 if (N0 == N1) 4280 return N0; 4281 4282 // fold vector ops 4283 if (VT.isVector()) { 4284 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4285 return FoldedVOp; 4286 4287 // fold (or x, 0) -> x, vector edition 4288 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4289 return N1; 4290 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4291 return N0; 4292 4293 // fold (or x, -1) -> -1, vector edition 4294 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4295 // do not return N0, because undef node may exist in N0 4296 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4297 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4298 // do not return N1, because undef node may exist in N1 4299 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4300 4301 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4302 // Do this only if the resulting shuffle is legal. 4303 if (isa<ShuffleVectorSDNode>(N0) && 4304 isa<ShuffleVectorSDNode>(N1) && 4305 // Avoid folding a node with illegal type. 4306 TLI.isTypeLegal(VT)) { 4307 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4308 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4309 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4310 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4311 // Ensure both shuffles have a zero input. 4312 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4313 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4314 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4315 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4316 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4317 bool CanFold = true; 4318 int NumElts = VT.getVectorNumElements(); 4319 SmallVector<int, 4> Mask(NumElts); 4320 4321 for (int i = 0; i != NumElts; ++i) { 4322 int M0 = SV0->getMaskElt(i); 4323 int M1 = SV1->getMaskElt(i); 4324 4325 // Determine if either index is pointing to a zero vector. 4326 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4327 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4328 4329 // If one element is zero and the otherside is undef, keep undef. 4330 // This also handles the case that both are undef. 4331 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4332 Mask[i] = -1; 4333 continue; 4334 } 4335 4336 // Make sure only one of the elements is zero. 4337 if (M0Zero == M1Zero) { 4338 CanFold = false; 4339 break; 4340 } 4341 4342 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4343 4344 // We have a zero and non-zero element. If the non-zero came from 4345 // SV0 make the index a LHS index. If it came from SV1, make it 4346 // a RHS index. We need to mod by NumElts because we don't care 4347 // which operand it came from in the original shuffles. 4348 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4349 } 4350 4351 if (CanFold) { 4352 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4353 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4354 4355 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4356 if (!LegalMask) { 4357 std::swap(NewLHS, NewRHS); 4358 ShuffleVectorSDNode::commuteMask(Mask); 4359 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4360 } 4361 4362 if (LegalMask) 4363 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4364 } 4365 } 4366 } 4367 } 4368 4369 // fold (or c1, c2) -> c1|c2 4370 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4371 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4372 if (N0C && N1C && !N1C->isOpaque()) 4373 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4374 // canonicalize constant to RHS 4375 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4376 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4377 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4378 // fold (or x, 0) -> x 4379 if (isNullConstant(N1)) 4380 return N0; 4381 // fold (or x, -1) -> -1 4382 if (isAllOnesConstant(N1)) 4383 return N1; 4384 4385 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4386 return NewSel; 4387 4388 // fold (or x, c) -> c iff (x & ~c) == 0 4389 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4390 return N1; 4391 4392 if (SDValue Combined = visitORLike(N0, N1, N)) 4393 return Combined; 4394 4395 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4396 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4397 return BSwap; 4398 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4399 return BSwap; 4400 4401 // reassociate or 4402 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4403 return ROR; 4404 4405 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4406 // iff (c1 & c2) != 0. 4407 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) { 4408 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4409 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) { 4410 if (SDValue COR = 4411 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1)) 4412 return DAG.getNode( 4413 ISD::AND, SDLoc(N), VT, 4414 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4415 return SDValue(); 4416 } 4417 } 4418 } 4419 4420 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4421 if (N0.getOpcode() == N1.getOpcode()) 4422 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4423 return Tmp; 4424 4425 // See if this is some rotate idiom. 4426 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4427 return SDValue(Rot, 0); 4428 4429 if (SDValue Load = MatchLoadCombine(N)) 4430 return Load; 4431 4432 // Simplify the operands using demanded-bits information. 4433 if (SimplifyDemandedBits(SDValue(N, 0))) 4434 return SDValue(N, 0); 4435 4436 return SDValue(); 4437 } 4438 4439 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4440 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4441 if (Op.getOpcode() == ISD::AND) { 4442 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4443 Mask = Op.getOperand(1); 4444 Op = Op.getOperand(0); 4445 } else { 4446 return false; 4447 } 4448 } 4449 4450 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4451 Shift = Op; 4452 return true; 4453 } 4454 4455 return false; 4456 } 4457 4458 // Return true if we can prove that, whenever Neg and Pos are both in the 4459 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4460 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4461 // 4462 // (or (shift1 X, Neg), (shift2 X, Pos)) 4463 // 4464 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4465 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4466 // to consider shift amounts with defined behavior. 4467 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4468 // If EltSize is a power of 2 then: 4469 // 4470 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4471 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4472 // 4473 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4474 // for the stronger condition: 4475 // 4476 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4477 // 4478 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4479 // we can just replace Neg with Neg' for the rest of the function. 4480 // 4481 // In other cases we check for the even stronger condition: 4482 // 4483 // Neg == EltSize - Pos [B] 4484 // 4485 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4486 // behavior if Pos == 0 (and consequently Neg == EltSize). 4487 // 4488 // We could actually use [A] whenever EltSize is a power of 2, but the 4489 // only extra cases that it would match are those uninteresting ones 4490 // where Neg and Pos are never in range at the same time. E.g. for 4491 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4492 // as well as (sub 32, Pos), but: 4493 // 4494 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4495 // 4496 // always invokes undefined behavior for 32-bit X. 4497 // 4498 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4499 unsigned MaskLoBits = 0; 4500 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4501 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4502 if (NegC->getAPIntValue() == EltSize - 1) { 4503 Neg = Neg.getOperand(0); 4504 MaskLoBits = Log2_64(EltSize); 4505 } 4506 } 4507 } 4508 4509 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4510 if (Neg.getOpcode() != ISD::SUB) 4511 return false; 4512 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4513 if (!NegC) 4514 return false; 4515 SDValue NegOp1 = Neg.getOperand(1); 4516 4517 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4518 // Pos'. The truncation is redundant for the purpose of the equality. 4519 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4520 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4521 if (PosC->getAPIntValue() == EltSize - 1) 4522 Pos = Pos.getOperand(0); 4523 4524 // The condition we need is now: 4525 // 4526 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4527 // 4528 // If NegOp1 == Pos then we need: 4529 // 4530 // EltSize & Mask == NegC & Mask 4531 // 4532 // (because "x & Mask" is a truncation and distributes through subtraction). 4533 APInt Width; 4534 if (Pos == NegOp1) 4535 Width = NegC->getAPIntValue(); 4536 4537 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4538 // Then the condition we want to prove becomes: 4539 // 4540 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4541 // 4542 // which, again because "x & Mask" is a truncation, becomes: 4543 // 4544 // NegC & Mask == (EltSize - PosC) & Mask 4545 // EltSize & Mask == (NegC + PosC) & Mask 4546 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4547 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4548 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4549 else 4550 return false; 4551 } else 4552 return false; 4553 4554 // Now we just need to check that EltSize & Mask == Width & Mask. 4555 if (MaskLoBits) 4556 // EltSize & Mask is 0 since Mask is EltSize - 1. 4557 return Width.getLoBits(MaskLoBits) == 0; 4558 return Width == EltSize; 4559 } 4560 4561 // A subroutine of MatchRotate used once we have found an OR of two opposite 4562 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4563 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4564 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4565 // Neg with outer conversions stripped away. 4566 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4567 SDValue Neg, SDValue InnerPos, 4568 SDValue InnerNeg, unsigned PosOpcode, 4569 unsigned NegOpcode, const SDLoc &DL) { 4570 // fold (or (shl x, (*ext y)), 4571 // (srl x, (*ext (sub 32, y)))) -> 4572 // (rotl x, y) or (rotr x, (sub 32, y)) 4573 // 4574 // fold (or (shl x, (*ext (sub 32, y))), 4575 // (srl x, (*ext y))) -> 4576 // (rotr x, y) or (rotl x, (sub 32, y)) 4577 EVT VT = Shifted.getValueType(); 4578 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4579 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4580 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4581 HasPos ? Pos : Neg).getNode(); 4582 } 4583 4584 return nullptr; 4585 } 4586 4587 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4588 // idioms for rotate, and if the target supports rotation instructions, generate 4589 // a rot[lr]. 4590 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4591 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4592 EVT VT = LHS.getValueType(); 4593 if (!TLI.isTypeLegal(VT)) return nullptr; 4594 4595 // The target must have at least one rotate flavor. 4596 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4597 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4598 if (!HasROTL && !HasROTR) return nullptr; 4599 4600 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4601 SDValue LHSShift; // The shift. 4602 SDValue LHSMask; // AND value if any. 4603 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4604 return nullptr; // Not part of a rotate. 4605 4606 SDValue RHSShift; // The shift. 4607 SDValue RHSMask; // AND value if any. 4608 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4609 return nullptr; // Not part of a rotate. 4610 4611 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4612 return nullptr; // Not shifting the same value. 4613 4614 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4615 return nullptr; // Shifts must disagree. 4616 4617 // Canonicalize shl to left side in a shl/srl pair. 4618 if (RHSShift.getOpcode() == ISD::SHL) { 4619 std::swap(LHS, RHS); 4620 std::swap(LHSShift, RHSShift); 4621 std::swap(LHSMask, RHSMask); 4622 } 4623 4624 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4625 SDValue LHSShiftArg = LHSShift.getOperand(0); 4626 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4627 SDValue RHSShiftArg = RHSShift.getOperand(0); 4628 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4629 4630 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4631 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4632 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4633 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4634 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4635 if ((LShVal + RShVal) != EltSizeInBits) 4636 return nullptr; 4637 4638 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4639 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4640 4641 // If there is an AND of either shifted operand, apply it to the result. 4642 if (LHSMask.getNode() || RHSMask.getNode()) { 4643 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4644 4645 if (LHSMask.getNode()) { 4646 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4647 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4648 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4649 DAG.getConstant(RHSBits, DL, VT))); 4650 } 4651 if (RHSMask.getNode()) { 4652 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4653 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4654 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4655 DAG.getConstant(LHSBits, DL, VT))); 4656 } 4657 4658 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4659 } 4660 4661 return Rot.getNode(); 4662 } 4663 4664 // If there is a mask here, and we have a variable shift, we can't be sure 4665 // that we're masking out the right stuff. 4666 if (LHSMask.getNode() || RHSMask.getNode()) 4667 return nullptr; 4668 4669 // If the shift amount is sign/zext/any-extended just peel it off. 4670 SDValue LExtOp0 = LHSShiftAmt; 4671 SDValue RExtOp0 = RHSShiftAmt; 4672 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4673 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4674 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4675 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4676 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4677 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4678 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4679 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4680 LExtOp0 = LHSShiftAmt.getOperand(0); 4681 RExtOp0 = RHSShiftAmt.getOperand(0); 4682 } 4683 4684 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4685 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4686 if (TryL) 4687 return TryL; 4688 4689 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4690 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4691 if (TryR) 4692 return TryR; 4693 4694 return nullptr; 4695 } 4696 4697 namespace { 4698 /// Helper struct to parse and store a memory address as base + index + offset. 4699 /// We ignore sign extensions when it is safe to do so. 4700 /// The following two expressions are not equivalent. To differentiate we need 4701 /// to store whether there was a sign extension involved in the index 4702 /// computation. 4703 /// (load (i64 add (i64 copyfromreg %c) 4704 /// (i64 signextend (add (i8 load %index) 4705 /// (i8 1)))) 4706 /// vs 4707 /// 4708 /// (load (i64 add (i64 copyfromreg %c) 4709 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4710 /// (i32 1))))) 4711 struct BaseIndexOffset { 4712 SDValue Base; 4713 SDValue Index; 4714 int64_t Offset; 4715 bool IsIndexSignExt; 4716 4717 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4718 4719 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4720 bool IsIndexSignExt) : 4721 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4722 4723 bool equalBaseIndex(const BaseIndexOffset &Other) { 4724 return Other.Base == Base && Other.Index == Index && 4725 Other.IsIndexSignExt == IsIndexSignExt; 4726 } 4727 4728 /// Parses tree in Ptr for base, index, offset addresses. 4729 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 4730 4731 SDValue Base = Ptr; 4732 SDValue Index = SDValue(); 4733 int64_t Offset = 0; 4734 bool IsIndexSignExt = false; 4735 4736 // (((B + I*M) + O)) + O ... 4737 4738 //Consume constant adds 4739 while (Base->getOpcode() == ISD::ADD && 4740 isa<ConstantSDNode>(Base->getOperand(1))) { 4741 int64_t POffset = cast<ConstantSDNode>(Base->getOperand(1))->getSExtValue(); 4742 Offset += POffset; 4743 Base = Base->getOperand(0); 4744 } 4745 4746 // Split up a folded GlobalAddress+Offset into its component parts. 4747 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Base)) 4748 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4749 Base = DAG.getGlobalAddress(GA->getGlobal(), 4750 SDLoc(GA), 4751 GA->getValueType(0), 4752 /*Offset*/ 0, 4753 /*isTargetGA=*/false, 4754 GA->getTargetFlags()); 4755 Offset += GA->getOffset(); 4756 return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt); 4757 } 4758 4759 if (Base->getOpcode() == ISD::ADD) { 4760 // TODO: The following code appears to be needless as it just 4761 // bails on some Ptrs early, reducing the cases where we 4762 // find equivalence. We should be able to remove this. 4763 // Inside a loop the current BASE pointer is calculated using an ADD and a 4764 // MUL instruction. In this case Base is the actual BASE pointer. 4765 // (i64 add (i64 %array_ptr) 4766 // (i64 mul (i64 %induction_var) 4767 // (i64 %element_size))) 4768 if (Base->getOperand(1)->getOpcode() == ISD::MUL) 4769 return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt); 4770 4771 // Look at Base + Index + Offset cases. 4772 Index = Base->getOperand(1); 4773 SDValue PotentialBase = Base->getOperand(0); 4774 4775 // Skip signextends. 4776 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4777 Index = Index->getOperand(0); 4778 IsIndexSignExt = true; 4779 } 4780 4781 // Check if Index Offset pattern 4782 if (Index->getOpcode() != ISD::ADD || 4783 !isa<ConstantSDNode>(Index->getOperand(1))) 4784 return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt); 4785 4786 Offset += cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue(); 4787 Index = Index->getOperand(0); 4788 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4789 Index = Index->getOperand(0); 4790 IsIndexSignExt = true; 4791 } else IsIndexSignExt = false; 4792 Base = PotentialBase; 4793 } 4794 return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt); 4795 } 4796 }; 4797 } // namespace 4798 4799 namespace { 4800 /// Represents known origin of an individual byte in load combine pattern. The 4801 /// value of the byte is either constant zero or comes from memory. 4802 struct ByteProvider { 4803 // For constant zero providers Load is set to nullptr. For memory providers 4804 // Load represents the node which loads the byte from memory. 4805 // ByteOffset is the offset of the byte in the value produced by the load. 4806 LoadSDNode *Load; 4807 unsigned ByteOffset; 4808 4809 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4810 4811 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4812 return ByteProvider(Load, ByteOffset); 4813 } 4814 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4815 4816 bool isConstantZero() const { return !Load; } 4817 bool isMemory() const { return Load; } 4818 4819 bool operator==(const ByteProvider &Other) const { 4820 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4821 } 4822 4823 private: 4824 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4825 : Load(Load), ByteOffset(ByteOffset) {} 4826 }; 4827 4828 /// Recursively traverses the expression calculating the origin of the requested 4829 /// byte of the given value. Returns None if the provider can't be calculated. 4830 /// 4831 /// For all the values except the root of the expression verifies that the value 4832 /// has exactly one use and if it's not true return None. This way if the origin 4833 /// of the byte is returned it's guaranteed that the values which contribute to 4834 /// the byte are not used outside of this expression. 4835 /// 4836 /// Because the parts of the expression are not allowed to have more than one 4837 /// use this function iterates over trees, not DAGs. So it never visits the same 4838 /// node more than once. 4839 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4840 unsigned Depth, 4841 bool Root = false) { 4842 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4843 if (Depth == 10) 4844 return None; 4845 4846 if (!Root && !Op.hasOneUse()) 4847 return None; 4848 4849 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4850 unsigned BitWidth = Op.getValueSizeInBits(); 4851 if (BitWidth % 8 != 0) 4852 return None; 4853 unsigned ByteWidth = BitWidth / 8; 4854 assert(Index < ByteWidth && "invalid index requested"); 4855 (void) ByteWidth; 4856 4857 switch (Op.getOpcode()) { 4858 case ISD::OR: { 4859 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4860 if (!LHS) 4861 return None; 4862 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4863 if (!RHS) 4864 return None; 4865 4866 if (LHS->isConstantZero()) 4867 return RHS; 4868 if (RHS->isConstantZero()) 4869 return LHS; 4870 return None; 4871 } 4872 case ISD::SHL: { 4873 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4874 if (!ShiftOp) 4875 return None; 4876 4877 uint64_t BitShift = ShiftOp->getZExtValue(); 4878 if (BitShift % 8 != 0) 4879 return None; 4880 uint64_t ByteShift = BitShift / 8; 4881 4882 return Index < ByteShift 4883 ? ByteProvider::getConstantZero() 4884 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4885 Depth + 1); 4886 } 4887 case ISD::ANY_EXTEND: 4888 case ISD::SIGN_EXTEND: 4889 case ISD::ZERO_EXTEND: { 4890 SDValue NarrowOp = Op->getOperand(0); 4891 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4892 if (NarrowBitWidth % 8 != 0) 4893 return None; 4894 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4895 4896 if (Index >= NarrowByteWidth) 4897 return Op.getOpcode() == ISD::ZERO_EXTEND 4898 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4899 : None; 4900 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4901 } 4902 case ISD::BSWAP: 4903 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4904 Depth + 1); 4905 case ISD::LOAD: { 4906 auto L = cast<LoadSDNode>(Op.getNode()); 4907 if (L->isVolatile() || L->isIndexed()) 4908 return None; 4909 4910 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4911 if (NarrowBitWidth % 8 != 0) 4912 return None; 4913 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4914 4915 if (Index >= NarrowByteWidth) 4916 return L->getExtensionType() == ISD::ZEXTLOAD 4917 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4918 : None; 4919 return ByteProvider::getMemory(L, Index); 4920 } 4921 } 4922 4923 return None; 4924 } 4925 } // namespace 4926 4927 /// Match a pattern where a wide type scalar value is loaded by several narrow 4928 /// loads and combined by shifts and ors. Fold it into a single load or a load 4929 /// and a BSWAP if the targets supports it. 4930 /// 4931 /// Assuming little endian target: 4932 /// i8 *a = ... 4933 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4934 /// => 4935 /// i32 val = *((i32)a) 4936 /// 4937 /// i8 *a = ... 4938 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4939 /// => 4940 /// i32 val = BSWAP(*((i32)a)) 4941 /// 4942 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4943 /// interact well with the worklist mechanism. When a part of the pattern is 4944 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4945 /// but the root node of the pattern which triggers the load combine is not 4946 /// necessarily a direct user of the changed node. For example, once the address 4947 /// of t28 load is reassociated load combine won't be triggered: 4948 /// t25: i32 = add t4, Constant:i32<2> 4949 /// t26: i64 = sign_extend t25 4950 /// t27: i64 = add t2, t26 4951 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4952 /// t29: i32 = zero_extend t28 4953 /// t32: i32 = shl t29, Constant:i8<8> 4954 /// t33: i32 = or t23, t32 4955 /// As a possible fix visitLoad can check if the load can be a part of a load 4956 /// combine pattern and add corresponding OR roots to the worklist. 4957 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4958 assert(N->getOpcode() == ISD::OR && 4959 "Can only match load combining against OR nodes"); 4960 4961 // Handles simple types only 4962 EVT VT = N->getValueType(0); 4963 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4964 return SDValue(); 4965 unsigned ByteWidth = VT.getSizeInBits() / 8; 4966 4967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4968 // Before legalize we can introduce too wide illegal loads which will be later 4969 // split into legal sized loads. This enables us to combine i64 load by i8 4970 // patterns to a couple of i32 loads on 32 bit targets. 4971 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4972 return SDValue(); 4973 4974 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4975 unsigned BW, unsigned i) { return i; }; 4976 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4977 unsigned BW, unsigned i) { return BW - i - 1; }; 4978 4979 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4980 auto MemoryByteOffset = [&] (ByteProvider P) { 4981 assert(P.isMemory() && "Must be a memory byte provider"); 4982 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4983 assert(LoadBitWidth % 8 == 0 && 4984 "can only analyze providers for individual bytes not bit"); 4985 unsigned LoadByteWidth = LoadBitWidth / 8; 4986 return IsBigEndianTarget 4987 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4988 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4989 }; 4990 4991 Optional<BaseIndexOffset> Base; 4992 SDValue Chain; 4993 4994 SmallSet<LoadSDNode *, 8> Loads; 4995 Optional<ByteProvider> FirstByteProvider; 4996 int64_t FirstOffset = INT64_MAX; 4997 4998 // Check if all the bytes of the OR we are looking at are loaded from the same 4999 // base address. Collect bytes offsets from Base address in ByteOffsets. 5000 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 5001 for (unsigned i = 0; i < ByteWidth; i++) { 5002 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 5003 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 5004 return SDValue(); 5005 5006 LoadSDNode *L = P->Load; 5007 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 5008 "Must be enforced by calculateByteProvider"); 5009 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 5010 5011 // All loads must share the same chain 5012 SDValue LChain = L->getChain(); 5013 if (!Chain) 5014 Chain = LChain; 5015 else if (Chain != LChain) 5016 return SDValue(); 5017 5018 // Loads must share the same base address 5019 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 5020 if (!Base) 5021 Base = Ptr; 5022 else if (!Base->equalBaseIndex(Ptr)) 5023 return SDValue(); 5024 5025 // Calculate the offset of the current byte from the base address 5026 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 5027 ByteOffsets[i] = ByteOffsetFromBase; 5028 5029 // Remember the first byte load 5030 if (ByteOffsetFromBase < FirstOffset) { 5031 FirstByteProvider = P; 5032 FirstOffset = ByteOffsetFromBase; 5033 } 5034 5035 Loads.insert(L); 5036 } 5037 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 5038 "memory, so there must be at least one load which produces the value"); 5039 assert(Base && "Base address of the accessed memory location must be set"); 5040 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 5041 5042 // Check if the bytes of the OR we are looking at match with either big or 5043 // little endian value load 5044 bool BigEndian = true, LittleEndian = true; 5045 for (unsigned i = 0; i < ByteWidth; i++) { 5046 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 5047 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 5048 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 5049 if (!BigEndian && !LittleEndian) 5050 return SDValue(); 5051 } 5052 assert((BigEndian != LittleEndian) && "should be either or"); 5053 assert(FirstByteProvider && "must be set"); 5054 5055 // Ensure that the first byte is loaded from zero offset of the first load. 5056 // So the combined value can be loaded from the first load address. 5057 if (MemoryByteOffset(*FirstByteProvider) != 0) 5058 return SDValue(); 5059 LoadSDNode *FirstLoad = FirstByteProvider->Load; 5060 5061 // The node we are looking at matches with the pattern, check if we can 5062 // replace it with a single load and bswap if needed. 5063 5064 // If the load needs byte swap check if the target supports it 5065 bool NeedsBswap = IsBigEndianTarget != BigEndian; 5066 5067 // Before legalize we can introduce illegal bswaps which will be later 5068 // converted to an explicit bswap sequence. This way we end up with a single 5069 // load and byte shuffling instead of several loads and byte shuffling. 5070 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 5071 return SDValue(); 5072 5073 // Check that a load of the wide type is both allowed and fast on the target 5074 bool Fast = false; 5075 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 5076 VT, FirstLoad->getAddressSpace(), 5077 FirstLoad->getAlignment(), &Fast); 5078 if (!Allowed || !Fast) 5079 return SDValue(); 5080 5081 SDValue NewLoad = 5082 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 5083 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 5084 5085 // Transfer chain users from old loads to the new load. 5086 for (LoadSDNode *L : Loads) 5087 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 5088 5089 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5090 } 5091 5092 SDValue DAGCombiner::visitXOR(SDNode *N) { 5093 SDValue N0 = N->getOperand(0); 5094 SDValue N1 = N->getOperand(1); 5095 EVT VT = N0.getValueType(); 5096 5097 // fold vector ops 5098 if (VT.isVector()) { 5099 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5100 return FoldedVOp; 5101 5102 // fold (xor x, 0) -> x, vector edition 5103 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5104 return N1; 5105 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5106 return N0; 5107 } 5108 5109 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5110 if (N0.isUndef() && N1.isUndef()) 5111 return DAG.getConstant(0, SDLoc(N), VT); 5112 // fold (xor x, undef) -> undef 5113 if (N0.isUndef()) 5114 return N0; 5115 if (N1.isUndef()) 5116 return N1; 5117 // fold (xor c1, c2) -> c1^c2 5118 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5119 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5120 if (N0C && N1C) 5121 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5122 // canonicalize constant to RHS 5123 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5124 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5125 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5126 // fold (xor x, 0) -> x 5127 if (isNullConstant(N1)) 5128 return N0; 5129 5130 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5131 return NewSel; 5132 5133 // reassociate xor 5134 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5135 return RXOR; 5136 5137 // fold !(x cc y) -> (x !cc y) 5138 SDValue LHS, RHS, CC; 5139 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5140 bool isInt = LHS.getValueType().isInteger(); 5141 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5142 isInt); 5143 5144 if (!LegalOperations || 5145 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5146 switch (N0.getOpcode()) { 5147 default: 5148 llvm_unreachable("Unhandled SetCC Equivalent!"); 5149 case ISD::SETCC: 5150 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5151 case ISD::SELECT_CC: 5152 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5153 N0.getOperand(3), NotCC); 5154 } 5155 } 5156 } 5157 5158 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5159 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5160 N0.getNode()->hasOneUse() && 5161 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5162 SDValue V = N0.getOperand(0); 5163 SDLoc DL(N0); 5164 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5165 DAG.getConstant(1, DL, V.getValueType())); 5166 AddToWorklist(V.getNode()); 5167 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5168 } 5169 5170 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5171 if (isOneConstant(N1) && VT == MVT::i1 && 5172 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5173 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5174 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5175 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5176 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5177 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5178 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5179 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5180 } 5181 } 5182 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5183 if (isAllOnesConstant(N1) && 5184 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5185 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5186 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5187 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5188 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5189 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5190 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5191 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5192 } 5193 } 5194 // fold (xor (and x, y), y) -> (and (not x), y) 5195 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5196 N0->getOperand(1) == N1) { 5197 SDValue X = N0->getOperand(0); 5198 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5199 AddToWorklist(NotX.getNode()); 5200 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5201 } 5202 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 5203 if (N1C && N0.getOpcode() == ISD::XOR) { 5204 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 5205 SDLoc DL(N); 5206 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 5207 DAG.getConstant(N1C->getAPIntValue() ^ 5208 N00C->getAPIntValue(), DL, VT)); 5209 } 5210 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 5211 SDLoc DL(N); 5212 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 5213 DAG.getConstant(N1C->getAPIntValue() ^ 5214 N01C->getAPIntValue(), DL, VT)); 5215 } 5216 } 5217 5218 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5219 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5220 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5221 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5222 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5223 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5224 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5225 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5226 } 5227 5228 // fold (xor x, x) -> 0 5229 if (N0 == N1) 5230 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5231 5232 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5233 // Here is a concrete example of this equivalence: 5234 // i16 x == 14 5235 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5236 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5237 // 5238 // => 5239 // 5240 // i16 ~1 == 0b1111111111111110 5241 // i16 rol(~1, 14) == 0b1011111111111111 5242 // 5243 // Some additional tips to help conceptualize this transform: 5244 // - Try to see the operation as placing a single zero in a value of all ones. 5245 // - There exists no value for x which would allow the result to contain zero. 5246 // - Values of x larger than the bitwidth are undefined and do not require a 5247 // consistent result. 5248 // - Pushing the zero left requires shifting one bits in from the right. 5249 // A rotate left of ~1 is a nice way of achieving the desired result. 5250 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5251 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5252 SDLoc DL(N); 5253 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5254 N0.getOperand(1)); 5255 } 5256 5257 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5258 if (N0.getOpcode() == N1.getOpcode()) 5259 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5260 return Tmp; 5261 5262 // Simplify the expression using non-local knowledge. 5263 if (SimplifyDemandedBits(SDValue(N, 0))) 5264 return SDValue(N, 0); 5265 5266 return SDValue(); 5267 } 5268 5269 /// Handle transforms common to the three shifts, when the shift amount is a 5270 /// constant. 5271 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5272 SDNode *LHS = N->getOperand(0).getNode(); 5273 if (!LHS->hasOneUse()) return SDValue(); 5274 5275 // We want to pull some binops through shifts, so that we have (and (shift)) 5276 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5277 // thing happens with address calculations, so it's important to canonicalize 5278 // it. 5279 bool HighBitSet = false; // Can we transform this if the high bit is set? 5280 5281 switch (LHS->getOpcode()) { 5282 default: return SDValue(); 5283 case ISD::OR: 5284 case ISD::XOR: 5285 HighBitSet = false; // We can only transform sra if the high bit is clear. 5286 break; 5287 case ISD::AND: 5288 HighBitSet = true; // We can only transform sra if the high bit is set. 5289 break; 5290 case ISD::ADD: 5291 if (N->getOpcode() != ISD::SHL) 5292 return SDValue(); // only shl(add) not sr[al](add). 5293 HighBitSet = false; // We can only transform sra if the high bit is clear. 5294 break; 5295 } 5296 5297 // We require the RHS of the binop to be a constant and not opaque as well. 5298 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5299 if (!BinOpCst) return SDValue(); 5300 5301 // FIXME: disable this unless the input to the binop is a shift by a constant 5302 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5303 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5304 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5305 BinOpLHSVal->getOpcode() == ISD::SRA || 5306 BinOpLHSVal->getOpcode() == ISD::SRL; 5307 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5308 BinOpLHSVal->getOpcode() == ISD::SELECT; 5309 5310 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5311 !isCopyOrSelect) 5312 return SDValue(); 5313 5314 if (isCopyOrSelect && N->hasOneUse()) 5315 return SDValue(); 5316 5317 EVT VT = N->getValueType(0); 5318 5319 // If this is a signed shift right, and the high bit is modified by the 5320 // logical operation, do not perform the transformation. The highBitSet 5321 // boolean indicates the value of the high bit of the constant which would 5322 // cause it to be modified for this operation. 5323 if (N->getOpcode() == ISD::SRA) { 5324 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5325 if (BinOpRHSSignSet != HighBitSet) 5326 return SDValue(); 5327 } 5328 5329 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5330 return SDValue(); 5331 5332 // Fold the constants, shifting the binop RHS by the shift amount. 5333 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5334 N->getValueType(0), 5335 LHS->getOperand(1), N->getOperand(1)); 5336 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5337 5338 // Create the new shift. 5339 SDValue NewShift = DAG.getNode(N->getOpcode(), 5340 SDLoc(LHS->getOperand(0)), 5341 VT, LHS->getOperand(0), N->getOperand(1)); 5342 5343 // Create the new binop. 5344 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5345 } 5346 5347 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5348 assert(N->getOpcode() == ISD::TRUNCATE); 5349 assert(N->getOperand(0).getOpcode() == ISD::AND); 5350 5351 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5352 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5353 SDValue N01 = N->getOperand(0).getOperand(1); 5354 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5355 SDLoc DL(N); 5356 EVT TruncVT = N->getValueType(0); 5357 SDValue N00 = N->getOperand(0).getOperand(0); 5358 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5359 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5360 AddToWorklist(Trunc00.getNode()); 5361 AddToWorklist(Trunc01.getNode()); 5362 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5363 } 5364 } 5365 5366 return SDValue(); 5367 } 5368 5369 SDValue DAGCombiner::visitRotate(SDNode *N) { 5370 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5371 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 5372 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 5373 if (SDValue NewOp1 = 5374 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 5375 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 5376 N->getOperand(0), NewOp1); 5377 } 5378 return SDValue(); 5379 } 5380 5381 SDValue DAGCombiner::visitSHL(SDNode *N) { 5382 SDValue N0 = N->getOperand(0); 5383 SDValue N1 = N->getOperand(1); 5384 EVT VT = N0.getValueType(); 5385 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5386 5387 // fold vector ops 5388 if (VT.isVector()) { 5389 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5390 return FoldedVOp; 5391 5392 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5393 // If setcc produces all-one true value then: 5394 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5395 if (N1CV && N1CV->isConstant()) { 5396 if (N0.getOpcode() == ISD::AND) { 5397 SDValue N00 = N0->getOperand(0); 5398 SDValue N01 = N0->getOperand(1); 5399 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5400 5401 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5402 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5403 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5404 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5405 N01CV, N1CV)) 5406 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5407 } 5408 } 5409 } 5410 } 5411 5412 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5413 5414 // fold (shl c1, c2) -> c1<<c2 5415 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5416 if (N0C && N1C && !N1C->isOpaque()) 5417 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5418 // fold (shl 0, x) -> 0 5419 if (isNullConstantOrNullSplatConstant(N0)) 5420 return N0; 5421 // fold (shl x, c >= size(x)) -> undef 5422 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5423 return DAG.getUNDEF(VT); 5424 // fold (shl x, 0) -> x 5425 if (N1C && N1C->isNullValue()) 5426 return N0; 5427 // fold (shl undef, x) -> 0 5428 if (N0.isUndef()) 5429 return DAG.getConstant(0, SDLoc(N), VT); 5430 5431 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5432 return NewSel; 5433 5434 // if (shl x, c) is known to be zero, return 0 5435 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5436 APInt::getAllOnesValue(OpSizeInBits))) 5437 return DAG.getConstant(0, SDLoc(N), VT); 5438 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5439 if (N1.getOpcode() == ISD::TRUNCATE && 5440 N1.getOperand(0).getOpcode() == ISD::AND) { 5441 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5442 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5443 } 5444 5445 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5446 return SDValue(N, 0); 5447 5448 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5449 if (N1C && N0.getOpcode() == ISD::SHL) { 5450 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5451 SDLoc DL(N); 5452 APInt c1 = N0C1->getAPIntValue(); 5453 APInt c2 = N1C->getAPIntValue(); 5454 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5455 5456 APInt Sum = c1 + c2; 5457 if (Sum.uge(OpSizeInBits)) 5458 return DAG.getConstant(0, DL, VT); 5459 5460 return DAG.getNode( 5461 ISD::SHL, DL, VT, N0.getOperand(0), 5462 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5463 } 5464 } 5465 5466 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5467 // For this to be valid, the second form must not preserve any of the bits 5468 // that are shifted out by the inner shift in the first form. This means 5469 // the outer shift size must be >= the number of bits added by the ext. 5470 // As a corollary, we don't care what kind of ext it is. 5471 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5472 N0.getOpcode() == ISD::ANY_EXTEND || 5473 N0.getOpcode() == ISD::SIGN_EXTEND) && 5474 N0.getOperand(0).getOpcode() == ISD::SHL) { 5475 SDValue N0Op0 = N0.getOperand(0); 5476 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5477 APInt c1 = N0Op0C1->getAPIntValue(); 5478 APInt c2 = N1C->getAPIntValue(); 5479 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5480 5481 EVT InnerShiftVT = N0Op0.getValueType(); 5482 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5483 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5484 SDLoc DL(N0); 5485 APInt Sum = c1 + c2; 5486 if (Sum.uge(OpSizeInBits)) 5487 return DAG.getConstant(0, DL, VT); 5488 5489 return DAG.getNode( 5490 ISD::SHL, DL, VT, 5491 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5492 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5493 } 5494 } 5495 } 5496 5497 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5498 // Only fold this if the inner zext has no other uses to avoid increasing 5499 // the total number of instructions. 5500 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5501 N0.getOperand(0).getOpcode() == ISD::SRL) { 5502 SDValue N0Op0 = N0.getOperand(0); 5503 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5504 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5505 uint64_t c1 = N0Op0C1->getZExtValue(); 5506 uint64_t c2 = N1C->getZExtValue(); 5507 if (c1 == c2) { 5508 SDValue NewOp0 = N0.getOperand(0); 5509 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5510 SDLoc DL(N); 5511 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5512 NewOp0, 5513 DAG.getConstant(c2, DL, CountVT)); 5514 AddToWorklist(NewSHL.getNode()); 5515 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5516 } 5517 } 5518 } 5519 } 5520 5521 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5522 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5523 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5524 N0->getFlags().hasExact()) { 5525 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5526 uint64_t C1 = N0C1->getZExtValue(); 5527 uint64_t C2 = N1C->getZExtValue(); 5528 SDLoc DL(N); 5529 if (C1 <= C2) 5530 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5531 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5532 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5533 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5534 } 5535 } 5536 5537 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5538 // (and (srl x, (sub c1, c2), MASK) 5539 // Only fold this if the inner shift has no other uses -- if it does, folding 5540 // this will increase the total number of instructions. 5541 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5542 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5543 uint64_t c1 = N0C1->getZExtValue(); 5544 if (c1 < OpSizeInBits) { 5545 uint64_t c2 = N1C->getZExtValue(); 5546 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5547 SDValue Shift; 5548 if (c2 > c1) { 5549 Mask <<= c2 - c1; 5550 SDLoc DL(N); 5551 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5552 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5553 } else { 5554 Mask.lshrInPlace(c1 - c2); 5555 SDLoc DL(N); 5556 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5557 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5558 } 5559 SDLoc DL(N0); 5560 return DAG.getNode(ISD::AND, DL, VT, Shift, 5561 DAG.getConstant(Mask, DL, VT)); 5562 } 5563 } 5564 } 5565 5566 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5567 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5568 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5569 SDLoc DL(N); 5570 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5571 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5572 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5573 } 5574 5575 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5576 // Variant of version done on multiply, except mul by a power of 2 is turned 5577 // into a shift. 5578 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5579 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5580 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5581 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5582 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5583 AddToWorklist(Shl0.getNode()); 5584 AddToWorklist(Shl1.getNode()); 5585 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5586 } 5587 5588 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5589 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5590 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5591 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5592 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5593 if (isConstantOrConstantVector(Shl)) 5594 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5595 } 5596 5597 if (N1C && !N1C->isOpaque()) 5598 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5599 return NewSHL; 5600 5601 return SDValue(); 5602 } 5603 5604 SDValue DAGCombiner::visitSRA(SDNode *N) { 5605 SDValue N0 = N->getOperand(0); 5606 SDValue N1 = N->getOperand(1); 5607 EVT VT = N0.getValueType(); 5608 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5609 5610 // Arithmetic shifting an all-sign-bit value is a no-op. 5611 // fold (sra 0, x) -> 0 5612 // fold (sra -1, x) -> -1 5613 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5614 return N0; 5615 5616 // fold vector ops 5617 if (VT.isVector()) 5618 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5619 return FoldedVOp; 5620 5621 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5622 5623 // fold (sra c1, c2) -> (sra c1, c2) 5624 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5625 if (N0C && N1C && !N1C->isOpaque()) 5626 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5627 // fold (sra x, c >= size(x)) -> undef 5628 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5629 return DAG.getUNDEF(VT); 5630 // fold (sra x, 0) -> x 5631 if (N1C && N1C->isNullValue()) 5632 return N0; 5633 5634 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5635 return NewSel; 5636 5637 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5638 // sext_inreg. 5639 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5640 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5641 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5642 if (VT.isVector()) 5643 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5644 ExtVT, VT.getVectorNumElements()); 5645 if ((!LegalOperations || 5646 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5647 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5648 N0.getOperand(0), DAG.getValueType(ExtVT)); 5649 } 5650 5651 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5652 if (N1C && N0.getOpcode() == ISD::SRA) { 5653 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5654 SDLoc DL(N); 5655 APInt c1 = N0C1->getAPIntValue(); 5656 APInt c2 = N1C->getAPIntValue(); 5657 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5658 5659 APInt Sum = c1 + c2; 5660 if (Sum.uge(OpSizeInBits)) 5661 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5662 5663 return DAG.getNode( 5664 ISD::SRA, DL, VT, N0.getOperand(0), 5665 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5666 } 5667 } 5668 5669 // fold (sra (shl X, m), (sub result_size, n)) 5670 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5671 // result_size - n != m. 5672 // If truncate is free for the target sext(shl) is likely to result in better 5673 // code. 5674 if (N0.getOpcode() == ISD::SHL && N1C) { 5675 // Get the two constanst of the shifts, CN0 = m, CN = n. 5676 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5677 if (N01C) { 5678 LLVMContext &Ctx = *DAG.getContext(); 5679 // Determine what the truncate's result bitsize and type would be. 5680 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5681 5682 if (VT.isVector()) 5683 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5684 5685 // Determine the residual right-shift amount. 5686 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5687 5688 // If the shift is not a no-op (in which case this should be just a sign 5689 // extend already), the truncated to type is legal, sign_extend is legal 5690 // on that type, and the truncate to that type is both legal and free, 5691 // perform the transform. 5692 if ((ShiftAmt > 0) && 5693 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5694 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5695 TLI.isTruncateFree(VT, TruncVT)) { 5696 5697 SDLoc DL(N); 5698 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5699 getShiftAmountTy(N0.getOperand(0).getValueType())); 5700 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5701 N0.getOperand(0), Amt); 5702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5703 Shift); 5704 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5705 N->getValueType(0), Trunc); 5706 } 5707 } 5708 } 5709 5710 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5711 if (N1.getOpcode() == ISD::TRUNCATE && 5712 N1.getOperand(0).getOpcode() == ISD::AND) { 5713 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5714 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5715 } 5716 5717 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5718 // if c1 is equal to the number of bits the trunc removes 5719 if (N0.getOpcode() == ISD::TRUNCATE && 5720 (N0.getOperand(0).getOpcode() == ISD::SRL || 5721 N0.getOperand(0).getOpcode() == ISD::SRA) && 5722 N0.getOperand(0).hasOneUse() && 5723 N0.getOperand(0).getOperand(1).hasOneUse() && 5724 N1C) { 5725 SDValue N0Op0 = N0.getOperand(0); 5726 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5727 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5728 EVT LargeVT = N0Op0.getValueType(); 5729 5730 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5731 SDLoc DL(N); 5732 SDValue Amt = 5733 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5734 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5735 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5736 N0Op0.getOperand(0), Amt); 5737 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5738 } 5739 } 5740 } 5741 5742 // Simplify, based on bits shifted out of the LHS. 5743 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5744 return SDValue(N, 0); 5745 5746 5747 // If the sign bit is known to be zero, switch this to a SRL. 5748 if (DAG.SignBitIsZero(N0)) 5749 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5750 5751 if (N1C && !N1C->isOpaque()) 5752 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5753 return NewSRA; 5754 5755 return SDValue(); 5756 } 5757 5758 SDValue DAGCombiner::visitSRL(SDNode *N) { 5759 SDValue N0 = N->getOperand(0); 5760 SDValue N1 = N->getOperand(1); 5761 EVT VT = N0.getValueType(); 5762 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5763 5764 // fold vector ops 5765 if (VT.isVector()) 5766 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5767 return FoldedVOp; 5768 5769 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5770 5771 // fold (srl c1, c2) -> c1 >>u c2 5772 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5773 if (N0C && N1C && !N1C->isOpaque()) 5774 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5775 // fold (srl 0, x) -> 0 5776 if (isNullConstantOrNullSplatConstant(N0)) 5777 return N0; 5778 // fold (srl x, c >= size(x)) -> undef 5779 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5780 return DAG.getUNDEF(VT); 5781 // fold (srl x, 0) -> x 5782 if (N1C && N1C->isNullValue()) 5783 return N0; 5784 5785 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5786 return NewSel; 5787 5788 // if (srl x, c) is known to be zero, return 0 5789 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5790 APInt::getAllOnesValue(OpSizeInBits))) 5791 return DAG.getConstant(0, SDLoc(N), VT); 5792 5793 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5794 if (N1C && N0.getOpcode() == ISD::SRL) { 5795 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5796 SDLoc DL(N); 5797 APInt c1 = N0C1->getAPIntValue(); 5798 APInt c2 = N1C->getAPIntValue(); 5799 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5800 5801 APInt Sum = c1 + c2; 5802 if (Sum.uge(OpSizeInBits)) 5803 return DAG.getConstant(0, DL, VT); 5804 5805 return DAG.getNode( 5806 ISD::SRL, DL, VT, N0.getOperand(0), 5807 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5808 } 5809 } 5810 5811 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5812 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5813 N0.getOperand(0).getOpcode() == ISD::SRL) { 5814 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 5815 uint64_t c1 = N001C->getZExtValue(); 5816 uint64_t c2 = N1C->getZExtValue(); 5817 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5818 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 5819 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5820 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5821 if (c1 + OpSizeInBits == InnerShiftSize) { 5822 SDLoc DL(N0); 5823 if (c1 + c2 >= InnerShiftSize) 5824 return DAG.getConstant(0, DL, VT); 5825 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5826 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5827 N0.getOperand(0).getOperand(0), 5828 DAG.getConstant(c1 + c2, DL, 5829 ShiftCountVT))); 5830 } 5831 } 5832 } 5833 5834 // fold (srl (shl x, c), c) -> (and x, cst2) 5835 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5836 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5837 SDLoc DL(N); 5838 SDValue Mask = 5839 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5840 AddToWorklist(Mask.getNode()); 5841 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5842 } 5843 5844 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5845 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5846 // Shifting in all undef bits? 5847 EVT SmallVT = N0.getOperand(0).getValueType(); 5848 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5849 if (N1C->getZExtValue() >= BitSize) 5850 return DAG.getUNDEF(VT); 5851 5852 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5853 uint64_t ShiftAmt = N1C->getZExtValue(); 5854 SDLoc DL0(N0); 5855 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5856 N0.getOperand(0), 5857 DAG.getConstant(ShiftAmt, DL0, 5858 getShiftAmountTy(SmallVT))); 5859 AddToWorklist(SmallShift.getNode()); 5860 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 5861 SDLoc DL(N); 5862 return DAG.getNode(ISD::AND, DL, VT, 5863 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5864 DAG.getConstant(Mask, DL, VT)); 5865 } 5866 } 5867 5868 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5869 // bit, which is unmodified by sra. 5870 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5871 if (N0.getOpcode() == ISD::SRA) 5872 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5873 } 5874 5875 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5876 if (N1C && N0.getOpcode() == ISD::CTLZ && 5877 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5878 KnownBits Known; 5879 DAG.computeKnownBits(N0.getOperand(0), Known); 5880 5881 // If any of the input bits are KnownOne, then the input couldn't be all 5882 // zeros, thus the result of the srl will always be zero. 5883 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5884 5885 // If all of the bits input the to ctlz node are known to be zero, then 5886 // the result of the ctlz is "32" and the result of the shift is one. 5887 APInt UnknownBits = ~Known.Zero; 5888 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5889 5890 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5891 if (UnknownBits.isPowerOf2()) { 5892 // Okay, we know that only that the single bit specified by UnknownBits 5893 // could be set on input to the CTLZ node. If this bit is set, the SRL 5894 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5895 // to an SRL/XOR pair, which is likely to simplify more. 5896 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5897 SDValue Op = N0.getOperand(0); 5898 5899 if (ShAmt) { 5900 SDLoc DL(N0); 5901 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5902 DAG.getConstant(ShAmt, DL, 5903 getShiftAmountTy(Op.getValueType()))); 5904 AddToWorklist(Op.getNode()); 5905 } 5906 5907 SDLoc DL(N); 5908 return DAG.getNode(ISD::XOR, DL, VT, 5909 Op, DAG.getConstant(1, DL, VT)); 5910 } 5911 } 5912 5913 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5914 if (N1.getOpcode() == ISD::TRUNCATE && 5915 N1.getOperand(0).getOpcode() == ISD::AND) { 5916 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5917 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5918 } 5919 5920 // fold operands of srl based on knowledge that the low bits are not 5921 // demanded. 5922 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5923 return SDValue(N, 0); 5924 5925 if (N1C && !N1C->isOpaque()) 5926 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5927 return NewSRL; 5928 5929 // Attempt to convert a srl of a load into a narrower zero-extending load. 5930 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5931 return NarrowLoad; 5932 5933 // Here is a common situation. We want to optimize: 5934 // 5935 // %a = ... 5936 // %b = and i32 %a, 2 5937 // %c = srl i32 %b, 1 5938 // brcond i32 %c ... 5939 // 5940 // into 5941 // 5942 // %a = ... 5943 // %b = and %a, 2 5944 // %c = setcc eq %b, 0 5945 // brcond %c ... 5946 // 5947 // However when after the source operand of SRL is optimized into AND, the SRL 5948 // itself may not be optimized further. Look for it and add the BRCOND into 5949 // the worklist. 5950 if (N->hasOneUse()) { 5951 SDNode *Use = *N->use_begin(); 5952 if (Use->getOpcode() == ISD::BRCOND) 5953 AddToWorklist(Use); 5954 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5955 // Also look pass the truncate. 5956 Use = *Use->use_begin(); 5957 if (Use->getOpcode() == ISD::BRCOND) 5958 AddToWorklist(Use); 5959 } 5960 } 5961 5962 return SDValue(); 5963 } 5964 5965 SDValue DAGCombiner::visitABS(SDNode *N) { 5966 SDValue N0 = N->getOperand(0); 5967 EVT VT = N->getValueType(0); 5968 5969 // fold (abs c1) -> c2 5970 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5971 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 5972 // fold (abs (abs x)) -> (abs x) 5973 if (N0.getOpcode() == ISD::ABS) 5974 return N0; 5975 // fold (abs x) -> x iff not-negative 5976 if (DAG.SignBitIsZero(N0)) 5977 return N0; 5978 return SDValue(); 5979 } 5980 5981 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5982 SDValue N0 = N->getOperand(0); 5983 EVT VT = N->getValueType(0); 5984 5985 // fold (bswap c1) -> c2 5986 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5987 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5988 // fold (bswap (bswap x)) -> x 5989 if (N0.getOpcode() == ISD::BSWAP) 5990 return N0->getOperand(0); 5991 return SDValue(); 5992 } 5993 5994 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5995 SDValue N0 = N->getOperand(0); 5996 EVT VT = N->getValueType(0); 5997 5998 // fold (bitreverse c1) -> c2 5999 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6000 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 6001 // fold (bitreverse (bitreverse x)) -> x 6002 if (N0.getOpcode() == ISD::BITREVERSE) 6003 return N0.getOperand(0); 6004 return SDValue(); 6005 } 6006 6007 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 6008 SDValue N0 = N->getOperand(0); 6009 EVT VT = N->getValueType(0); 6010 6011 // fold (ctlz c1) -> c2 6012 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6013 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 6014 return SDValue(); 6015 } 6016 6017 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 6018 SDValue N0 = N->getOperand(0); 6019 EVT VT = N->getValueType(0); 6020 6021 // fold (ctlz_zero_undef c1) -> c2 6022 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6023 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6024 return SDValue(); 6025 } 6026 6027 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 6028 SDValue N0 = N->getOperand(0); 6029 EVT VT = N->getValueType(0); 6030 6031 // fold (cttz c1) -> c2 6032 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6033 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 6034 return SDValue(); 6035 } 6036 6037 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 6038 SDValue N0 = N->getOperand(0); 6039 EVT VT = N->getValueType(0); 6040 6041 // fold (cttz_zero_undef c1) -> c2 6042 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6043 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 6044 return SDValue(); 6045 } 6046 6047 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 6048 SDValue N0 = N->getOperand(0); 6049 EVT VT = N->getValueType(0); 6050 6051 // fold (ctpop c1) -> c2 6052 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6053 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 6054 return SDValue(); 6055 } 6056 6057 6058 /// \brief Generate Min/Max node 6059 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6060 SDValue RHS, SDValue True, SDValue False, 6061 ISD::CondCode CC, const TargetLowering &TLI, 6062 SelectionDAG &DAG) { 6063 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6064 return SDValue(); 6065 6066 switch (CC) { 6067 case ISD::SETOLT: 6068 case ISD::SETOLE: 6069 case ISD::SETLT: 6070 case ISD::SETLE: 6071 case ISD::SETULT: 6072 case ISD::SETULE: { 6073 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6074 if (TLI.isOperationLegal(Opcode, VT)) 6075 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6076 return SDValue(); 6077 } 6078 case ISD::SETOGT: 6079 case ISD::SETOGE: 6080 case ISD::SETGT: 6081 case ISD::SETGE: 6082 case ISD::SETUGT: 6083 case ISD::SETUGE: { 6084 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6085 if (TLI.isOperationLegal(Opcode, VT)) 6086 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6087 return SDValue(); 6088 } 6089 default: 6090 return SDValue(); 6091 } 6092 } 6093 6094 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6095 SDValue Cond = N->getOperand(0); 6096 SDValue N1 = N->getOperand(1); 6097 SDValue N2 = N->getOperand(2); 6098 EVT VT = N->getValueType(0); 6099 EVT CondVT = Cond.getValueType(); 6100 SDLoc DL(N); 6101 6102 if (!VT.isInteger()) 6103 return SDValue(); 6104 6105 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6106 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6107 if (!C1 || !C2) 6108 return SDValue(); 6109 6110 // Only do this before legalization to avoid conflicting with target-specific 6111 // transforms in the other direction (create a select from a zext/sext). There 6112 // is also a target-independent combine here in DAGCombiner in the other 6113 // direction for (select Cond, -1, 0) when the condition is not i1. 6114 if (CondVT == MVT::i1 && !LegalOperations) { 6115 if (C1->isNullValue() && C2->isOne()) { 6116 // select Cond, 0, 1 --> zext (!Cond) 6117 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6118 if (VT != MVT::i1) 6119 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6120 return NotCond; 6121 } 6122 if (C1->isNullValue() && C2->isAllOnesValue()) { 6123 // select Cond, 0, -1 --> sext (!Cond) 6124 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6125 if (VT != MVT::i1) 6126 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6127 return NotCond; 6128 } 6129 if (C1->isOne() && C2->isNullValue()) { 6130 // select Cond, 1, 0 --> zext (Cond) 6131 if (VT != MVT::i1) 6132 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6133 return Cond; 6134 } 6135 if (C1->isAllOnesValue() && C2->isNullValue()) { 6136 // select Cond, -1, 0 --> sext (Cond) 6137 if (VT != MVT::i1) 6138 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6139 return Cond; 6140 } 6141 6142 // For any constants that differ by 1, we can transform the select into an 6143 // extend and add. Use a target hook because some targets may prefer to 6144 // transform in the other direction. 6145 if (TLI.convertSelectOfConstantsToMath()) { 6146 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6147 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6148 if (VT != MVT::i1) 6149 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6150 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6151 } 6152 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6153 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6154 if (VT != MVT::i1) 6155 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6156 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6157 } 6158 } 6159 6160 return SDValue(); 6161 } 6162 6163 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6164 // We can't do this reliably if integer based booleans have different contents 6165 // to floating point based booleans. This is because we can't tell whether we 6166 // have an integer-based boolean or a floating-point-based boolean unless we 6167 // can find the SETCC that produced it and inspect its operands. This is 6168 // fairly easy if C is the SETCC node, but it can potentially be 6169 // undiscoverable (or not reasonably discoverable). For example, it could be 6170 // in another basic block or it could require searching a complicated 6171 // expression. 6172 if (CondVT.isInteger() && 6173 TLI.getBooleanContents(false, true) == 6174 TargetLowering::ZeroOrOneBooleanContent && 6175 TLI.getBooleanContents(false, false) == 6176 TargetLowering::ZeroOrOneBooleanContent && 6177 C1->isNullValue() && C2->isOne()) { 6178 SDValue NotCond = 6179 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6180 if (VT.bitsEq(CondVT)) 6181 return NotCond; 6182 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6183 } 6184 6185 return SDValue(); 6186 } 6187 6188 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6189 SDValue N0 = N->getOperand(0); 6190 SDValue N1 = N->getOperand(1); 6191 SDValue N2 = N->getOperand(2); 6192 EVT VT = N->getValueType(0); 6193 EVT VT0 = N0.getValueType(); 6194 6195 // fold (select C, X, X) -> X 6196 if (N1 == N2) 6197 return N1; 6198 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6199 // fold (select true, X, Y) -> X 6200 // fold (select false, X, Y) -> Y 6201 return !N0C->isNullValue() ? N1 : N2; 6202 } 6203 // fold (select X, X, Y) -> (or X, Y) 6204 // fold (select X, 1, Y) -> (or C, Y) 6205 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6206 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 6207 6208 if (SDValue V = foldSelectOfConstants(N)) 6209 return V; 6210 6211 // fold (select C, 0, X) -> (and (not C), X) 6212 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6213 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6214 AddToWorklist(NOTNode.getNode()); 6215 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 6216 } 6217 // fold (select C, X, 1) -> (or (not C), X) 6218 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6219 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6220 AddToWorklist(NOTNode.getNode()); 6221 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 6222 } 6223 // fold (select X, Y, X) -> (and X, Y) 6224 // fold (select X, Y, 0) -> (and X, Y) 6225 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6226 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 6227 6228 // If we can fold this based on the true/false value, do so. 6229 if (SimplifySelectOps(N, N1, N2)) 6230 return SDValue(N, 0); // Don't revisit N. 6231 6232 if (VT0 == MVT::i1) { 6233 // The code in this block deals with the following 2 equivalences: 6234 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6235 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6236 // The target can specify its preferred form with the 6237 // shouldNormalizeToSelectSequence() callback. However we always transform 6238 // to the right anyway if we find the inner select exists in the DAG anyway 6239 // and we always transform to the left side if we know that we can further 6240 // optimize the combination of the conditions. 6241 bool normalizeToSequence 6242 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6243 // select (and Cond0, Cond1), X, Y 6244 // -> select Cond0, (select Cond1, X, Y), Y 6245 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6246 SDValue Cond0 = N0->getOperand(0); 6247 SDValue Cond1 = N0->getOperand(1); 6248 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6249 N1.getValueType(), Cond1, N1, N2); 6250 if (normalizeToSequence || !InnerSelect.use_empty()) 6251 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 6252 InnerSelect, N2); 6253 } 6254 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6255 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6256 SDValue Cond0 = N0->getOperand(0); 6257 SDValue Cond1 = N0->getOperand(1); 6258 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6259 N1.getValueType(), Cond1, N1, N2); 6260 if (normalizeToSequence || !InnerSelect.use_empty()) 6261 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 6262 InnerSelect); 6263 } 6264 6265 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6266 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6267 SDValue N1_0 = N1->getOperand(0); 6268 SDValue N1_1 = N1->getOperand(1); 6269 SDValue N1_2 = N1->getOperand(2); 6270 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6271 // Create the actual and node if we can generate good code for it. 6272 if (!normalizeToSequence) { 6273 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 6274 N0, N1_0); 6275 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 6276 N1_1, N2); 6277 } 6278 // Otherwise see if we can optimize the "and" to a better pattern. 6279 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6280 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6281 N1_1, N2); 6282 } 6283 } 6284 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6285 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6286 SDValue N2_0 = N2->getOperand(0); 6287 SDValue N2_1 = N2->getOperand(1); 6288 SDValue N2_2 = N2->getOperand(2); 6289 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6290 // Create the actual or node if we can generate good code for it. 6291 if (!normalizeToSequence) { 6292 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 6293 N0, N2_0); 6294 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 6295 N1, N2_2); 6296 } 6297 // Otherwise see if we can optimize to a better pattern. 6298 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6299 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6300 N1, N2_2); 6301 } 6302 } 6303 } 6304 6305 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6306 if (VT0 == MVT::i1) { 6307 if (N0->getOpcode() == ISD::XOR) { 6308 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6309 SDValue Cond0 = N0->getOperand(0); 6310 if (C->isOne()) 6311 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 6312 Cond0, N2, N1); 6313 } 6314 } 6315 } 6316 6317 // fold selects based on a setcc into other things, such as min/max/abs 6318 if (N0.getOpcode() == ISD::SETCC) { 6319 // select x, y (fcmp lt x, y) -> fminnum x, y 6320 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6321 // 6322 // This is OK if we don't care about what happens if either operand is a 6323 // NaN. 6324 // 6325 6326 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6327 // no signed zeros as well as no nans. 6328 const TargetOptions &Options = DAG.getTarget().Options; 6329 if (Options.UnsafeFPMath && 6330 VT.isFloatingPoint() && N0.hasOneUse() && 6331 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6332 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6333 6334 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 6335 N0.getOperand(1), N1, N2, CC, 6336 TLI, DAG)) 6337 return FMinMax; 6338 } 6339 6340 if ((!LegalOperations && 6341 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6342 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6343 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 6344 N0.getOperand(0), N0.getOperand(1), 6345 N1, N2, N0.getOperand(2)); 6346 return SimplifySelect(SDLoc(N), N0, N1, N2); 6347 } 6348 6349 return SDValue(); 6350 } 6351 6352 static 6353 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6354 SDLoc DL(N); 6355 EVT LoVT, HiVT; 6356 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6357 6358 // Split the inputs. 6359 SDValue Lo, Hi, LL, LH, RL, RH; 6360 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6361 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6362 6363 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6364 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6365 6366 return std::make_pair(Lo, Hi); 6367 } 6368 6369 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6370 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6371 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6372 SDLoc DL(N); 6373 SDValue Cond = N->getOperand(0); 6374 SDValue LHS = N->getOperand(1); 6375 SDValue RHS = N->getOperand(2); 6376 EVT VT = N->getValueType(0); 6377 int NumElems = VT.getVectorNumElements(); 6378 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6379 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6380 Cond.getOpcode() == ISD::BUILD_VECTOR); 6381 6382 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6383 // binary ones here. 6384 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6385 return SDValue(); 6386 6387 // We're sure we have an even number of elements due to the 6388 // concat_vectors we have as arguments to vselect. 6389 // Skip BV elements until we find one that's not an UNDEF 6390 // After we find an UNDEF element, keep looping until we get to half the 6391 // length of the BV and see if all the non-undef nodes are the same. 6392 ConstantSDNode *BottomHalf = nullptr; 6393 for (int i = 0; i < NumElems / 2; ++i) { 6394 if (Cond->getOperand(i)->isUndef()) 6395 continue; 6396 6397 if (BottomHalf == nullptr) 6398 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6399 else if (Cond->getOperand(i).getNode() != BottomHalf) 6400 return SDValue(); 6401 } 6402 6403 // Do the same for the second half of the BuildVector 6404 ConstantSDNode *TopHalf = nullptr; 6405 for (int i = NumElems / 2; i < NumElems; ++i) { 6406 if (Cond->getOperand(i)->isUndef()) 6407 continue; 6408 6409 if (TopHalf == nullptr) 6410 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6411 else if (Cond->getOperand(i).getNode() != TopHalf) 6412 return SDValue(); 6413 } 6414 6415 assert(TopHalf && BottomHalf && 6416 "One half of the selector was all UNDEFs and the other was all the " 6417 "same value. This should have been addressed before this function."); 6418 return DAG.getNode( 6419 ISD::CONCAT_VECTORS, DL, VT, 6420 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6421 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6422 } 6423 6424 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6425 6426 if (Level >= AfterLegalizeTypes) 6427 return SDValue(); 6428 6429 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6430 SDValue Mask = MSC->getMask(); 6431 SDValue Data = MSC->getValue(); 6432 SDLoc DL(N); 6433 6434 // If the MSCATTER data type requires splitting and the mask is provided by a 6435 // SETCC, then split both nodes and its operands before legalization. This 6436 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6437 // and enables future optimizations (e.g. min/max pattern matching on X86). 6438 if (Mask.getOpcode() != ISD::SETCC) 6439 return SDValue(); 6440 6441 // Check if any splitting is required. 6442 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6443 TargetLowering::TypeSplitVector) 6444 return SDValue(); 6445 SDValue MaskLo, MaskHi, Lo, Hi; 6446 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6447 6448 EVT LoVT, HiVT; 6449 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6450 6451 SDValue Chain = MSC->getChain(); 6452 6453 EVT MemoryVT = MSC->getMemoryVT(); 6454 unsigned Alignment = MSC->getOriginalAlignment(); 6455 6456 EVT LoMemVT, HiMemVT; 6457 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6458 6459 SDValue DataLo, DataHi; 6460 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6461 6462 SDValue BasePtr = MSC->getBasePtr(); 6463 SDValue IndexLo, IndexHi; 6464 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6465 6466 MachineMemOperand *MMO = DAG.getMachineFunction(). 6467 getMachineMemOperand(MSC->getPointerInfo(), 6468 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6469 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6470 6471 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6472 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6473 DL, OpsLo, MMO); 6474 6475 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6476 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6477 DL, OpsHi, MMO); 6478 6479 AddToWorklist(Lo.getNode()); 6480 AddToWorklist(Hi.getNode()); 6481 6482 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6483 } 6484 6485 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6486 6487 if (Level >= AfterLegalizeTypes) 6488 return SDValue(); 6489 6490 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6491 SDValue Mask = MST->getMask(); 6492 SDValue Data = MST->getValue(); 6493 EVT VT = Data.getValueType(); 6494 SDLoc DL(N); 6495 6496 // If the MSTORE data type requires splitting and the mask is provided by a 6497 // SETCC, then split both nodes and its operands before legalization. This 6498 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6499 // and enables future optimizations (e.g. min/max pattern matching on X86). 6500 if (Mask.getOpcode() == ISD::SETCC) { 6501 6502 // Check if any splitting is required. 6503 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6504 TargetLowering::TypeSplitVector) 6505 return SDValue(); 6506 6507 SDValue MaskLo, MaskHi, Lo, Hi; 6508 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6509 6510 SDValue Chain = MST->getChain(); 6511 SDValue Ptr = MST->getBasePtr(); 6512 6513 EVT MemoryVT = MST->getMemoryVT(); 6514 unsigned Alignment = MST->getOriginalAlignment(); 6515 6516 // if Alignment is equal to the vector size, 6517 // take the half of it for the second part 6518 unsigned SecondHalfAlignment = 6519 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6520 6521 EVT LoMemVT, HiMemVT; 6522 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6523 6524 SDValue DataLo, DataHi; 6525 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6526 6527 MachineMemOperand *MMO = DAG.getMachineFunction(). 6528 getMachineMemOperand(MST->getPointerInfo(), 6529 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6530 Alignment, MST->getAAInfo(), MST->getRanges()); 6531 6532 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6533 MST->isTruncatingStore(), 6534 MST->isCompressingStore()); 6535 6536 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6537 MST->isCompressingStore()); 6538 6539 MMO = DAG.getMachineFunction(). 6540 getMachineMemOperand(MST->getPointerInfo(), 6541 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6542 SecondHalfAlignment, MST->getAAInfo(), 6543 MST->getRanges()); 6544 6545 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6546 MST->isTruncatingStore(), 6547 MST->isCompressingStore()); 6548 6549 AddToWorklist(Lo.getNode()); 6550 AddToWorklist(Hi.getNode()); 6551 6552 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6553 } 6554 return SDValue(); 6555 } 6556 6557 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6558 6559 if (Level >= AfterLegalizeTypes) 6560 return SDValue(); 6561 6562 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6563 SDValue Mask = MGT->getMask(); 6564 SDLoc DL(N); 6565 6566 // If the MGATHER result requires splitting and the mask is provided by a 6567 // SETCC, then split both nodes and its operands before legalization. This 6568 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6569 // and enables future optimizations (e.g. min/max pattern matching on X86). 6570 6571 if (Mask.getOpcode() != ISD::SETCC) 6572 return SDValue(); 6573 6574 EVT VT = N->getValueType(0); 6575 6576 // Check if any splitting is required. 6577 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6578 TargetLowering::TypeSplitVector) 6579 return SDValue(); 6580 6581 SDValue MaskLo, MaskHi, Lo, Hi; 6582 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6583 6584 SDValue Src0 = MGT->getValue(); 6585 SDValue Src0Lo, Src0Hi; 6586 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6587 6588 EVT LoVT, HiVT; 6589 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6590 6591 SDValue Chain = MGT->getChain(); 6592 EVT MemoryVT = MGT->getMemoryVT(); 6593 unsigned Alignment = MGT->getOriginalAlignment(); 6594 6595 EVT LoMemVT, HiMemVT; 6596 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6597 6598 SDValue BasePtr = MGT->getBasePtr(); 6599 SDValue Index = MGT->getIndex(); 6600 SDValue IndexLo, IndexHi; 6601 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6602 6603 MachineMemOperand *MMO = DAG.getMachineFunction(). 6604 getMachineMemOperand(MGT->getPointerInfo(), 6605 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6606 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6607 6608 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6609 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6610 MMO); 6611 6612 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6613 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6614 MMO); 6615 6616 AddToWorklist(Lo.getNode()); 6617 AddToWorklist(Hi.getNode()); 6618 6619 // Build a factor node to remember that this load is independent of the 6620 // other one. 6621 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6622 Hi.getValue(1)); 6623 6624 // Legalized the chain result - switch anything that used the old chain to 6625 // use the new one. 6626 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6627 6628 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6629 6630 SDValue RetOps[] = { GatherRes, Chain }; 6631 return DAG.getMergeValues(RetOps, DL); 6632 } 6633 6634 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6635 6636 if (Level >= AfterLegalizeTypes) 6637 return SDValue(); 6638 6639 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6640 SDValue Mask = MLD->getMask(); 6641 SDLoc DL(N); 6642 6643 // If the MLOAD result requires splitting and the mask is provided by a 6644 // SETCC, then split both nodes and its operands before legalization. This 6645 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6646 // and enables future optimizations (e.g. min/max pattern matching on X86). 6647 6648 if (Mask.getOpcode() == ISD::SETCC) { 6649 EVT VT = N->getValueType(0); 6650 6651 // Check if any splitting is required. 6652 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6653 TargetLowering::TypeSplitVector) 6654 return SDValue(); 6655 6656 SDValue MaskLo, MaskHi, Lo, Hi; 6657 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6658 6659 SDValue Src0 = MLD->getSrc0(); 6660 SDValue Src0Lo, Src0Hi; 6661 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6662 6663 EVT LoVT, HiVT; 6664 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6665 6666 SDValue Chain = MLD->getChain(); 6667 SDValue Ptr = MLD->getBasePtr(); 6668 EVT MemoryVT = MLD->getMemoryVT(); 6669 unsigned Alignment = MLD->getOriginalAlignment(); 6670 6671 // if Alignment is equal to the vector size, 6672 // take the half of it for the second part 6673 unsigned SecondHalfAlignment = 6674 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6675 Alignment/2 : Alignment; 6676 6677 EVT LoMemVT, HiMemVT; 6678 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6679 6680 MachineMemOperand *MMO = DAG.getMachineFunction(). 6681 getMachineMemOperand(MLD->getPointerInfo(), 6682 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6683 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6684 6685 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6686 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6687 6688 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6689 MLD->isExpandingLoad()); 6690 6691 MMO = DAG.getMachineFunction(). 6692 getMachineMemOperand(MLD->getPointerInfo(), 6693 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6694 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6695 6696 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6697 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6698 6699 AddToWorklist(Lo.getNode()); 6700 AddToWorklist(Hi.getNode()); 6701 6702 // Build a factor node to remember that this load is independent of the 6703 // other one. 6704 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6705 Hi.getValue(1)); 6706 6707 // Legalized the chain result - switch anything that used the old chain to 6708 // use the new one. 6709 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6710 6711 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6712 6713 SDValue RetOps[] = { LoadRes, Chain }; 6714 return DAG.getMergeValues(RetOps, DL); 6715 } 6716 return SDValue(); 6717 } 6718 6719 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6720 SDValue N0 = N->getOperand(0); 6721 SDValue N1 = N->getOperand(1); 6722 SDValue N2 = N->getOperand(2); 6723 SDLoc DL(N); 6724 6725 // fold (vselect C, X, X) -> X 6726 if (N1 == N2) 6727 return N1; 6728 6729 // Canonicalize integer abs. 6730 // vselect (setg[te] X, 0), X, -X -> 6731 // vselect (setgt X, -1), X, -X -> 6732 // vselect (setl[te] X, 0), -X, X -> 6733 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6734 if (N0.getOpcode() == ISD::SETCC) { 6735 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6736 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6737 bool isAbs = false; 6738 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6739 6740 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6741 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6742 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6743 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6744 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6745 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6746 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6747 6748 if (isAbs) { 6749 EVT VT = LHS.getValueType(); 6750 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 6751 return DAG.getNode(ISD::ABS, DL, VT, LHS); 6752 6753 SDValue Shift = DAG.getNode( 6754 ISD::SRA, DL, VT, LHS, 6755 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6756 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6757 AddToWorklist(Shift.getNode()); 6758 AddToWorklist(Add.getNode()); 6759 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6760 } 6761 } 6762 6763 if (SimplifySelectOps(N, N1, N2)) 6764 return SDValue(N, 0); // Don't revisit N. 6765 6766 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6767 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6768 return N1; 6769 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6770 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6771 return N2; 6772 6773 // The ConvertSelectToConcatVector function is assuming both the above 6774 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6775 // and addressed. 6776 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6777 N2.getOpcode() == ISD::CONCAT_VECTORS && 6778 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6779 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6780 return CV; 6781 } 6782 6783 return SDValue(); 6784 } 6785 6786 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6787 SDValue N0 = N->getOperand(0); 6788 SDValue N1 = N->getOperand(1); 6789 SDValue N2 = N->getOperand(2); 6790 SDValue N3 = N->getOperand(3); 6791 SDValue N4 = N->getOperand(4); 6792 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6793 6794 // fold select_cc lhs, rhs, x, x, cc -> x 6795 if (N2 == N3) 6796 return N2; 6797 6798 // Determine if the condition we're dealing with is constant 6799 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6800 CC, SDLoc(N), false)) { 6801 AddToWorklist(SCC.getNode()); 6802 6803 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6804 if (!SCCC->isNullValue()) 6805 return N2; // cond always true -> true val 6806 else 6807 return N3; // cond always false -> false val 6808 } else if (SCC->isUndef()) { 6809 // When the condition is UNDEF, just return the first operand. This is 6810 // coherent the DAG creation, no setcc node is created in this case 6811 return N2; 6812 } else if (SCC.getOpcode() == ISD::SETCC) { 6813 // Fold to a simpler select_cc 6814 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6815 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6816 SCC.getOperand(2)); 6817 } 6818 } 6819 6820 // If we can fold this based on the true/false value, do so. 6821 if (SimplifySelectOps(N, N2, N3)) 6822 return SDValue(N, 0); // Don't revisit N. 6823 6824 // fold select_cc into other things, such as min/max/abs 6825 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6826 } 6827 6828 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6829 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6830 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6831 SDLoc(N)); 6832 } 6833 6834 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6835 SDValue LHS = N->getOperand(0); 6836 SDValue RHS = N->getOperand(1); 6837 SDValue Carry = N->getOperand(2); 6838 SDValue Cond = N->getOperand(3); 6839 6840 // If Carry is false, fold to a regular SETCC. 6841 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6842 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6843 6844 return SDValue(); 6845 } 6846 6847 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 6848 SDValue LHS = N->getOperand(0); 6849 SDValue RHS = N->getOperand(1); 6850 SDValue Carry = N->getOperand(2); 6851 SDValue Cond = N->getOperand(3); 6852 6853 // If Carry is false, fold to a regular SETCC. 6854 if (isNullConstant(Carry)) 6855 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6856 6857 return SDValue(); 6858 } 6859 6860 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6861 /// a build_vector of constants. 6862 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6863 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6864 /// Vector extends are not folded if operations are legal; this is to 6865 /// avoid introducing illegal build_vector dag nodes. 6866 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6867 SelectionDAG &DAG, bool LegalTypes, 6868 bool LegalOperations) { 6869 unsigned Opcode = N->getOpcode(); 6870 SDValue N0 = N->getOperand(0); 6871 EVT VT = N->getValueType(0); 6872 6873 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6874 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6875 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6876 && "Expected EXTEND dag node in input!"); 6877 6878 // fold (sext c1) -> c1 6879 // fold (zext c1) -> c1 6880 // fold (aext c1) -> c1 6881 if (isa<ConstantSDNode>(N0)) 6882 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6883 6884 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6885 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6886 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6887 EVT SVT = VT.getScalarType(); 6888 if (!(VT.isVector() && 6889 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6890 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6891 return nullptr; 6892 6893 // We can fold this node into a build_vector. 6894 unsigned VTBits = SVT.getSizeInBits(); 6895 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6896 SmallVector<SDValue, 8> Elts; 6897 unsigned NumElts = VT.getVectorNumElements(); 6898 SDLoc DL(N); 6899 6900 for (unsigned i=0; i != NumElts; ++i) { 6901 SDValue Op = N0->getOperand(i); 6902 if (Op->isUndef()) { 6903 Elts.push_back(DAG.getUNDEF(SVT)); 6904 continue; 6905 } 6906 6907 SDLoc DL(Op); 6908 // Get the constant value and if needed trunc it to the size of the type. 6909 // Nodes like build_vector might have constants wider than the scalar type. 6910 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6911 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6912 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6913 else 6914 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6915 } 6916 6917 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6918 } 6919 6920 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6921 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6922 // transformation. Returns true if extension are possible and the above 6923 // mentioned transformation is profitable. 6924 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6925 unsigned ExtOpc, 6926 SmallVectorImpl<SDNode *> &ExtendNodes, 6927 const TargetLowering &TLI) { 6928 bool HasCopyToRegUses = false; 6929 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6930 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6931 UE = N0.getNode()->use_end(); 6932 UI != UE; ++UI) { 6933 SDNode *User = *UI; 6934 if (User == N) 6935 continue; 6936 if (UI.getUse().getResNo() != N0.getResNo()) 6937 continue; 6938 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6939 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6940 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6941 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6942 // Sign bits will be lost after a zext. 6943 return false; 6944 bool Add = false; 6945 for (unsigned i = 0; i != 2; ++i) { 6946 SDValue UseOp = User->getOperand(i); 6947 if (UseOp == N0) 6948 continue; 6949 if (!isa<ConstantSDNode>(UseOp)) 6950 return false; 6951 Add = true; 6952 } 6953 if (Add) 6954 ExtendNodes.push_back(User); 6955 continue; 6956 } 6957 // If truncates aren't free and there are users we can't 6958 // extend, it isn't worthwhile. 6959 if (!isTruncFree) 6960 return false; 6961 // Remember if this value is live-out. 6962 if (User->getOpcode() == ISD::CopyToReg) 6963 HasCopyToRegUses = true; 6964 } 6965 6966 if (HasCopyToRegUses) { 6967 bool BothLiveOut = false; 6968 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6969 UI != UE; ++UI) { 6970 SDUse &Use = UI.getUse(); 6971 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6972 BothLiveOut = true; 6973 break; 6974 } 6975 } 6976 if (BothLiveOut) 6977 // Both unextended and extended values are live out. There had better be 6978 // a good reason for the transformation. 6979 return ExtendNodes.size(); 6980 } 6981 return true; 6982 } 6983 6984 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6985 SDValue Trunc, SDValue ExtLoad, 6986 const SDLoc &DL, ISD::NodeType ExtType) { 6987 // Extend SetCC uses if necessary. 6988 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6989 SDNode *SetCC = SetCCs[i]; 6990 SmallVector<SDValue, 4> Ops; 6991 6992 for (unsigned j = 0; j != 2; ++j) { 6993 SDValue SOp = SetCC->getOperand(j); 6994 if (SOp == Trunc) 6995 Ops.push_back(ExtLoad); 6996 else 6997 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6998 } 6999 7000 Ops.push_back(SetCC->getOperand(2)); 7001 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7002 } 7003 } 7004 7005 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 7006 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 7007 SDValue N0 = N->getOperand(0); 7008 EVT DstVT = N->getValueType(0); 7009 EVT SrcVT = N0.getValueType(); 7010 7011 assert((N->getOpcode() == ISD::SIGN_EXTEND || 7012 N->getOpcode() == ISD::ZERO_EXTEND) && 7013 "Unexpected node type (not an extend)!"); 7014 7015 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 7016 // For example, on a target with legal v4i32, but illegal v8i32, turn: 7017 // (v8i32 (sext (v8i16 (load x)))) 7018 // into: 7019 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7020 // (v4i32 (sextload (x + 16))))) 7021 // Where uses of the original load, i.e.: 7022 // (v8i16 (load x)) 7023 // are replaced with: 7024 // (v8i16 (truncate 7025 // (v8i32 (concat_vectors (v4i32 (sextload x)), 7026 // (v4i32 (sextload (x + 16))))))) 7027 // 7028 // This combine is only applicable to illegal, but splittable, vectors. 7029 // All legal types, and illegal non-vector types, are handled elsewhere. 7030 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 7031 // 7032 if (N0->getOpcode() != ISD::LOAD) 7033 return SDValue(); 7034 7035 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7036 7037 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 7038 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 7039 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 7040 return SDValue(); 7041 7042 SmallVector<SDNode *, 4> SetCCs; 7043 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 7044 return SDValue(); 7045 7046 ISD::LoadExtType ExtType = 7047 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 7048 7049 // Try to split the vector types to get down to legal types. 7050 EVT SplitSrcVT = SrcVT; 7051 EVT SplitDstVT = DstVT; 7052 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 7053 SplitSrcVT.getVectorNumElements() > 1) { 7054 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 7055 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 7056 } 7057 7058 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 7059 return SDValue(); 7060 7061 SDLoc DL(N); 7062 const unsigned NumSplits = 7063 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 7064 const unsigned Stride = SplitSrcVT.getStoreSize(); 7065 SmallVector<SDValue, 4> Loads; 7066 SmallVector<SDValue, 4> Chains; 7067 7068 SDValue BasePtr = LN0->getBasePtr(); 7069 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 7070 const unsigned Offset = Idx * Stride; 7071 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7072 7073 SDValue SplitLoad = DAG.getExtLoad( 7074 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7075 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7076 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7077 7078 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7079 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7080 7081 Loads.push_back(SplitLoad.getValue(0)); 7082 Chains.push_back(SplitLoad.getValue(1)); 7083 } 7084 7085 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7086 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7087 7088 // Simplify TF. 7089 AddToWorklist(NewChain.getNode()); 7090 7091 CombineTo(N, NewValue); 7092 7093 // Replace uses of the original load (before extension) 7094 // with a truncate of the concatenated sextloaded vectors. 7095 SDValue Trunc = 7096 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7097 CombineTo(N0.getNode(), Trunc, NewChain); 7098 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7099 (ISD::NodeType)N->getOpcode()); 7100 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7101 } 7102 7103 /// If we're narrowing or widening the result of a vector select and the final 7104 /// size is the same size as a setcc (compare) feeding the select, then try to 7105 /// apply the cast operation to the select's operands because matching vector 7106 /// sizes for a select condition and other operands should be more efficient. 7107 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7108 unsigned CastOpcode = Cast->getOpcode(); 7109 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7110 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7111 CastOpcode == ISD::FP_ROUND) && 7112 "Unexpected opcode for vector select narrowing/widening"); 7113 7114 // We only do this transform before legal ops because the pattern may be 7115 // obfuscated by target-specific operations after legalization. Do not create 7116 // an illegal select op, however, because that may be difficult to lower. 7117 EVT VT = Cast->getValueType(0); 7118 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7119 return SDValue(); 7120 7121 SDValue VSel = Cast->getOperand(0); 7122 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7123 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7124 return SDValue(); 7125 7126 // Does the setcc have the same vector size as the casted select? 7127 SDValue SetCC = VSel.getOperand(0); 7128 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7129 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7130 return SDValue(); 7131 7132 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7133 SDValue A = VSel.getOperand(1); 7134 SDValue B = VSel.getOperand(2); 7135 SDValue CastA, CastB; 7136 SDLoc DL(Cast); 7137 if (CastOpcode == ISD::FP_ROUND) { 7138 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7139 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7140 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7141 } else { 7142 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7143 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7144 } 7145 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7146 } 7147 7148 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7149 SDValue N0 = N->getOperand(0); 7150 EVT VT = N->getValueType(0); 7151 SDLoc DL(N); 7152 7153 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7154 LegalOperations)) 7155 return SDValue(Res, 0); 7156 7157 // fold (sext (sext x)) -> (sext x) 7158 // fold (sext (aext x)) -> (sext x) 7159 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7160 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7161 7162 if (N0.getOpcode() == ISD::TRUNCATE) { 7163 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7164 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7165 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7166 SDNode *oye = N0.getOperand(0).getNode(); 7167 if (NarrowLoad.getNode() != N0.getNode()) { 7168 CombineTo(N0.getNode(), NarrowLoad); 7169 // CombineTo deleted the truncate, if needed, but not what's under it. 7170 AddToWorklist(oye); 7171 } 7172 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7173 } 7174 7175 // See if the value being truncated is already sign extended. If so, just 7176 // eliminate the trunc/sext pair. 7177 SDValue Op = N0.getOperand(0); 7178 unsigned OpBits = Op.getScalarValueSizeInBits(); 7179 unsigned MidBits = N0.getScalarValueSizeInBits(); 7180 unsigned DestBits = VT.getScalarSizeInBits(); 7181 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7182 7183 if (OpBits == DestBits) { 7184 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7185 // bits, it is already ready. 7186 if (NumSignBits > DestBits-MidBits) 7187 return Op; 7188 } else if (OpBits < DestBits) { 7189 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7190 // bits, just sext from i32. 7191 if (NumSignBits > OpBits-MidBits) 7192 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7193 } else { 7194 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7195 // bits, just truncate to i32. 7196 if (NumSignBits > OpBits-MidBits) 7197 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7198 } 7199 7200 // fold (sext (truncate x)) -> (sextinreg x). 7201 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7202 N0.getValueType())) { 7203 if (OpBits < DestBits) 7204 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7205 else if (OpBits > DestBits) 7206 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7207 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7208 DAG.getValueType(N0.getValueType())); 7209 } 7210 } 7211 7212 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7213 // Only generate vector extloads when 1) they're legal, and 2) they are 7214 // deemed desirable by the target. 7215 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7216 ((!LegalOperations && !VT.isVector() && 7217 !cast<LoadSDNode>(N0)->isVolatile()) || 7218 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7219 bool DoXform = true; 7220 SmallVector<SDNode*, 4> SetCCs; 7221 if (!N0.hasOneUse()) 7222 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7223 if (VT.isVector()) 7224 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7225 if (DoXform) { 7226 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7227 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7228 LN0->getBasePtr(), N0.getValueType(), 7229 LN0->getMemOperand()); 7230 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7231 N0.getValueType(), ExtLoad); 7232 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7233 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7234 return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked! 7235 } 7236 } 7237 7238 // fold (sext (load x)) to multiple smaller sextloads. 7239 // Only on illegal but splittable vectors. 7240 if (SDValue ExtLoad = CombineExtLoad(N)) 7241 return ExtLoad; 7242 7243 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7244 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7245 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7246 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7247 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7248 EVT MemVT = LN0->getMemoryVT(); 7249 if ((!LegalOperations && !LN0->isVolatile()) || 7250 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7251 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7252 LN0->getBasePtr(), MemVT, 7253 LN0->getMemOperand()); 7254 CombineTo(N, ExtLoad); 7255 CombineTo(N0.getNode(), 7256 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7257 N0.getValueType(), ExtLoad), 7258 ExtLoad.getValue(1)); 7259 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7260 } 7261 } 7262 7263 // fold (sext (and/or/xor (load x), cst)) -> 7264 // (and/or/xor (sextload x), (sext cst)) 7265 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7266 N0.getOpcode() == ISD::XOR) && 7267 isa<LoadSDNode>(N0.getOperand(0)) && 7268 N0.getOperand(1).getOpcode() == ISD::Constant && 7269 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7270 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7271 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7272 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7273 bool DoXform = true; 7274 SmallVector<SDNode*, 4> SetCCs; 7275 if (!N0.hasOneUse()) 7276 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7277 SetCCs, TLI); 7278 if (DoXform) { 7279 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7280 LN0->getChain(), LN0->getBasePtr(), 7281 LN0->getMemoryVT(), 7282 LN0->getMemOperand()); 7283 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7284 Mask = Mask.sext(VT.getSizeInBits()); 7285 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7286 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7287 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7288 SDLoc(N0.getOperand(0)), 7289 N0.getOperand(0).getValueType(), ExtLoad); 7290 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7291 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7292 return CombineTo(N, And); // Return N so it doesn't get rechecked! 7293 } 7294 } 7295 } 7296 7297 if (N0.getOpcode() == ISD::SETCC) { 7298 SDValue N00 = N0.getOperand(0); 7299 SDValue N01 = N0.getOperand(1); 7300 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7301 EVT N00VT = N0.getOperand(0).getValueType(); 7302 7303 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7304 // Only do this before legalize for now. 7305 if (VT.isVector() && !LegalOperations && 7306 TLI.getBooleanContents(N00VT) == 7307 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7308 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7309 // of the same size as the compared operands. Only optimize sext(setcc()) 7310 // if this is the case. 7311 EVT SVT = getSetCCResultType(N00VT); 7312 7313 // We know that the # elements of the results is the same as the 7314 // # elements of the compare (and the # elements of the compare result 7315 // for that matter). Check to see that they are the same size. If so, 7316 // we know that the element size of the sext'd result matches the 7317 // element size of the compare operands. 7318 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7319 return DAG.getSetCC(DL, VT, N00, N01, CC); 7320 7321 // If the desired elements are smaller or larger than the source 7322 // elements, we can use a matching integer vector type and then 7323 // truncate/sign extend. 7324 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7325 if (SVT == MatchingVecType) { 7326 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7327 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7328 } 7329 } 7330 7331 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7332 // Here, T can be 1 or -1, depending on the type of the setcc and 7333 // getBooleanContents(). 7334 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7335 7336 // To determine the "true" side of the select, we need to know the high bit 7337 // of the value returned by the setcc if it evaluates to true. 7338 // If the type of the setcc is i1, then the true case of the select is just 7339 // sext(i1 1), that is, -1. 7340 // If the type of the setcc is larger (say, i8) then the value of the high 7341 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7342 // of the appropriate width. 7343 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7344 : TLI.getConstTrueVal(DAG, VT, DL); 7345 SDValue Zero = DAG.getConstant(0, DL, VT); 7346 if (SDValue SCC = 7347 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7348 return SCC; 7349 7350 if (!VT.isVector()) { 7351 EVT SetCCVT = getSetCCResultType(N00VT); 7352 // Don't do this transform for i1 because there's a select transform 7353 // that would reverse it. 7354 // TODO: We should not do this transform at all without a target hook 7355 // because a sext is likely cheaper than a select? 7356 if (SetCCVT.getScalarSizeInBits() != 1 && 7357 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7358 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7359 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7360 } 7361 } 7362 } 7363 7364 // fold (sext x) -> (zext x) if the sign bit is known zero. 7365 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7366 DAG.SignBitIsZero(N0)) 7367 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7368 7369 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7370 return NewVSel; 7371 7372 return SDValue(); 7373 } 7374 7375 // isTruncateOf - If N is a truncate of some other value, return true, record 7376 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7377 // This function computes KnownBits to avoid a duplicated call to 7378 // computeKnownBits in the caller. 7379 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7380 KnownBits &Known) { 7381 if (N->getOpcode() == ISD::TRUNCATE) { 7382 Op = N->getOperand(0); 7383 DAG.computeKnownBits(Op, Known); 7384 return true; 7385 } 7386 7387 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7388 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7389 return false; 7390 7391 SDValue Op0 = N->getOperand(0); 7392 SDValue Op1 = N->getOperand(1); 7393 assert(Op0.getValueType() == Op1.getValueType()); 7394 7395 if (isNullConstant(Op0)) 7396 Op = Op1; 7397 else if (isNullConstant(Op1)) 7398 Op = Op0; 7399 else 7400 return false; 7401 7402 DAG.computeKnownBits(Op, Known); 7403 7404 if (!(Known.Zero | 1).isAllOnesValue()) 7405 return false; 7406 7407 return true; 7408 } 7409 7410 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7411 SDValue N0 = N->getOperand(0); 7412 EVT VT = N->getValueType(0); 7413 7414 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7415 LegalOperations)) 7416 return SDValue(Res, 0); 7417 7418 // fold (zext (zext x)) -> (zext x) 7419 // fold (zext (aext x)) -> (zext x) 7420 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7421 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7422 N0.getOperand(0)); 7423 7424 // fold (zext (truncate x)) -> (zext x) or 7425 // (zext (truncate x)) -> (truncate x) 7426 // This is valid when the truncated bits of x are already zero. 7427 // FIXME: We should extend this to work for vectors too. 7428 SDValue Op; 7429 KnownBits Known; 7430 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7431 APInt TruncatedBits = 7432 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7433 APInt(Op.getValueSizeInBits(), 0) : 7434 APInt::getBitsSet(Op.getValueSizeInBits(), 7435 N0.getValueSizeInBits(), 7436 std::min(Op.getValueSizeInBits(), 7437 VT.getSizeInBits())); 7438 if (TruncatedBits.isSubsetOf(Known.Zero)) 7439 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7440 } 7441 7442 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7443 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7444 if (N0.getOpcode() == ISD::TRUNCATE) { 7445 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7446 SDNode *oye = N0.getOperand(0).getNode(); 7447 if (NarrowLoad.getNode() != N0.getNode()) { 7448 CombineTo(N0.getNode(), NarrowLoad); 7449 // CombineTo deleted the truncate, if needed, but not what's under it. 7450 AddToWorklist(oye); 7451 } 7452 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7453 } 7454 } 7455 7456 // fold (zext (truncate x)) -> (and x, mask) 7457 if (N0.getOpcode() == ISD::TRUNCATE) { 7458 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7459 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7460 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7461 SDNode *oye = N0.getOperand(0).getNode(); 7462 if (NarrowLoad.getNode() != N0.getNode()) { 7463 CombineTo(N0.getNode(), NarrowLoad); 7464 // CombineTo deleted the truncate, if needed, but not what's under it. 7465 AddToWorklist(oye); 7466 } 7467 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7468 } 7469 7470 EVT SrcVT = N0.getOperand(0).getValueType(); 7471 EVT MinVT = N0.getValueType(); 7472 7473 // Try to mask before the extension to avoid having to generate a larger mask, 7474 // possibly over several sub-vectors. 7475 if (SrcVT.bitsLT(VT)) { 7476 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7477 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7478 SDValue Op = N0.getOperand(0); 7479 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7480 AddToWorklist(Op.getNode()); 7481 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7482 } 7483 } 7484 7485 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7486 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7487 AddToWorklist(Op.getNode()); 7488 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7489 } 7490 } 7491 7492 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7493 // if either of the casts is not free. 7494 if (N0.getOpcode() == ISD::AND && 7495 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7496 N0.getOperand(1).getOpcode() == ISD::Constant && 7497 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7498 N0.getValueType()) || 7499 !TLI.isZExtFree(N0.getValueType(), VT))) { 7500 SDValue X = N0.getOperand(0).getOperand(0); 7501 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7502 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7503 Mask = Mask.zext(VT.getSizeInBits()); 7504 SDLoc DL(N); 7505 return DAG.getNode(ISD::AND, DL, VT, 7506 X, DAG.getConstant(Mask, DL, VT)); 7507 } 7508 7509 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7510 // Only generate vector extloads when 1) they're legal, and 2) they are 7511 // deemed desirable by the target. 7512 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7513 ((!LegalOperations && !VT.isVector() && 7514 !cast<LoadSDNode>(N0)->isVolatile()) || 7515 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7516 bool DoXform = true; 7517 SmallVector<SDNode*, 4> SetCCs; 7518 if (!N0.hasOneUse()) 7519 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7520 if (VT.isVector()) 7521 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7522 if (DoXform) { 7523 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7524 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7525 LN0->getChain(), 7526 LN0->getBasePtr(), N0.getValueType(), 7527 LN0->getMemOperand()); 7528 7529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7530 N0.getValueType(), ExtLoad); 7531 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND); 7532 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7533 return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked! 7534 } 7535 } 7536 7537 // fold (zext (load x)) to multiple smaller zextloads. 7538 // Only on illegal but splittable vectors. 7539 if (SDValue ExtLoad = CombineExtLoad(N)) 7540 return ExtLoad; 7541 7542 // fold (zext (and/or/xor (load x), cst)) -> 7543 // (and/or/xor (zextload x), (zext cst)) 7544 // Unless (and (load x) cst) will match as a zextload already and has 7545 // additional users. 7546 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7547 N0.getOpcode() == ISD::XOR) && 7548 isa<LoadSDNode>(N0.getOperand(0)) && 7549 N0.getOperand(1).getOpcode() == ISD::Constant && 7550 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7551 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7552 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7553 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7554 bool DoXform = true; 7555 SmallVector<SDNode*, 4> SetCCs; 7556 if (!N0.hasOneUse()) { 7557 if (N0.getOpcode() == ISD::AND) { 7558 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7559 auto NarrowLoad = false; 7560 EVT LoadResultTy = AndC->getValueType(0); 7561 EVT ExtVT, LoadedVT; 7562 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7563 NarrowLoad)) 7564 DoXform = false; 7565 } 7566 if (DoXform) 7567 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7568 ISD::ZERO_EXTEND, SetCCs, TLI); 7569 } 7570 if (DoXform) { 7571 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7572 LN0->getChain(), LN0->getBasePtr(), 7573 LN0->getMemoryVT(), 7574 LN0->getMemOperand()); 7575 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7576 Mask = Mask.zext(VT.getSizeInBits()); 7577 SDLoc DL(N); 7578 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7579 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7580 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7581 SDLoc(N0.getOperand(0)), 7582 N0.getOperand(0).getValueType(), ExtLoad); 7583 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND); 7584 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7585 return CombineTo(N, And); // Return N so it doesn't get rechecked! 7586 } 7587 } 7588 } 7589 7590 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7591 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7592 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7593 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7594 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7595 EVT MemVT = LN0->getMemoryVT(); 7596 if ((!LegalOperations && !LN0->isVolatile()) || 7597 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7598 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7599 LN0->getChain(), 7600 LN0->getBasePtr(), MemVT, 7601 LN0->getMemOperand()); 7602 CombineTo(N, ExtLoad); 7603 CombineTo(N0.getNode(), 7604 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7605 ExtLoad), 7606 ExtLoad.getValue(1)); 7607 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7608 } 7609 } 7610 7611 if (N0.getOpcode() == ISD::SETCC) { 7612 // Only do this before legalize for now. 7613 if (!LegalOperations && VT.isVector() && 7614 N0.getValueType().getVectorElementType() == MVT::i1) { 7615 EVT N00VT = N0.getOperand(0).getValueType(); 7616 if (getSetCCResultType(N00VT) == N0.getValueType()) 7617 return SDValue(); 7618 7619 // We know that the # elements of the results is the same as the # 7620 // elements of the compare (and the # elements of the compare result for 7621 // that matter). Check to see that they are the same size. If so, we know 7622 // that the element size of the sext'd result matches the element size of 7623 // the compare operands. 7624 SDLoc DL(N); 7625 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7626 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7627 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7628 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7629 N0.getOperand(1), N0.getOperand(2)); 7630 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7631 } 7632 7633 // If the desired elements are smaller or larger than the source 7634 // elements we can use a matching integer vector type and then 7635 // truncate/sign extend. 7636 EVT MatchingElementType = EVT::getIntegerVT( 7637 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7638 EVT MatchingVectorType = EVT::getVectorVT( 7639 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7640 SDValue VsetCC = 7641 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7642 N0.getOperand(1), N0.getOperand(2)); 7643 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7644 VecOnes); 7645 } 7646 7647 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7648 SDLoc DL(N); 7649 if (SDValue SCC = SimplifySelectCC( 7650 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7651 DAG.getConstant(0, DL, VT), 7652 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7653 return SCC; 7654 } 7655 7656 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7657 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7658 isa<ConstantSDNode>(N0.getOperand(1)) && 7659 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7660 N0.hasOneUse()) { 7661 SDValue ShAmt = N0.getOperand(1); 7662 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7663 if (N0.getOpcode() == ISD::SHL) { 7664 SDValue InnerZExt = N0.getOperand(0); 7665 // If the original shl may be shifting out bits, do not perform this 7666 // transformation. 7667 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7668 InnerZExt.getOperand(0).getValueSizeInBits(); 7669 if (ShAmtVal > KnownZeroBits) 7670 return SDValue(); 7671 } 7672 7673 SDLoc DL(N); 7674 7675 // Ensure that the shift amount is wide enough for the shifted value. 7676 if (VT.getSizeInBits() >= 256) 7677 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7678 7679 return DAG.getNode(N0.getOpcode(), DL, VT, 7680 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7681 ShAmt); 7682 } 7683 7684 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7685 return NewVSel; 7686 7687 return SDValue(); 7688 } 7689 7690 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7691 SDValue N0 = N->getOperand(0); 7692 EVT VT = N->getValueType(0); 7693 7694 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7695 LegalOperations)) 7696 return SDValue(Res, 0); 7697 7698 // fold (aext (aext x)) -> (aext x) 7699 // fold (aext (zext x)) -> (zext x) 7700 // fold (aext (sext x)) -> (sext x) 7701 if (N0.getOpcode() == ISD::ANY_EXTEND || 7702 N0.getOpcode() == ISD::ZERO_EXTEND || 7703 N0.getOpcode() == ISD::SIGN_EXTEND) 7704 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7705 7706 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7707 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7708 if (N0.getOpcode() == ISD::TRUNCATE) { 7709 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7710 SDNode *oye = N0.getOperand(0).getNode(); 7711 if (NarrowLoad.getNode() != N0.getNode()) { 7712 CombineTo(N0.getNode(), NarrowLoad); 7713 // CombineTo deleted the truncate, if needed, but not what's under it. 7714 AddToWorklist(oye); 7715 } 7716 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7717 } 7718 } 7719 7720 // fold (aext (truncate x)) 7721 if (N0.getOpcode() == ISD::TRUNCATE) 7722 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7723 7724 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7725 // if the trunc is not free. 7726 if (N0.getOpcode() == ISD::AND && 7727 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7728 N0.getOperand(1).getOpcode() == ISD::Constant && 7729 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7730 N0.getValueType())) { 7731 SDLoc DL(N); 7732 SDValue X = N0.getOperand(0).getOperand(0); 7733 X = DAG.getAnyExtOrTrunc(X, DL, VT); 7734 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7735 Mask = Mask.zext(VT.getSizeInBits()); 7736 return DAG.getNode(ISD::AND, DL, VT, 7737 X, DAG.getConstant(Mask, DL, VT)); 7738 } 7739 7740 // fold (aext (load x)) -> (aext (truncate (extload x))) 7741 // None of the supported targets knows how to perform load and any_ext 7742 // on vectors in one instruction. We only perform this transformation on 7743 // scalars. 7744 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7745 ISD::isUNINDEXEDLoad(N0.getNode()) && 7746 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7747 bool DoXform = true; 7748 SmallVector<SDNode*, 4> SetCCs; 7749 if (!N0.hasOneUse()) 7750 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7751 if (DoXform) { 7752 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7753 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7754 LN0->getChain(), 7755 LN0->getBasePtr(), N0.getValueType(), 7756 LN0->getMemOperand()); 7757 CombineTo(N, ExtLoad); 7758 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7759 N0.getValueType(), ExtLoad); 7760 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7761 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7762 ISD::ANY_EXTEND); 7763 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7764 } 7765 } 7766 7767 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7768 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7769 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7770 if (N0.getOpcode() == ISD::LOAD && 7771 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7772 N0.hasOneUse()) { 7773 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7774 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7775 EVT MemVT = LN0->getMemoryVT(); 7776 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7777 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7778 VT, LN0->getChain(), LN0->getBasePtr(), 7779 MemVT, LN0->getMemOperand()); 7780 CombineTo(N, ExtLoad); 7781 CombineTo(N0.getNode(), 7782 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7783 N0.getValueType(), ExtLoad), 7784 ExtLoad.getValue(1)); 7785 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7786 } 7787 } 7788 7789 if (N0.getOpcode() == ISD::SETCC) { 7790 // For vectors: 7791 // aext(setcc) -> vsetcc 7792 // aext(setcc) -> truncate(vsetcc) 7793 // aext(setcc) -> aext(vsetcc) 7794 // Only do this before legalize for now. 7795 if (VT.isVector() && !LegalOperations) { 7796 EVT N0VT = N0.getOperand(0).getValueType(); 7797 // We know that the # elements of the results is the same as the 7798 // # elements of the compare (and the # elements of the compare result 7799 // for that matter). Check to see that they are the same size. If so, 7800 // we know that the element size of the sext'd result matches the 7801 // element size of the compare operands. 7802 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7803 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7804 N0.getOperand(1), 7805 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7806 // If the desired elements are smaller or larger than the source 7807 // elements we can use a matching integer vector type and then 7808 // truncate/any extend 7809 else { 7810 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7811 SDValue VsetCC = 7812 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7813 N0.getOperand(1), 7814 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7815 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7816 } 7817 } 7818 7819 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7820 SDLoc DL(N); 7821 if (SDValue SCC = SimplifySelectCC( 7822 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7823 DAG.getConstant(0, DL, VT), 7824 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7825 return SCC; 7826 } 7827 7828 return SDValue(); 7829 } 7830 7831 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7832 SDValue N0 = N->getOperand(0); 7833 SDValue N1 = N->getOperand(1); 7834 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7835 7836 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7837 if (N0.getOpcode() == ISD::AssertZext && 7838 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7839 return N0; 7840 7841 return SDValue(); 7842 } 7843 7844 /// See if the specified operand can be simplified with the knowledge that only 7845 /// the bits specified by Mask are used. If so, return the simpler operand, 7846 /// otherwise return a null SDValue. 7847 /// 7848 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can 7849 /// simplify nodes with multiple uses more aggressively.) 7850 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7851 switch (V.getOpcode()) { 7852 default: break; 7853 case ISD::Constant: { 7854 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7855 assert(CV && "Const value should be ConstSDNode."); 7856 const APInt &CVal = CV->getAPIntValue(); 7857 APInt NewVal = CVal & Mask; 7858 if (NewVal != CVal) 7859 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7860 break; 7861 } 7862 case ISD::OR: 7863 case ISD::XOR: 7864 // If the LHS or RHS don't contribute bits to the or, drop them. 7865 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7866 return V.getOperand(1); 7867 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7868 return V.getOperand(0); 7869 break; 7870 case ISD::SRL: 7871 // Only look at single-use SRLs. 7872 if (!V.getNode()->hasOneUse()) 7873 break; 7874 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7875 // See if we can recursively simplify the LHS. 7876 unsigned Amt = RHSC->getZExtValue(); 7877 7878 // Watch out for shift count overflow though. 7879 if (Amt >= Mask.getBitWidth()) break; 7880 APInt NewMask = Mask << Amt; 7881 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7882 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7883 SimplifyLHS, V.getOperand(1)); 7884 } 7885 break; 7886 case ISD::AND: { 7887 // X & -1 -> X (ignoring bits which aren't demanded). 7888 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1)); 7889 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask) 7890 return V.getOperand(0); 7891 break; 7892 } 7893 } 7894 return SDValue(); 7895 } 7896 7897 /// If the result of a wider load is shifted to right of N bits and then 7898 /// truncated to a narrower type and where N is a multiple of number of bits of 7899 /// the narrower type, transform it to a narrower load from address + N / num of 7900 /// bits of new type. If the result is to be extended, also fold the extension 7901 /// to form a extending load. 7902 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7903 unsigned Opc = N->getOpcode(); 7904 7905 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7906 SDValue N0 = N->getOperand(0); 7907 EVT VT = N->getValueType(0); 7908 EVT ExtVT = VT; 7909 7910 // This transformation isn't valid for vector loads. 7911 if (VT.isVector()) 7912 return SDValue(); 7913 7914 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7915 // extended to VT. 7916 if (Opc == ISD::SIGN_EXTEND_INREG) { 7917 ExtType = ISD::SEXTLOAD; 7918 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7919 } else if (Opc == ISD::SRL) { 7920 // Another special-case: SRL is basically zero-extending a narrower value. 7921 ExtType = ISD::ZEXTLOAD; 7922 N0 = SDValue(N, 0); 7923 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7924 if (!N01) return SDValue(); 7925 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7926 VT.getSizeInBits() - N01->getZExtValue()); 7927 } 7928 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7929 return SDValue(); 7930 7931 unsigned EVTBits = ExtVT.getSizeInBits(); 7932 7933 // Do not generate loads of non-round integer types since these can 7934 // be expensive (and would be wrong if the type is not byte sized). 7935 if (!ExtVT.isRound()) 7936 return SDValue(); 7937 7938 unsigned ShAmt = 0; 7939 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7940 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7941 ShAmt = N01->getZExtValue(); 7942 // Is the shift amount a multiple of size of VT? 7943 if ((ShAmt & (EVTBits-1)) == 0) { 7944 N0 = N0.getOperand(0); 7945 // Is the load width a multiple of size of VT? 7946 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7947 return SDValue(); 7948 } 7949 7950 // At this point, we must have a load or else we can't do the transform. 7951 if (!isa<LoadSDNode>(N0)) return SDValue(); 7952 7953 // Because a SRL must be assumed to *need* to zero-extend the high bits 7954 // (as opposed to anyext the high bits), we can't combine the zextload 7955 // lowering of SRL and an sextload. 7956 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7957 return SDValue(); 7958 7959 // If the shift amount is larger than the input type then we're not 7960 // accessing any of the loaded bytes. If the load was a zextload/extload 7961 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7962 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7963 return SDValue(); 7964 } 7965 } 7966 7967 // If the load is shifted left (and the result isn't shifted back right), 7968 // we can fold the truncate through the shift. 7969 unsigned ShLeftAmt = 0; 7970 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7971 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7972 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7973 ShLeftAmt = N01->getZExtValue(); 7974 N0 = N0.getOperand(0); 7975 } 7976 } 7977 7978 // If we haven't found a load, we can't narrow it. Don't transform one with 7979 // multiple uses, this would require adding a new load. 7980 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7981 return SDValue(); 7982 7983 // Don't change the width of a volatile load. 7984 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7985 if (LN0->isVolatile()) 7986 return SDValue(); 7987 7988 // Verify that we are actually reducing a load width here. 7989 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7990 return SDValue(); 7991 7992 // For the transform to be legal, the load must produce only two values 7993 // (the value loaded and the chain). Don't transform a pre-increment 7994 // load, for example, which produces an extra value. Otherwise the 7995 // transformation is not equivalent, and the downstream logic to replace 7996 // uses gets things wrong. 7997 if (LN0->getNumValues() > 2) 7998 return SDValue(); 7999 8000 // If the load that we're shrinking is an extload and we're not just 8001 // discarding the extension we can't simply shrink the load. Bail. 8002 // TODO: It would be possible to merge the extensions in some cases. 8003 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 8004 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 8005 return SDValue(); 8006 8007 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 8008 return SDValue(); 8009 8010 EVT PtrType = N0.getOperand(1).getValueType(); 8011 8012 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8013 // It's not possible to generate a constant of extended or untyped type. 8014 return SDValue(); 8015 8016 // For big endian targets, we need to adjust the offset to the pointer to 8017 // load the correct bytes. 8018 if (DAG.getDataLayout().isBigEndian()) { 8019 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 8020 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 8021 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 8022 } 8023 8024 uint64_t PtrOff = ShAmt / 8; 8025 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 8026 SDLoc DL(LN0); 8027 // The original load itself didn't wrap, so an offset within it doesn't. 8028 SDNodeFlags Flags; 8029 Flags.setNoUnsignedWrap(true); 8030 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 8031 PtrType, LN0->getBasePtr(), 8032 DAG.getConstant(PtrOff, DL, PtrType), 8033 Flags); 8034 AddToWorklist(NewPtr.getNode()); 8035 8036 SDValue Load; 8037 if (ExtType == ISD::NON_EXTLOAD) 8038 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8039 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8040 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8041 else 8042 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8043 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8044 NewAlign, LN0->getMemOperand()->getFlags(), 8045 LN0->getAAInfo()); 8046 8047 // Replace the old load's chain with the new load's chain. 8048 WorklistRemover DeadNodes(*this); 8049 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8050 8051 // Shift the result left, if we've swallowed a left shift. 8052 SDValue Result = Load; 8053 if (ShLeftAmt != 0) { 8054 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8055 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8056 ShImmTy = VT; 8057 // If the shift amount is as large as the result size (but, presumably, 8058 // no larger than the source) then the useful bits of the result are 8059 // zero; we can't simply return the shortened shift, because the result 8060 // of that operation is undefined. 8061 SDLoc DL(N0); 8062 if (ShLeftAmt >= VT.getSizeInBits()) 8063 Result = DAG.getConstant(0, DL, VT); 8064 else 8065 Result = DAG.getNode(ISD::SHL, DL, VT, 8066 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8067 } 8068 8069 // Return the new loaded value. 8070 return Result; 8071 } 8072 8073 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8074 SDValue N0 = N->getOperand(0); 8075 SDValue N1 = N->getOperand(1); 8076 EVT VT = N->getValueType(0); 8077 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8078 unsigned VTBits = VT.getScalarSizeInBits(); 8079 unsigned EVTBits = EVT.getScalarSizeInBits(); 8080 8081 if (N0.isUndef()) 8082 return DAG.getUNDEF(VT); 8083 8084 // fold (sext_in_reg c1) -> c1 8085 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8086 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8087 8088 // If the input is already sign extended, just drop the extension. 8089 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8090 return N0; 8091 8092 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8093 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8094 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8095 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8096 N0.getOperand(0), N1); 8097 8098 // fold (sext_in_reg (sext x)) -> (sext x) 8099 // fold (sext_in_reg (aext x)) -> (sext x) 8100 // if x is small enough. 8101 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8102 SDValue N00 = N0.getOperand(0); 8103 if (N00.getScalarValueSizeInBits() <= EVTBits && 8104 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8105 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8106 } 8107 8108 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8109 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8110 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8111 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8112 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8113 if (!LegalOperations || 8114 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8115 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8116 } 8117 8118 // fold (sext_in_reg (zext x)) -> (sext x) 8119 // iff we are extending the source sign bit. 8120 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8121 SDValue N00 = N0.getOperand(0); 8122 if (N00.getScalarValueSizeInBits() == EVTBits && 8123 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8124 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8125 } 8126 8127 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8128 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8129 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8130 8131 // fold operands of sext_in_reg based on knowledge that the top bits are not 8132 // demanded. 8133 if (SimplifyDemandedBits(SDValue(N, 0))) 8134 return SDValue(N, 0); 8135 8136 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8137 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8138 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8139 return NarrowLoad; 8140 8141 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8142 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8143 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8144 if (N0.getOpcode() == ISD::SRL) { 8145 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8146 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8147 // We can turn this into an SRA iff the input to the SRL is already sign 8148 // extended enough. 8149 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8150 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8151 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8152 N0.getOperand(0), N0.getOperand(1)); 8153 } 8154 } 8155 8156 // fold (sext_inreg (extload x)) -> (sextload x) 8157 if (ISD::isEXTLoad(N0.getNode()) && 8158 ISD::isUNINDEXEDLoad(N0.getNode()) && 8159 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8160 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8161 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8162 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8163 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8164 LN0->getChain(), 8165 LN0->getBasePtr(), EVT, 8166 LN0->getMemOperand()); 8167 CombineTo(N, ExtLoad); 8168 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8169 AddToWorklist(ExtLoad.getNode()); 8170 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8171 } 8172 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8173 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8174 N0.hasOneUse() && 8175 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8176 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8177 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8178 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8179 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8180 LN0->getChain(), 8181 LN0->getBasePtr(), EVT, 8182 LN0->getMemOperand()); 8183 CombineTo(N, ExtLoad); 8184 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8185 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8186 } 8187 8188 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8189 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8190 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8191 N0.getOperand(1), false)) 8192 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8193 BSwap, N1); 8194 } 8195 8196 return SDValue(); 8197 } 8198 8199 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8200 SDValue N0 = N->getOperand(0); 8201 EVT VT = N->getValueType(0); 8202 8203 if (N0.isUndef()) 8204 return DAG.getUNDEF(VT); 8205 8206 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8207 LegalOperations)) 8208 return SDValue(Res, 0); 8209 8210 return SDValue(); 8211 } 8212 8213 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8214 SDValue N0 = N->getOperand(0); 8215 EVT VT = N->getValueType(0); 8216 8217 if (N0.isUndef()) 8218 return DAG.getUNDEF(VT); 8219 8220 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8221 LegalOperations)) 8222 return SDValue(Res, 0); 8223 8224 return SDValue(); 8225 } 8226 8227 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8228 SDValue N0 = N->getOperand(0); 8229 EVT VT = N->getValueType(0); 8230 bool isLE = DAG.getDataLayout().isLittleEndian(); 8231 8232 // noop truncate 8233 if (N0.getValueType() == N->getValueType(0)) 8234 return N0; 8235 // fold (truncate c1) -> c1 8236 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8237 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8238 // fold (truncate (truncate x)) -> (truncate x) 8239 if (N0.getOpcode() == ISD::TRUNCATE) 8240 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8241 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8242 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8243 N0.getOpcode() == ISD::SIGN_EXTEND || 8244 N0.getOpcode() == ISD::ANY_EXTEND) { 8245 // if the source is smaller than the dest, we still need an extend. 8246 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8247 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8248 // if the source is larger than the dest, than we just need the truncate. 8249 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8250 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8251 // if the source and dest are the same type, we can drop both the extend 8252 // and the truncate. 8253 return N0.getOperand(0); 8254 } 8255 8256 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8257 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8258 return SDValue(); 8259 8260 // Fold extract-and-trunc into a narrow extract. For example: 8261 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8262 // i32 y = TRUNCATE(i64 x) 8263 // -- becomes -- 8264 // v16i8 b = BITCAST (v2i64 val) 8265 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8266 // 8267 // Note: We only run this optimization after type legalization (which often 8268 // creates this pattern) and before operation legalization after which 8269 // we need to be more careful about the vector instructions that we generate. 8270 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8271 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8272 8273 EVT VecTy = N0.getOperand(0).getValueType(); 8274 EVT ExTy = N0.getValueType(); 8275 EVT TrTy = N->getValueType(0); 8276 8277 unsigned NumElem = VecTy.getVectorNumElements(); 8278 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8279 8280 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8281 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8282 8283 SDValue EltNo = N0->getOperand(1); 8284 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8285 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8286 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8287 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8288 8289 SDLoc DL(N); 8290 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8291 DAG.getBitcast(NVT, N0.getOperand(0)), 8292 DAG.getConstant(Index, DL, IndexTy)); 8293 } 8294 } 8295 8296 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8297 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8298 EVT SrcVT = N0.getValueType(); 8299 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8300 TLI.isTruncateFree(SrcVT, VT)) { 8301 SDLoc SL(N0); 8302 SDValue Cond = N0.getOperand(0); 8303 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8304 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8305 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8306 } 8307 } 8308 8309 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8310 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8311 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8312 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8313 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 8314 uint64_t Amt = CAmt->getZExtValue(); 8315 unsigned Size = VT.getScalarSizeInBits(); 8316 8317 if (Amt < Size) { 8318 SDLoc SL(N); 8319 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8320 8321 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8322 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 8323 DAG.getConstant(Amt, SL, AmtVT)); 8324 } 8325 } 8326 } 8327 8328 // Fold a series of buildvector, bitcast, and truncate if possible. 8329 // For example fold 8330 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8331 // (2xi32 (buildvector x, y)). 8332 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8333 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8334 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8335 N0.getOperand(0).hasOneUse()) { 8336 8337 SDValue BuildVect = N0.getOperand(0); 8338 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8339 EVT TruncVecEltTy = VT.getVectorElementType(); 8340 8341 // Check that the element types match. 8342 if (BuildVectEltTy == TruncVecEltTy) { 8343 // Now we only need to compute the offset of the truncated elements. 8344 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8345 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8346 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8347 8348 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8349 "Invalid number of elements"); 8350 8351 SmallVector<SDValue, 8> Opnds; 8352 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8353 Opnds.push_back(BuildVect.getOperand(i)); 8354 8355 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8356 } 8357 } 8358 8359 // See if we can simplify the input to this truncate through knowledge that 8360 // only the low bits are being used. 8361 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8362 // Currently we only perform this optimization on scalars because vectors 8363 // may have different active low bits. 8364 if (!VT.isVector()) { 8365 if (SDValue Shorter = 8366 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 8367 VT.getSizeInBits()))) 8368 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8369 } 8370 8371 // fold (truncate (load x)) -> (smaller load x) 8372 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8373 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8374 if (SDValue Reduced = ReduceLoadWidth(N)) 8375 return Reduced; 8376 8377 // Handle the case where the load remains an extending load even 8378 // after truncation. 8379 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8380 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8381 if (!LN0->isVolatile() && 8382 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8383 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8384 VT, LN0->getChain(), LN0->getBasePtr(), 8385 LN0->getMemoryVT(), 8386 LN0->getMemOperand()); 8387 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8388 return NewLoad; 8389 } 8390 } 8391 } 8392 8393 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8394 // where ... are all 'undef'. 8395 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8396 SmallVector<EVT, 8> VTs; 8397 SDValue V; 8398 unsigned Idx = 0; 8399 unsigned NumDefs = 0; 8400 8401 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8402 SDValue X = N0.getOperand(i); 8403 if (!X.isUndef()) { 8404 V = X; 8405 Idx = i; 8406 NumDefs++; 8407 } 8408 // Stop if more than one members are non-undef. 8409 if (NumDefs > 1) 8410 break; 8411 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8412 VT.getVectorElementType(), 8413 X.getValueType().getVectorNumElements())); 8414 } 8415 8416 if (NumDefs == 0) 8417 return DAG.getUNDEF(VT); 8418 8419 if (NumDefs == 1) { 8420 assert(V.getNode() && "The single defined operand is empty!"); 8421 SmallVector<SDValue, 8> Opnds; 8422 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8423 if (i != Idx) { 8424 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8425 continue; 8426 } 8427 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8428 AddToWorklist(NV.getNode()); 8429 Opnds.push_back(NV); 8430 } 8431 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8432 } 8433 } 8434 8435 // Fold truncate of a bitcast of a vector to an extract of the low vector 8436 // element. 8437 // 8438 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8439 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8440 SDValue VecSrc = N0.getOperand(0); 8441 EVT SrcVT = VecSrc.getValueType(); 8442 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8443 (!LegalOperations || 8444 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8445 SDLoc SL(N); 8446 8447 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8448 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8449 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8450 } 8451 } 8452 8453 // Simplify the operands using demanded-bits information. 8454 if (!VT.isVector() && 8455 SimplifyDemandedBits(SDValue(N, 0))) 8456 return SDValue(N, 0); 8457 8458 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8459 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8460 // When the adde's carry is not used. 8461 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8462 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8463 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8464 SDLoc SL(N); 8465 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8466 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8467 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8468 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8469 } 8470 8471 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8472 return NewVSel; 8473 8474 return SDValue(); 8475 } 8476 8477 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8478 SDValue Elt = N->getOperand(i); 8479 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8480 return Elt.getNode(); 8481 return Elt.getOperand(Elt.getResNo()).getNode(); 8482 } 8483 8484 /// build_pair (load, load) -> load 8485 /// if load locations are consecutive. 8486 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8487 assert(N->getOpcode() == ISD::BUILD_PAIR); 8488 8489 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8490 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8491 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8492 LD1->getAddressSpace() != LD2->getAddressSpace()) 8493 return SDValue(); 8494 EVT LD1VT = LD1->getValueType(0); 8495 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8496 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8497 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8498 unsigned Align = LD1->getAlignment(); 8499 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8500 VT.getTypeForEVT(*DAG.getContext())); 8501 8502 if (NewAlign <= Align && 8503 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8504 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8505 LD1->getPointerInfo(), Align); 8506 } 8507 8508 return SDValue(); 8509 } 8510 8511 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8512 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8513 // and Lo parts; on big-endian machines it doesn't. 8514 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8515 } 8516 8517 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8518 const TargetLowering &TLI) { 8519 // If this is not a bitcast to an FP type or if the target doesn't have 8520 // IEEE754-compliant FP logic, we're done. 8521 EVT VT = N->getValueType(0); 8522 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8523 return SDValue(); 8524 8525 // TODO: Use splat values for the constant-checking below and remove this 8526 // restriction. 8527 SDValue N0 = N->getOperand(0); 8528 EVT SourceVT = N0.getValueType(); 8529 if (SourceVT.isVector()) 8530 return SDValue(); 8531 8532 unsigned FPOpcode; 8533 APInt SignMask; 8534 switch (N0.getOpcode()) { 8535 case ISD::AND: 8536 FPOpcode = ISD::FABS; 8537 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8538 break; 8539 case ISD::XOR: 8540 FPOpcode = ISD::FNEG; 8541 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8542 break; 8543 // TODO: ISD::OR --> ISD::FNABS? 8544 default: 8545 return SDValue(); 8546 } 8547 8548 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8549 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8550 SDValue LogicOp0 = N0.getOperand(0); 8551 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8552 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8553 LogicOp0.getOpcode() == ISD::BITCAST && 8554 LogicOp0->getOperand(0).getValueType() == VT) 8555 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8556 8557 return SDValue(); 8558 } 8559 8560 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8561 SDValue N0 = N->getOperand(0); 8562 EVT VT = N->getValueType(0); 8563 8564 if (N0.isUndef()) 8565 return DAG.getUNDEF(VT); 8566 8567 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8568 // Only do this before legalize, since afterward the target may be depending 8569 // on the bitconvert. 8570 // First check to see if this is all constant. 8571 if (!LegalTypes && 8572 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8573 VT.isVector()) { 8574 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8575 8576 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8577 assert(!DestEltVT.isVector() && 8578 "Element type of vector ValueType must not be vector!"); 8579 if (isSimple) 8580 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8581 } 8582 8583 // If the input is a constant, let getNode fold it. 8584 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8585 // If we can't allow illegal operations, we need to check that this is just 8586 // a fp -> int or int -> conversion and that the resulting operation will 8587 // be legal. 8588 if (!LegalOperations || 8589 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8590 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8591 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8592 TLI.isOperationLegal(ISD::Constant, VT))) 8593 return DAG.getBitcast(VT, N0); 8594 } 8595 8596 // (conv (conv x, t1), t2) -> (conv x, t2) 8597 if (N0.getOpcode() == ISD::BITCAST) 8598 return DAG.getBitcast(VT, N0.getOperand(0)); 8599 8600 // fold (conv (load x)) -> (load (conv*)x) 8601 // If the resultant load doesn't need a higher alignment than the original! 8602 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8603 // Do not change the width of a volatile load. 8604 !cast<LoadSDNode>(N0)->isVolatile() && 8605 // Do not remove the cast if the types differ in endian layout. 8606 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8607 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8608 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8609 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8610 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8611 unsigned OrigAlign = LN0->getAlignment(); 8612 8613 bool Fast = false; 8614 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8615 LN0->getAddressSpace(), OrigAlign, &Fast) && 8616 Fast) { 8617 SDValue Load = 8618 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8619 LN0->getPointerInfo(), OrigAlign, 8620 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8621 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8622 return Load; 8623 } 8624 } 8625 8626 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8627 return V; 8628 8629 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8630 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8631 // 8632 // For ppc_fp128: 8633 // fold (bitcast (fneg x)) -> 8634 // flipbit = signbit 8635 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8636 // 8637 // fold (bitcast (fabs x)) -> 8638 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8639 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8640 // This often reduces constant pool loads. 8641 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8642 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8643 N0.getNode()->hasOneUse() && VT.isInteger() && 8644 !VT.isVector() && !N0.getValueType().isVector()) { 8645 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8646 AddToWorklist(NewConv.getNode()); 8647 8648 SDLoc DL(N); 8649 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8650 assert(VT.getSizeInBits() == 128); 8651 SDValue SignBit = DAG.getConstant( 8652 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8653 SDValue FlipBit; 8654 if (N0.getOpcode() == ISD::FNEG) { 8655 FlipBit = SignBit; 8656 AddToWorklist(FlipBit.getNode()); 8657 } else { 8658 assert(N0.getOpcode() == ISD::FABS); 8659 SDValue Hi = 8660 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8661 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8662 SDLoc(NewConv))); 8663 AddToWorklist(Hi.getNode()); 8664 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8665 AddToWorklist(FlipBit.getNode()); 8666 } 8667 SDValue FlipBits = 8668 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8669 AddToWorklist(FlipBits.getNode()); 8670 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8671 } 8672 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8673 if (N0.getOpcode() == ISD::FNEG) 8674 return DAG.getNode(ISD::XOR, DL, VT, 8675 NewConv, DAG.getConstant(SignBit, DL, VT)); 8676 assert(N0.getOpcode() == ISD::FABS); 8677 return DAG.getNode(ISD::AND, DL, VT, 8678 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8679 } 8680 8681 // fold (bitconvert (fcopysign cst, x)) -> 8682 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8683 // Note that we don't handle (copysign x, cst) because this can always be 8684 // folded to an fneg or fabs. 8685 // 8686 // For ppc_fp128: 8687 // fold (bitcast (fcopysign cst, x)) -> 8688 // flipbit = (and (extract_element 8689 // (xor (bitcast cst), (bitcast x)), 0), 8690 // signbit) 8691 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8692 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8693 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8694 VT.isInteger() && !VT.isVector()) { 8695 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8696 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8697 if (isTypeLegal(IntXVT)) { 8698 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8699 AddToWorklist(X.getNode()); 8700 8701 // If X has a different width than the result/lhs, sext it or truncate it. 8702 unsigned VTWidth = VT.getSizeInBits(); 8703 if (OrigXWidth < VTWidth) { 8704 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8705 AddToWorklist(X.getNode()); 8706 } else if (OrigXWidth > VTWidth) { 8707 // To get the sign bit in the right place, we have to shift it right 8708 // before truncating. 8709 SDLoc DL(X); 8710 X = DAG.getNode(ISD::SRL, DL, 8711 X.getValueType(), X, 8712 DAG.getConstant(OrigXWidth-VTWidth, DL, 8713 X.getValueType())); 8714 AddToWorklist(X.getNode()); 8715 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8716 AddToWorklist(X.getNode()); 8717 } 8718 8719 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8720 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 8721 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8722 AddToWorklist(Cst.getNode()); 8723 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8724 AddToWorklist(X.getNode()); 8725 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8726 AddToWorklist(XorResult.getNode()); 8727 SDValue XorResult64 = DAG.getNode( 8728 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8729 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8730 SDLoc(XorResult))); 8731 AddToWorklist(XorResult64.getNode()); 8732 SDValue FlipBit = 8733 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8734 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8735 AddToWorklist(FlipBit.getNode()); 8736 SDValue FlipBits = 8737 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8738 AddToWorklist(FlipBits.getNode()); 8739 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8740 } 8741 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8742 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8743 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8744 AddToWorklist(X.getNode()); 8745 8746 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8747 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8748 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8749 AddToWorklist(Cst.getNode()); 8750 8751 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8752 } 8753 } 8754 8755 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8756 if (N0.getOpcode() == ISD::BUILD_PAIR) 8757 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8758 return CombineLD; 8759 8760 // Remove double bitcasts from shuffles - this is often a legacy of 8761 // XformToShuffleWithZero being used to combine bitmaskings (of 8762 // float vectors bitcast to integer vectors) into shuffles. 8763 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8764 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8765 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8766 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8767 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8768 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8769 8770 // If operands are a bitcast, peek through if it casts the original VT. 8771 // If operands are a constant, just bitcast back to original VT. 8772 auto PeekThroughBitcast = [&](SDValue Op) { 8773 if (Op.getOpcode() == ISD::BITCAST && 8774 Op.getOperand(0).getValueType() == VT) 8775 return SDValue(Op.getOperand(0)); 8776 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8777 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8778 return DAG.getBitcast(VT, Op); 8779 return SDValue(); 8780 }; 8781 8782 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8783 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8784 if (!(SV0 && SV1)) 8785 return SDValue(); 8786 8787 int MaskScale = 8788 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8789 SmallVector<int, 8> NewMask; 8790 for (int M : SVN->getMask()) 8791 for (int i = 0; i != MaskScale; ++i) 8792 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8793 8794 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8795 if (!LegalMask) { 8796 std::swap(SV0, SV1); 8797 ShuffleVectorSDNode::commuteMask(NewMask); 8798 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8799 } 8800 8801 if (LegalMask) 8802 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8803 } 8804 8805 return SDValue(); 8806 } 8807 8808 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8809 EVT VT = N->getValueType(0); 8810 return CombineConsecutiveLoads(N, VT); 8811 } 8812 8813 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8814 /// operands. DstEltVT indicates the destination element value type. 8815 SDValue DAGCombiner:: 8816 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8817 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8818 8819 // If this is already the right type, we're done. 8820 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8821 8822 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8823 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8824 8825 // If this is a conversion of N elements of one type to N elements of another 8826 // type, convert each element. This handles FP<->INT cases. 8827 if (SrcBitSize == DstBitSize) { 8828 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8829 BV->getValueType(0).getVectorNumElements()); 8830 8831 // Due to the FP element handling below calling this routine recursively, 8832 // we can end up with a scalar-to-vector node here. 8833 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8834 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8835 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8836 8837 SmallVector<SDValue, 8> Ops; 8838 for (SDValue Op : BV->op_values()) { 8839 // If the vector element type is not legal, the BUILD_VECTOR operands 8840 // are promoted and implicitly truncated. Make that explicit here. 8841 if (Op.getValueType() != SrcEltVT) 8842 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8843 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8844 AddToWorklist(Ops.back().getNode()); 8845 } 8846 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8847 } 8848 8849 // Otherwise, we're growing or shrinking the elements. To avoid having to 8850 // handle annoying details of growing/shrinking FP values, we convert them to 8851 // int first. 8852 if (SrcEltVT.isFloatingPoint()) { 8853 // Convert the input float vector to a int vector where the elements are the 8854 // same sizes. 8855 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8856 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8857 SrcEltVT = IntVT; 8858 } 8859 8860 // Now we know the input is an integer vector. If the output is a FP type, 8861 // convert to integer first, then to FP of the right size. 8862 if (DstEltVT.isFloatingPoint()) { 8863 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8864 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8865 8866 // Next, convert to FP elements of the same size. 8867 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8868 } 8869 8870 SDLoc DL(BV); 8871 8872 // Okay, we know the src/dst types are both integers of differing types. 8873 // Handling growing first. 8874 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8875 if (SrcBitSize < DstBitSize) { 8876 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8877 8878 SmallVector<SDValue, 8> Ops; 8879 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8880 i += NumInputsPerOutput) { 8881 bool isLE = DAG.getDataLayout().isLittleEndian(); 8882 APInt NewBits = APInt(DstBitSize, 0); 8883 bool EltIsUndef = true; 8884 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8885 // Shift the previously computed bits over. 8886 NewBits <<= SrcBitSize; 8887 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8888 if (Op.isUndef()) continue; 8889 EltIsUndef = false; 8890 8891 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8892 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8893 } 8894 8895 if (EltIsUndef) 8896 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8897 else 8898 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8899 } 8900 8901 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8902 return DAG.getBuildVector(VT, DL, Ops); 8903 } 8904 8905 // Finally, this must be the case where we are shrinking elements: each input 8906 // turns into multiple outputs. 8907 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8908 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8909 NumOutputsPerInput*BV->getNumOperands()); 8910 SmallVector<SDValue, 8> Ops; 8911 8912 for (const SDValue &Op : BV->op_values()) { 8913 if (Op.isUndef()) { 8914 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8915 continue; 8916 } 8917 8918 APInt OpVal = cast<ConstantSDNode>(Op)-> 8919 getAPIntValue().zextOrTrunc(SrcBitSize); 8920 8921 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8922 APInt ThisVal = OpVal.trunc(DstBitSize); 8923 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8924 OpVal.lshrInPlace(DstBitSize); 8925 } 8926 8927 // For big endian targets, swap the order of the pieces of each element. 8928 if (DAG.getDataLayout().isBigEndian()) 8929 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8930 } 8931 8932 return DAG.getBuildVector(VT, DL, Ops); 8933 } 8934 8935 static bool isContractable(SDNode *N) { 8936 SDNodeFlags F = N->getFlags(); 8937 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 8938 } 8939 8940 /// Try to perform FMA combining on a given FADD node. 8941 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8942 SDValue N0 = N->getOperand(0); 8943 SDValue N1 = N->getOperand(1); 8944 EVT VT = N->getValueType(0); 8945 SDLoc SL(N); 8946 8947 const TargetOptions &Options = DAG.getTarget().Options; 8948 8949 // Floating-point multiply-add with intermediate rounding. 8950 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8951 8952 // Floating-point multiply-add without intermediate rounding. 8953 bool HasFMA = 8954 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8955 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8956 8957 // No valid opcode, do not combine. 8958 if (!HasFMAD && !HasFMA) 8959 return SDValue(); 8960 8961 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 8962 Options.UnsafeFPMath || HasFMAD); 8963 // If the addition is not contractable, do not combine. 8964 if (!AllowFusionGlobally && !isContractable(N)) 8965 return SDValue(); 8966 8967 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8968 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8969 return SDValue(); 8970 8971 // Always prefer FMAD to FMA for precision. 8972 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8973 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8974 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8975 8976 // Is the node an FMUL and contractable either due to global flags or 8977 // SDNodeFlags. 8978 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 8979 if (N.getOpcode() != ISD::FMUL) 8980 return false; 8981 return AllowFusionGlobally || isContractable(N.getNode()); 8982 }; 8983 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8984 // prefer to fold the multiply with fewer uses. 8985 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 8986 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8987 std::swap(N0, N1); 8988 } 8989 8990 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 8991 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 8992 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8993 N0.getOperand(0), N0.getOperand(1), N1); 8994 } 8995 8996 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8997 // Note: Commutes FADD operands. 8998 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 8999 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9000 N1.getOperand(0), N1.getOperand(1), N0); 9001 } 9002 9003 // Look through FP_EXTEND nodes to do more combining. 9004 if (LookThroughFPExt) { 9005 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 9006 if (N0.getOpcode() == ISD::FP_EXTEND) { 9007 SDValue N00 = N0.getOperand(0); 9008 if (isContractableFMUL(N00)) 9009 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9010 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9011 N00.getOperand(0)), 9012 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9013 N00.getOperand(1)), N1); 9014 } 9015 9016 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 9017 // Note: Commutes FADD operands. 9018 if (N1.getOpcode() == ISD::FP_EXTEND) { 9019 SDValue N10 = N1.getOperand(0); 9020 if (isContractableFMUL(N10)) 9021 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9022 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9023 N10.getOperand(0)), 9024 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9025 N10.getOperand(1)), N0); 9026 } 9027 } 9028 9029 // More folding opportunities when target permits. 9030 if (Aggressive) { 9031 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 9032 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9033 // are currently only supported on binary nodes. 9034 if (Options.UnsafeFPMath && 9035 N0.getOpcode() == PreferredFusedOpcode && 9036 N0.getOperand(2).getOpcode() == ISD::FMUL && 9037 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 9038 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9039 N0.getOperand(0), N0.getOperand(1), 9040 DAG.getNode(PreferredFusedOpcode, SL, VT, 9041 N0.getOperand(2).getOperand(0), 9042 N0.getOperand(2).getOperand(1), 9043 N1)); 9044 } 9045 9046 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9047 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9048 // are currently only supported on binary nodes. 9049 if (Options.UnsafeFPMath && 9050 N1->getOpcode() == PreferredFusedOpcode && 9051 N1.getOperand(2).getOpcode() == ISD::FMUL && 9052 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9053 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9054 N1.getOperand(0), N1.getOperand(1), 9055 DAG.getNode(PreferredFusedOpcode, SL, VT, 9056 N1.getOperand(2).getOperand(0), 9057 N1.getOperand(2).getOperand(1), 9058 N0)); 9059 } 9060 9061 if (LookThroughFPExt) { 9062 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9063 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9064 auto FoldFAddFMAFPExtFMul = [&] ( 9065 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9066 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9067 DAG.getNode(PreferredFusedOpcode, SL, VT, 9068 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9069 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9070 Z)); 9071 }; 9072 if (N0.getOpcode() == PreferredFusedOpcode) { 9073 SDValue N02 = N0.getOperand(2); 9074 if (N02.getOpcode() == ISD::FP_EXTEND) { 9075 SDValue N020 = N02.getOperand(0); 9076 if (isContractableFMUL(N020)) 9077 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9078 N020.getOperand(0), N020.getOperand(1), 9079 N1); 9080 } 9081 } 9082 9083 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9084 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9085 // FIXME: This turns two single-precision and one double-precision 9086 // operation into two double-precision operations, which might not be 9087 // interesting for all targets, especially GPUs. 9088 auto FoldFAddFPExtFMAFMul = [&] ( 9089 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9090 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9091 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9092 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9093 DAG.getNode(PreferredFusedOpcode, SL, VT, 9094 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9095 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9096 Z)); 9097 }; 9098 if (N0.getOpcode() == ISD::FP_EXTEND) { 9099 SDValue N00 = N0.getOperand(0); 9100 if (N00.getOpcode() == PreferredFusedOpcode) { 9101 SDValue N002 = N00.getOperand(2); 9102 if (isContractableFMUL(N002)) 9103 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9104 N002.getOperand(0), N002.getOperand(1), 9105 N1); 9106 } 9107 } 9108 9109 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9110 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9111 if (N1.getOpcode() == PreferredFusedOpcode) { 9112 SDValue N12 = N1.getOperand(2); 9113 if (N12.getOpcode() == ISD::FP_EXTEND) { 9114 SDValue N120 = N12.getOperand(0); 9115 if (isContractableFMUL(N120)) 9116 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9117 N120.getOperand(0), N120.getOperand(1), 9118 N0); 9119 } 9120 } 9121 9122 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9123 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9124 // FIXME: This turns two single-precision and one double-precision 9125 // operation into two double-precision operations, which might not be 9126 // interesting for all targets, especially GPUs. 9127 if (N1.getOpcode() == ISD::FP_EXTEND) { 9128 SDValue N10 = N1.getOperand(0); 9129 if (N10.getOpcode() == PreferredFusedOpcode) { 9130 SDValue N102 = N10.getOperand(2); 9131 if (isContractableFMUL(N102)) 9132 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9133 N102.getOperand(0), N102.getOperand(1), 9134 N0); 9135 } 9136 } 9137 } 9138 } 9139 9140 return SDValue(); 9141 } 9142 9143 /// Try to perform FMA combining on a given FSUB node. 9144 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9145 SDValue N0 = N->getOperand(0); 9146 SDValue N1 = N->getOperand(1); 9147 EVT VT = N->getValueType(0); 9148 SDLoc SL(N); 9149 9150 const TargetOptions &Options = DAG.getTarget().Options; 9151 // Floating-point multiply-add with intermediate rounding. 9152 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9153 9154 // Floating-point multiply-add without intermediate rounding. 9155 bool HasFMA = 9156 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9157 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9158 9159 // No valid opcode, do not combine. 9160 if (!HasFMAD && !HasFMA) 9161 return SDValue(); 9162 9163 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9164 Options.UnsafeFPMath || HasFMAD); 9165 // If the subtraction is not contractable, do not combine. 9166 if (!AllowFusionGlobally && !isContractable(N)) 9167 return SDValue(); 9168 9169 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9170 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9171 return SDValue(); 9172 9173 // Always prefer FMAD to FMA for precision. 9174 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9175 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9176 bool LookThroughFPExt = TLI.isFPExtFree(VT); 9177 9178 // Is the node an FMUL and contractable either due to global flags or 9179 // SDNodeFlags. 9180 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9181 if (N.getOpcode() != ISD::FMUL) 9182 return false; 9183 return AllowFusionGlobally || isContractable(N.getNode()); 9184 }; 9185 9186 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9187 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9188 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9189 N0.getOperand(0), N0.getOperand(1), 9190 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9191 } 9192 9193 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9194 // Note: Commutes FSUB operands. 9195 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9196 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9197 DAG.getNode(ISD::FNEG, SL, VT, 9198 N1.getOperand(0)), 9199 N1.getOperand(1), N0); 9200 9201 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9202 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9203 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9204 SDValue N00 = N0.getOperand(0).getOperand(0); 9205 SDValue N01 = N0.getOperand(0).getOperand(1); 9206 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9207 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9208 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9209 } 9210 9211 // Look through FP_EXTEND nodes to do more combining. 9212 if (LookThroughFPExt) { 9213 // fold (fsub (fpext (fmul x, y)), z) 9214 // -> (fma (fpext x), (fpext y), (fneg z)) 9215 if (N0.getOpcode() == ISD::FP_EXTEND) { 9216 SDValue N00 = N0.getOperand(0); 9217 if (isContractableFMUL(N00)) 9218 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9219 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9220 N00.getOperand(0)), 9221 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9222 N00.getOperand(1)), 9223 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9224 } 9225 9226 // fold (fsub x, (fpext (fmul y, z))) 9227 // -> (fma (fneg (fpext y)), (fpext z), x) 9228 // Note: Commutes FSUB operands. 9229 if (N1.getOpcode() == ISD::FP_EXTEND) { 9230 SDValue N10 = N1.getOperand(0); 9231 if (isContractableFMUL(N10)) 9232 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9233 DAG.getNode(ISD::FNEG, SL, VT, 9234 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9235 N10.getOperand(0))), 9236 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9237 N10.getOperand(1)), 9238 N0); 9239 } 9240 9241 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9242 // -> (fneg (fma (fpext x), (fpext y), z)) 9243 // Note: This could be removed with appropriate canonicalization of the 9244 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9245 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9246 // from implementing the canonicalization in visitFSUB. 9247 if (N0.getOpcode() == ISD::FP_EXTEND) { 9248 SDValue N00 = N0.getOperand(0); 9249 if (N00.getOpcode() == ISD::FNEG) { 9250 SDValue N000 = N00.getOperand(0); 9251 if (isContractableFMUL(N000)) { 9252 return DAG.getNode(ISD::FNEG, SL, VT, 9253 DAG.getNode(PreferredFusedOpcode, SL, VT, 9254 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9255 N000.getOperand(0)), 9256 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9257 N000.getOperand(1)), 9258 N1)); 9259 } 9260 } 9261 } 9262 9263 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9264 // -> (fneg (fma (fpext x)), (fpext y), z) 9265 // Note: This could be removed with appropriate canonicalization of the 9266 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9267 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9268 // from implementing the canonicalization in visitFSUB. 9269 if (N0.getOpcode() == ISD::FNEG) { 9270 SDValue N00 = N0.getOperand(0); 9271 if (N00.getOpcode() == ISD::FP_EXTEND) { 9272 SDValue N000 = N00.getOperand(0); 9273 if (isContractableFMUL(N000)) { 9274 return DAG.getNode(ISD::FNEG, SL, VT, 9275 DAG.getNode(PreferredFusedOpcode, SL, VT, 9276 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9277 N000.getOperand(0)), 9278 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9279 N000.getOperand(1)), 9280 N1)); 9281 } 9282 } 9283 } 9284 9285 } 9286 9287 // More folding opportunities when target permits. 9288 if (Aggressive) { 9289 // fold (fsub (fma x, y, (fmul u, v)), z) 9290 // -> (fma x, y (fma u, v, (fneg z))) 9291 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9292 // are currently only supported on binary nodes. 9293 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9294 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9295 N0.getOperand(2)->hasOneUse()) { 9296 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9297 N0.getOperand(0), N0.getOperand(1), 9298 DAG.getNode(PreferredFusedOpcode, SL, VT, 9299 N0.getOperand(2).getOperand(0), 9300 N0.getOperand(2).getOperand(1), 9301 DAG.getNode(ISD::FNEG, SL, VT, 9302 N1))); 9303 } 9304 9305 // fold (fsub x, (fma y, z, (fmul u, v))) 9306 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9307 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9308 // are currently only supported on binary nodes. 9309 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9310 isContractableFMUL(N1.getOperand(2))) { 9311 SDValue N20 = N1.getOperand(2).getOperand(0); 9312 SDValue N21 = N1.getOperand(2).getOperand(1); 9313 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9314 DAG.getNode(ISD::FNEG, SL, VT, 9315 N1.getOperand(0)), 9316 N1.getOperand(1), 9317 DAG.getNode(PreferredFusedOpcode, SL, VT, 9318 DAG.getNode(ISD::FNEG, SL, VT, N20), 9319 9320 N21, N0)); 9321 } 9322 9323 if (LookThroughFPExt) { 9324 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9325 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9326 if (N0.getOpcode() == PreferredFusedOpcode) { 9327 SDValue N02 = N0.getOperand(2); 9328 if (N02.getOpcode() == ISD::FP_EXTEND) { 9329 SDValue N020 = N02.getOperand(0); 9330 if (isContractableFMUL(N020)) 9331 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9332 N0.getOperand(0), N0.getOperand(1), 9333 DAG.getNode(PreferredFusedOpcode, SL, VT, 9334 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9335 N020.getOperand(0)), 9336 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9337 N020.getOperand(1)), 9338 DAG.getNode(ISD::FNEG, SL, VT, 9339 N1))); 9340 } 9341 } 9342 9343 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9344 // -> (fma (fpext x), (fpext y), 9345 // (fma (fpext u), (fpext v), (fneg z))) 9346 // FIXME: This turns two single-precision and one double-precision 9347 // operation into two double-precision operations, which might not be 9348 // interesting for all targets, especially GPUs. 9349 if (N0.getOpcode() == ISD::FP_EXTEND) { 9350 SDValue N00 = N0.getOperand(0); 9351 if (N00.getOpcode() == PreferredFusedOpcode) { 9352 SDValue N002 = N00.getOperand(2); 9353 if (isContractableFMUL(N002)) 9354 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9355 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9356 N00.getOperand(0)), 9357 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9358 N00.getOperand(1)), 9359 DAG.getNode(PreferredFusedOpcode, SL, VT, 9360 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9361 N002.getOperand(0)), 9362 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9363 N002.getOperand(1)), 9364 DAG.getNode(ISD::FNEG, SL, VT, 9365 N1))); 9366 } 9367 } 9368 9369 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9370 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9371 if (N1.getOpcode() == PreferredFusedOpcode && 9372 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9373 SDValue N120 = N1.getOperand(2).getOperand(0); 9374 if (isContractableFMUL(N120)) { 9375 SDValue N1200 = N120.getOperand(0); 9376 SDValue N1201 = N120.getOperand(1); 9377 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9378 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9379 N1.getOperand(1), 9380 DAG.getNode(PreferredFusedOpcode, SL, VT, 9381 DAG.getNode(ISD::FNEG, SL, VT, 9382 DAG.getNode(ISD::FP_EXTEND, SL, 9383 VT, N1200)), 9384 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9385 N1201), 9386 N0)); 9387 } 9388 } 9389 9390 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9391 // -> (fma (fneg (fpext y)), (fpext z), 9392 // (fma (fneg (fpext u)), (fpext v), x)) 9393 // FIXME: This turns two single-precision and one double-precision 9394 // operation into two double-precision operations, which might not be 9395 // interesting for all targets, especially GPUs. 9396 if (N1.getOpcode() == ISD::FP_EXTEND && 9397 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9398 SDValue N100 = N1.getOperand(0).getOperand(0); 9399 SDValue N101 = N1.getOperand(0).getOperand(1); 9400 SDValue N102 = N1.getOperand(0).getOperand(2); 9401 if (isContractableFMUL(N102)) { 9402 SDValue N1020 = N102.getOperand(0); 9403 SDValue N1021 = N102.getOperand(1); 9404 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9405 DAG.getNode(ISD::FNEG, SL, VT, 9406 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9407 N100)), 9408 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9409 DAG.getNode(PreferredFusedOpcode, SL, VT, 9410 DAG.getNode(ISD::FNEG, SL, VT, 9411 DAG.getNode(ISD::FP_EXTEND, SL, 9412 VT, N1020)), 9413 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9414 N1021), 9415 N0)); 9416 } 9417 } 9418 } 9419 } 9420 9421 return SDValue(); 9422 } 9423 9424 /// Try to perform FMA combining on a given FMUL node based on the distributive 9425 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9426 /// subtraction instead of addition). 9427 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9428 SDValue N0 = N->getOperand(0); 9429 SDValue N1 = N->getOperand(1); 9430 EVT VT = N->getValueType(0); 9431 SDLoc SL(N); 9432 9433 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9434 9435 const TargetOptions &Options = DAG.getTarget().Options; 9436 9437 // The transforms below are incorrect when x == 0 and y == inf, because the 9438 // intermediate multiplication produces a nan. 9439 if (!Options.NoInfsFPMath) 9440 return SDValue(); 9441 9442 // Floating-point multiply-add without intermediate rounding. 9443 bool HasFMA = 9444 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9445 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9446 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9447 9448 // Floating-point multiply-add with intermediate rounding. This can result 9449 // in a less precise result due to the changed rounding order. 9450 bool HasFMAD = Options.UnsafeFPMath && 9451 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9452 9453 // No valid opcode, do not combine. 9454 if (!HasFMAD && !HasFMA) 9455 return SDValue(); 9456 9457 // Always prefer FMAD to FMA for precision. 9458 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9459 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9460 9461 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9462 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9463 auto FuseFADD = [&](SDValue X, SDValue Y) { 9464 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9465 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9466 if (XC1 && XC1->isExactlyValue(+1.0)) 9467 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9468 if (XC1 && XC1->isExactlyValue(-1.0)) 9469 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9470 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9471 } 9472 return SDValue(); 9473 }; 9474 9475 if (SDValue FMA = FuseFADD(N0, N1)) 9476 return FMA; 9477 if (SDValue FMA = FuseFADD(N1, N0)) 9478 return FMA; 9479 9480 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9481 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9482 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9483 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9484 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9485 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9486 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9487 if (XC0 && XC0->isExactlyValue(+1.0)) 9488 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9489 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9490 Y); 9491 if (XC0 && XC0->isExactlyValue(-1.0)) 9492 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9493 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9494 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9495 9496 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9497 if (XC1 && XC1->isExactlyValue(+1.0)) 9498 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9499 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9500 if (XC1 && XC1->isExactlyValue(-1.0)) 9501 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9502 } 9503 return SDValue(); 9504 }; 9505 9506 if (SDValue FMA = FuseFSUB(N0, N1)) 9507 return FMA; 9508 if (SDValue FMA = FuseFSUB(N1, N0)) 9509 return FMA; 9510 9511 return SDValue(); 9512 } 9513 9514 static bool isFMulNegTwo(SDValue &N) { 9515 if (N.getOpcode() != ISD::FMUL) 9516 return false; 9517 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9518 return CFP->isExactlyValue(-2.0); 9519 return false; 9520 } 9521 9522 SDValue DAGCombiner::visitFADD(SDNode *N) { 9523 SDValue N0 = N->getOperand(0); 9524 SDValue N1 = N->getOperand(1); 9525 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9526 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9527 EVT VT = N->getValueType(0); 9528 SDLoc DL(N); 9529 const TargetOptions &Options = DAG.getTarget().Options; 9530 const SDNodeFlags Flags = N->getFlags(); 9531 9532 // fold vector ops 9533 if (VT.isVector()) 9534 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9535 return FoldedVOp; 9536 9537 // fold (fadd c1, c2) -> c1 + c2 9538 if (N0CFP && N1CFP) 9539 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9540 9541 // canonicalize constant to RHS 9542 if (N0CFP && !N1CFP) 9543 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9544 9545 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9546 return NewSel; 9547 9548 // fold (fadd A, (fneg B)) -> (fsub A, B) 9549 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9550 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9551 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9552 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9553 9554 // fold (fadd (fneg A), B) -> (fsub B, A) 9555 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9556 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9557 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9558 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9559 9560 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9561 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9562 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9563 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9564 bool N1IsFMul = isFMulNegTwo(N1); 9565 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9566 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9567 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9568 } 9569 9570 // FIXME: Auto-upgrade the target/function-level option. 9571 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9572 // fold (fadd A, 0) -> A 9573 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9574 if (N1C->isZero()) 9575 return N0; 9576 } 9577 9578 // If 'unsafe math' is enabled, fold lots of things. 9579 if (Options.UnsafeFPMath) { 9580 // No FP constant should be created after legalization as Instruction 9581 // Selection pass has a hard time dealing with FP constants. 9582 bool AllowNewConst = (Level < AfterLegalizeDAG); 9583 9584 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9585 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9586 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9587 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9588 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9589 Flags), 9590 Flags); 9591 9592 // If allowed, fold (fadd (fneg x), x) -> 0.0 9593 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9594 return DAG.getConstantFP(0.0, DL, VT); 9595 9596 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9597 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9598 return DAG.getConstantFP(0.0, DL, VT); 9599 9600 // We can fold chains of FADD's of the same value into multiplications. 9601 // This transform is not safe in general because we are reducing the number 9602 // of rounding steps. 9603 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9604 if (N0.getOpcode() == ISD::FMUL) { 9605 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9606 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9607 9608 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9609 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9610 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9611 DAG.getConstantFP(1.0, DL, VT), Flags); 9612 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9613 } 9614 9615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9617 N1.getOperand(0) == N1.getOperand(1) && 9618 N0.getOperand(0) == N1.getOperand(0)) { 9619 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9620 DAG.getConstantFP(2.0, DL, VT), Flags); 9621 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9622 } 9623 } 9624 9625 if (N1.getOpcode() == ISD::FMUL) { 9626 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9627 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9628 9629 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9630 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9631 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9632 DAG.getConstantFP(1.0, DL, VT), Flags); 9633 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9634 } 9635 9636 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9637 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9638 N0.getOperand(0) == N0.getOperand(1) && 9639 N1.getOperand(0) == N0.getOperand(0)) { 9640 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9641 DAG.getConstantFP(2.0, DL, VT), Flags); 9642 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9643 } 9644 } 9645 9646 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9647 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9648 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9649 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9650 (N0.getOperand(0) == N1)) { 9651 return DAG.getNode(ISD::FMUL, DL, VT, 9652 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9653 } 9654 } 9655 9656 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9657 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9658 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9659 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9660 N1.getOperand(0) == N0) { 9661 return DAG.getNode(ISD::FMUL, DL, VT, 9662 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9663 } 9664 } 9665 9666 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9667 if (AllowNewConst && 9668 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9669 N0.getOperand(0) == N0.getOperand(1) && 9670 N1.getOperand(0) == N1.getOperand(1) && 9671 N0.getOperand(0) == N1.getOperand(0)) { 9672 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9673 DAG.getConstantFP(4.0, DL, VT), Flags); 9674 } 9675 } 9676 } // enable-unsafe-fp-math 9677 9678 // FADD -> FMA combines: 9679 if (SDValue Fused = visitFADDForFMACombine(N)) { 9680 AddToWorklist(Fused.getNode()); 9681 return Fused; 9682 } 9683 return SDValue(); 9684 } 9685 9686 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9687 SDValue N0 = N->getOperand(0); 9688 SDValue N1 = N->getOperand(1); 9689 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9690 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9691 EVT VT = N->getValueType(0); 9692 SDLoc DL(N); 9693 const TargetOptions &Options = DAG.getTarget().Options; 9694 const SDNodeFlags Flags = N->getFlags(); 9695 9696 // fold vector ops 9697 if (VT.isVector()) 9698 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9699 return FoldedVOp; 9700 9701 // fold (fsub c1, c2) -> c1-c2 9702 if (N0CFP && N1CFP) 9703 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9704 9705 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9706 return NewSel; 9707 9708 // fold (fsub A, (fneg B)) -> (fadd A, B) 9709 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9710 return DAG.getNode(ISD::FADD, DL, VT, N0, 9711 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9712 9713 // FIXME: Auto-upgrade the target/function-level option. 9714 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9715 // (fsub 0, B) -> -B 9716 if (N0CFP && N0CFP->isZero()) { 9717 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9718 return GetNegatedExpression(N1, DAG, LegalOperations); 9719 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9720 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9721 } 9722 } 9723 9724 // If 'unsafe math' is enabled, fold lots of things. 9725 if (Options.UnsafeFPMath) { 9726 // (fsub A, 0) -> A 9727 if (N1CFP && N1CFP->isZero()) 9728 return N0; 9729 9730 // (fsub x, x) -> 0.0 9731 if (N0 == N1) 9732 return DAG.getConstantFP(0.0f, DL, VT); 9733 9734 // (fsub x, (fadd x, y)) -> (fneg y) 9735 // (fsub x, (fadd y, x)) -> (fneg y) 9736 if (N1.getOpcode() == ISD::FADD) { 9737 SDValue N10 = N1->getOperand(0); 9738 SDValue N11 = N1->getOperand(1); 9739 9740 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9741 return GetNegatedExpression(N11, DAG, LegalOperations); 9742 9743 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9744 return GetNegatedExpression(N10, DAG, LegalOperations); 9745 } 9746 } 9747 9748 // FSUB -> FMA combines: 9749 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9750 AddToWorklist(Fused.getNode()); 9751 return Fused; 9752 } 9753 9754 return SDValue(); 9755 } 9756 9757 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9758 SDValue N0 = N->getOperand(0); 9759 SDValue N1 = N->getOperand(1); 9760 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9761 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9762 EVT VT = N->getValueType(0); 9763 SDLoc DL(N); 9764 const TargetOptions &Options = DAG.getTarget().Options; 9765 const SDNodeFlags Flags = N->getFlags(); 9766 9767 // fold vector ops 9768 if (VT.isVector()) { 9769 // This just handles C1 * C2 for vectors. Other vector folds are below. 9770 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9771 return FoldedVOp; 9772 } 9773 9774 // fold (fmul c1, c2) -> c1*c2 9775 if (N0CFP && N1CFP) 9776 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9777 9778 // canonicalize constant to RHS 9779 if (isConstantFPBuildVectorOrConstantFP(N0) && 9780 !isConstantFPBuildVectorOrConstantFP(N1)) 9781 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9782 9783 // fold (fmul A, 1.0) -> A 9784 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9785 return N0; 9786 9787 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9788 return NewSel; 9789 9790 if (Options.UnsafeFPMath) { 9791 // fold (fmul A, 0) -> 0 9792 if (N1CFP && N1CFP->isZero()) 9793 return N1; 9794 9795 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9796 if (N0.getOpcode() == ISD::FMUL) { 9797 // Fold scalars or any vector constants (not just splats). 9798 // This fold is done in general by InstCombine, but extra fmul insts 9799 // may have been generated during lowering. 9800 SDValue N00 = N0.getOperand(0); 9801 SDValue N01 = N0.getOperand(1); 9802 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9803 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9804 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9805 9806 // Check 1: Make sure that the first operand of the inner multiply is NOT 9807 // a constant. Otherwise, we may induce infinite looping. 9808 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9809 // Check 2: Make sure that the second operand of the inner multiply and 9810 // the second operand of the outer multiply are constants. 9811 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9812 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9813 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9814 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9815 } 9816 } 9817 } 9818 9819 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9820 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9821 // during an early run of DAGCombiner can prevent folding with fmuls 9822 // inserted during lowering. 9823 if (N0.getOpcode() == ISD::FADD && 9824 (N0.getOperand(0) == N0.getOperand(1)) && 9825 N0.hasOneUse()) { 9826 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9827 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9828 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9829 } 9830 } 9831 9832 // fold (fmul X, 2.0) -> (fadd X, X) 9833 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9834 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9835 9836 // fold (fmul X, -1.0) -> (fneg X) 9837 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9838 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9839 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9840 9841 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9842 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9843 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9844 // Both can be negated for free, check to see if at least one is cheaper 9845 // negated. 9846 if (LHSNeg == 2 || RHSNeg == 2) 9847 return DAG.getNode(ISD::FMUL, DL, VT, 9848 GetNegatedExpression(N0, DAG, LegalOperations), 9849 GetNegatedExpression(N1, DAG, LegalOperations), 9850 Flags); 9851 } 9852 } 9853 9854 // FMUL -> FMA combines: 9855 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9856 AddToWorklist(Fused.getNode()); 9857 return Fused; 9858 } 9859 9860 return SDValue(); 9861 } 9862 9863 SDValue DAGCombiner::visitFMA(SDNode *N) { 9864 SDValue N0 = N->getOperand(0); 9865 SDValue N1 = N->getOperand(1); 9866 SDValue N2 = N->getOperand(2); 9867 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9868 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9869 EVT VT = N->getValueType(0); 9870 SDLoc DL(N); 9871 const TargetOptions &Options = DAG.getTarget().Options; 9872 9873 // Constant fold FMA. 9874 if (isa<ConstantFPSDNode>(N0) && 9875 isa<ConstantFPSDNode>(N1) && 9876 isa<ConstantFPSDNode>(N2)) { 9877 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9878 } 9879 9880 if (Options.UnsafeFPMath) { 9881 if (N0CFP && N0CFP->isZero()) 9882 return N2; 9883 if (N1CFP && N1CFP->isZero()) 9884 return N2; 9885 } 9886 // TODO: The FMA node should have flags that propagate to these nodes. 9887 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9888 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9889 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9890 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9891 9892 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9893 if (isConstantFPBuildVectorOrConstantFP(N0) && 9894 !isConstantFPBuildVectorOrConstantFP(N1)) 9895 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9896 9897 // TODO: FMA nodes should have flags that propagate to the created nodes. 9898 // For now, create a Flags object for use with all unsafe math transforms. 9899 SDNodeFlags Flags; 9900 Flags.setUnsafeAlgebra(true); 9901 9902 if (Options.UnsafeFPMath) { 9903 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9904 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9905 isConstantFPBuildVectorOrConstantFP(N1) && 9906 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9907 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9908 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9909 Flags), Flags); 9910 } 9911 9912 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9913 if (N0.getOpcode() == ISD::FMUL && 9914 isConstantFPBuildVectorOrConstantFP(N1) && 9915 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9916 return DAG.getNode(ISD::FMA, DL, VT, 9917 N0.getOperand(0), 9918 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9919 Flags), 9920 N2); 9921 } 9922 } 9923 9924 // (fma x, 1, y) -> (fadd x, y) 9925 // (fma x, -1, y) -> (fadd (fneg x), y) 9926 if (N1CFP) { 9927 if (N1CFP->isExactlyValue(1.0)) 9928 // TODO: The FMA node should have flags that propagate to this node. 9929 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9930 9931 if (N1CFP->isExactlyValue(-1.0) && 9932 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9933 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9934 AddToWorklist(RHSNeg.getNode()); 9935 // TODO: The FMA node should have flags that propagate to this node. 9936 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9937 } 9938 } 9939 9940 if (Options.UnsafeFPMath) { 9941 // (fma x, c, x) -> (fmul x, (c+1)) 9942 if (N1CFP && N0 == N2) { 9943 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9944 DAG.getNode(ISD::FADD, DL, VT, N1, 9945 DAG.getConstantFP(1.0, DL, VT), Flags), 9946 Flags); 9947 } 9948 9949 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9950 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9951 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9952 DAG.getNode(ISD::FADD, DL, VT, N1, 9953 DAG.getConstantFP(-1.0, DL, VT), Flags), 9954 Flags); 9955 } 9956 } 9957 9958 return SDValue(); 9959 } 9960 9961 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9962 // reciprocal. 9963 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9964 // Notice that this is not always beneficial. One reason is different targets 9965 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9966 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9967 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9968 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9969 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9970 const SDNodeFlags Flags = N->getFlags(); 9971 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 9972 return SDValue(); 9973 9974 // Skip if current node is a reciprocal. 9975 SDValue N0 = N->getOperand(0); 9976 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9977 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9978 return SDValue(); 9979 9980 // Exit early if the target does not want this transform or if there can't 9981 // possibly be enough uses of the divisor to make the transform worthwhile. 9982 SDValue N1 = N->getOperand(1); 9983 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9984 if (!MinUses || N1->use_size() < MinUses) 9985 return SDValue(); 9986 9987 // Find all FDIV users of the same divisor. 9988 // Use a set because duplicates may be present in the user list. 9989 SetVector<SDNode *> Users; 9990 for (auto *U : N1->uses()) { 9991 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9992 // This division is eligible for optimization only if global unsafe math 9993 // is enabled or if this division allows reciprocal formation. 9994 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 9995 Users.insert(U); 9996 } 9997 } 9998 9999 // Now that we have the actual number of divisor uses, make sure it meets 10000 // the minimum threshold specified by the target. 10001 if (Users.size() < MinUses) 10002 return SDValue(); 10003 10004 EVT VT = N->getValueType(0); 10005 SDLoc DL(N); 10006 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 10007 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 10008 10009 // Dividend / Divisor -> Dividend * Reciprocal 10010 for (auto *U : Users) { 10011 SDValue Dividend = U->getOperand(0); 10012 if (Dividend != FPOne) { 10013 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 10014 Reciprocal, Flags); 10015 CombineTo(U, NewNode); 10016 } else if (U != Reciprocal.getNode()) { 10017 // In the absence of fast-math-flags, this user node is always the 10018 // same node as Reciprocal, but with FMF they may be different nodes. 10019 CombineTo(U, Reciprocal); 10020 } 10021 } 10022 return SDValue(N, 0); // N was replaced. 10023 } 10024 10025 SDValue DAGCombiner::visitFDIV(SDNode *N) { 10026 SDValue N0 = N->getOperand(0); 10027 SDValue N1 = N->getOperand(1); 10028 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10029 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10030 EVT VT = N->getValueType(0); 10031 SDLoc DL(N); 10032 const TargetOptions &Options = DAG.getTarget().Options; 10033 SDNodeFlags Flags = N->getFlags(); 10034 10035 // fold vector ops 10036 if (VT.isVector()) 10037 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 10038 return FoldedVOp; 10039 10040 // fold (fdiv c1, c2) -> c1/c2 10041 if (N0CFP && N1CFP) 10042 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10043 10044 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10045 return NewSel; 10046 10047 if (Options.UnsafeFPMath) { 10048 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10049 if (N1CFP) { 10050 // Compute the reciprocal 1.0 / c2. 10051 const APFloat &N1APF = N1CFP->getValueAPF(); 10052 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10053 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10054 // Only do the transform if the reciprocal is a legal fp immediate that 10055 // isn't too nasty (eg NaN, denormal, ...). 10056 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10057 (!LegalOperations || 10058 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10059 // backend)... we should handle this gracefully after Legalize. 10060 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 10061 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 10062 TLI.isFPImmLegal(Recip, VT))) 10063 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10064 DAG.getConstantFP(Recip, DL, VT), Flags); 10065 } 10066 10067 // If this FDIV is part of a reciprocal square root, it may be folded 10068 // into a target-specific square root estimate instruction. 10069 if (N1.getOpcode() == ISD::FSQRT) { 10070 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10071 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10072 } 10073 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10074 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10075 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10076 Flags)) { 10077 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10078 AddToWorklist(RV.getNode()); 10079 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10080 } 10081 } else if (N1.getOpcode() == ISD::FP_ROUND && 10082 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10083 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10084 Flags)) { 10085 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10086 AddToWorklist(RV.getNode()); 10087 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10088 } 10089 } else if (N1.getOpcode() == ISD::FMUL) { 10090 // Look through an FMUL. Even though this won't remove the FDIV directly, 10091 // it's still worthwhile to get rid of the FSQRT if possible. 10092 SDValue SqrtOp; 10093 SDValue OtherOp; 10094 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10095 SqrtOp = N1.getOperand(0); 10096 OtherOp = N1.getOperand(1); 10097 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10098 SqrtOp = N1.getOperand(1); 10099 OtherOp = N1.getOperand(0); 10100 } 10101 if (SqrtOp.getNode()) { 10102 // We found a FSQRT, so try to make this fold: 10103 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10104 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10105 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10106 AddToWorklist(RV.getNode()); 10107 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10108 } 10109 } 10110 } 10111 10112 // Fold into a reciprocal estimate and multiply instead of a real divide. 10113 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10114 AddToWorklist(RV.getNode()); 10115 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10116 } 10117 } 10118 10119 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10120 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10121 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10122 // Both can be negated for free, check to see if at least one is cheaper 10123 // negated. 10124 if (LHSNeg == 2 || RHSNeg == 2) 10125 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10126 GetNegatedExpression(N0, DAG, LegalOperations), 10127 GetNegatedExpression(N1, DAG, LegalOperations), 10128 Flags); 10129 } 10130 } 10131 10132 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10133 return CombineRepeatedDivisors; 10134 10135 return SDValue(); 10136 } 10137 10138 SDValue DAGCombiner::visitFREM(SDNode *N) { 10139 SDValue N0 = N->getOperand(0); 10140 SDValue N1 = N->getOperand(1); 10141 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10142 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10143 EVT VT = N->getValueType(0); 10144 10145 // fold (frem c1, c2) -> fmod(c1,c2) 10146 if (N0CFP && N1CFP) 10147 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10148 10149 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10150 return NewSel; 10151 10152 return SDValue(); 10153 } 10154 10155 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10156 if (!DAG.getTarget().Options.UnsafeFPMath) 10157 return SDValue(); 10158 10159 SDValue N0 = N->getOperand(0); 10160 if (TLI.isFsqrtCheap(N0, DAG)) 10161 return SDValue(); 10162 10163 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10164 // For now, create a Flags object for use with all unsafe math transforms. 10165 SDNodeFlags Flags; 10166 Flags.setUnsafeAlgebra(true); 10167 return buildSqrtEstimate(N0, Flags); 10168 } 10169 10170 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10171 /// copysign(x, fp_round(y)) -> copysign(x, y) 10172 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10173 SDValue N1 = N->getOperand(1); 10174 if ((N1.getOpcode() == ISD::FP_EXTEND || 10175 N1.getOpcode() == ISD::FP_ROUND)) { 10176 // Do not optimize out type conversion of f128 type yet. 10177 // For some targets like x86_64, configuration is changed to keep one f128 10178 // value in one SSE register, but instruction selection cannot handle 10179 // FCOPYSIGN on SSE registers yet. 10180 EVT N1VT = N1->getValueType(0); 10181 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 10182 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10183 } 10184 return false; 10185 } 10186 10187 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10188 SDValue N0 = N->getOperand(0); 10189 SDValue N1 = N->getOperand(1); 10190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10191 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10192 EVT VT = N->getValueType(0); 10193 10194 if (N0CFP && N1CFP) // Constant fold 10195 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10196 10197 if (N1CFP) { 10198 const APFloat &V = N1CFP->getValueAPF(); 10199 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10200 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10201 if (!V.isNegative()) { 10202 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10203 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10204 } else { 10205 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10206 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10207 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10208 } 10209 } 10210 10211 // copysign(fabs(x), y) -> copysign(x, y) 10212 // copysign(fneg(x), y) -> copysign(x, y) 10213 // copysign(copysign(x,z), y) -> copysign(x, y) 10214 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10215 N0.getOpcode() == ISD::FCOPYSIGN) 10216 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10217 10218 // copysign(x, abs(y)) -> abs(x) 10219 if (N1.getOpcode() == ISD::FABS) 10220 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10221 10222 // copysign(x, copysign(y,z)) -> copysign(x, z) 10223 if (N1.getOpcode() == ISD::FCOPYSIGN) 10224 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10225 10226 // copysign(x, fp_extend(y)) -> copysign(x, y) 10227 // copysign(x, fp_round(y)) -> copysign(x, y) 10228 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10229 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10230 10231 return SDValue(); 10232 } 10233 10234 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10235 SDValue N0 = N->getOperand(0); 10236 EVT VT = N->getValueType(0); 10237 EVT OpVT = N0.getValueType(); 10238 10239 // fold (sint_to_fp c1) -> c1fp 10240 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10241 // ...but only if the target supports immediate floating-point values 10242 (!LegalOperations || 10243 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10244 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10245 10246 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10247 // but UINT_TO_FP is legal on this target, try to convert. 10248 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10249 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10250 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10251 if (DAG.SignBitIsZero(N0)) 10252 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10253 } 10254 10255 // The next optimizations are desirable only if SELECT_CC can be lowered. 10256 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10257 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10258 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10259 !VT.isVector() && 10260 (!LegalOperations || 10261 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10262 SDLoc DL(N); 10263 SDValue Ops[] = 10264 { N0.getOperand(0), N0.getOperand(1), 10265 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10266 N0.getOperand(2) }; 10267 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10268 } 10269 10270 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10271 // (select_cc x, y, 1.0, 0.0,, cc) 10272 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10273 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10274 (!LegalOperations || 10275 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10276 SDLoc DL(N); 10277 SDValue Ops[] = 10278 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10279 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10280 N0.getOperand(0).getOperand(2) }; 10281 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10282 } 10283 } 10284 10285 return SDValue(); 10286 } 10287 10288 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10289 SDValue N0 = N->getOperand(0); 10290 EVT VT = N->getValueType(0); 10291 EVT OpVT = N0.getValueType(); 10292 10293 // fold (uint_to_fp c1) -> c1fp 10294 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10295 // ...but only if the target supports immediate floating-point values 10296 (!LegalOperations || 10297 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10298 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10299 10300 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10301 // but SINT_TO_FP is legal on this target, try to convert. 10302 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10303 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10304 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10305 if (DAG.SignBitIsZero(N0)) 10306 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10307 } 10308 10309 // The next optimizations are desirable only if SELECT_CC can be lowered. 10310 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10311 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10312 10313 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10314 (!LegalOperations || 10315 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10316 SDLoc DL(N); 10317 SDValue Ops[] = 10318 { N0.getOperand(0), N0.getOperand(1), 10319 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10320 N0.getOperand(2) }; 10321 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10322 } 10323 } 10324 10325 return SDValue(); 10326 } 10327 10328 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10329 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10330 SDValue N0 = N->getOperand(0); 10331 EVT VT = N->getValueType(0); 10332 10333 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10334 return SDValue(); 10335 10336 SDValue Src = N0.getOperand(0); 10337 EVT SrcVT = Src.getValueType(); 10338 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10339 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10340 10341 // We can safely assume the conversion won't overflow the output range, 10342 // because (for example) (uint8_t)18293.f is undefined behavior. 10343 10344 // Since we can assume the conversion won't overflow, our decision as to 10345 // whether the input will fit in the float should depend on the minimum 10346 // of the input range and output range. 10347 10348 // This means this is also safe for a signed input and unsigned output, since 10349 // a negative input would lead to undefined behavior. 10350 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10351 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10352 unsigned ActualSize = std::min(InputSize, OutputSize); 10353 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10354 10355 // We can only fold away the float conversion if the input range can be 10356 // represented exactly in the float range. 10357 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10358 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10359 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10360 : ISD::ZERO_EXTEND; 10361 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10362 } 10363 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10364 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10365 return DAG.getBitcast(VT, Src); 10366 } 10367 return SDValue(); 10368 } 10369 10370 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10371 SDValue N0 = N->getOperand(0); 10372 EVT VT = N->getValueType(0); 10373 10374 // fold (fp_to_sint c1fp) -> c1 10375 if (isConstantFPBuildVectorOrConstantFP(N0)) 10376 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10377 10378 return FoldIntToFPToInt(N, DAG); 10379 } 10380 10381 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10382 SDValue N0 = N->getOperand(0); 10383 EVT VT = N->getValueType(0); 10384 10385 // fold (fp_to_uint c1fp) -> c1 10386 if (isConstantFPBuildVectorOrConstantFP(N0)) 10387 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10388 10389 return FoldIntToFPToInt(N, DAG); 10390 } 10391 10392 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10393 SDValue N0 = N->getOperand(0); 10394 SDValue N1 = N->getOperand(1); 10395 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10396 EVT VT = N->getValueType(0); 10397 10398 // fold (fp_round c1fp) -> c1fp 10399 if (N0CFP) 10400 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10401 10402 // fold (fp_round (fp_extend x)) -> x 10403 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10404 return N0.getOperand(0); 10405 10406 // fold (fp_round (fp_round x)) -> (fp_round x) 10407 if (N0.getOpcode() == ISD::FP_ROUND) { 10408 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10409 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10410 10411 // Skip this folding if it results in an fp_round from f80 to f16. 10412 // 10413 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10414 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10415 // instructions from f32 or f64. Moreover, the first (value-preserving) 10416 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10417 // x86. 10418 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10419 return SDValue(); 10420 10421 // If the first fp_round isn't a value preserving truncation, it might 10422 // introduce a tie in the second fp_round, that wouldn't occur in the 10423 // single-step fp_round we want to fold to. 10424 // In other words, double rounding isn't the same as rounding. 10425 // Also, this is a value preserving truncation iff both fp_round's are. 10426 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10427 SDLoc DL(N); 10428 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10429 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10430 } 10431 } 10432 10433 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10434 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10435 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10436 N0.getOperand(0), N1); 10437 AddToWorklist(Tmp.getNode()); 10438 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10439 Tmp, N0.getOperand(1)); 10440 } 10441 10442 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10443 return NewVSel; 10444 10445 return SDValue(); 10446 } 10447 10448 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10449 SDValue N0 = N->getOperand(0); 10450 EVT VT = N->getValueType(0); 10451 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10452 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10453 10454 // fold (fp_round_inreg c1fp) -> c1fp 10455 if (N0CFP && isTypeLegal(EVT)) { 10456 SDLoc DL(N); 10457 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10458 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10459 } 10460 10461 return SDValue(); 10462 } 10463 10464 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10465 SDValue N0 = N->getOperand(0); 10466 EVT VT = N->getValueType(0); 10467 10468 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10469 if (N->hasOneUse() && 10470 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10471 return SDValue(); 10472 10473 // fold (fp_extend c1fp) -> c1fp 10474 if (isConstantFPBuildVectorOrConstantFP(N0)) 10475 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10476 10477 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10478 if (N0.getOpcode() == ISD::FP16_TO_FP && 10479 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10480 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10481 10482 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10483 // value of X. 10484 if (N0.getOpcode() == ISD::FP_ROUND 10485 && N0.getConstantOperandVal(1) == 1) { 10486 SDValue In = N0.getOperand(0); 10487 if (In.getValueType() == VT) return In; 10488 if (VT.bitsLT(In.getValueType())) 10489 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10490 In, N0.getOperand(1)); 10491 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10492 } 10493 10494 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10495 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10496 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10497 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10498 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10499 LN0->getChain(), 10500 LN0->getBasePtr(), N0.getValueType(), 10501 LN0->getMemOperand()); 10502 CombineTo(N, ExtLoad); 10503 CombineTo(N0.getNode(), 10504 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10505 N0.getValueType(), ExtLoad, 10506 DAG.getIntPtrConstant(1, SDLoc(N0))), 10507 ExtLoad.getValue(1)); 10508 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10509 } 10510 10511 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10512 return NewVSel; 10513 10514 return SDValue(); 10515 } 10516 10517 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10518 SDValue N0 = N->getOperand(0); 10519 EVT VT = N->getValueType(0); 10520 10521 // fold (fceil c1) -> fceil(c1) 10522 if (isConstantFPBuildVectorOrConstantFP(N0)) 10523 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10524 10525 return SDValue(); 10526 } 10527 10528 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10529 SDValue N0 = N->getOperand(0); 10530 EVT VT = N->getValueType(0); 10531 10532 // fold (ftrunc c1) -> ftrunc(c1) 10533 if (isConstantFPBuildVectorOrConstantFP(N0)) 10534 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10535 10536 return SDValue(); 10537 } 10538 10539 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10540 SDValue N0 = N->getOperand(0); 10541 EVT VT = N->getValueType(0); 10542 10543 // fold (ffloor c1) -> ffloor(c1) 10544 if (isConstantFPBuildVectorOrConstantFP(N0)) 10545 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10546 10547 return SDValue(); 10548 } 10549 10550 // FIXME: FNEG and FABS have a lot in common; refactor. 10551 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10552 SDValue N0 = N->getOperand(0); 10553 EVT VT = N->getValueType(0); 10554 10555 // Constant fold FNEG. 10556 if (isConstantFPBuildVectorOrConstantFP(N0)) 10557 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10558 10559 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10560 &DAG.getTarget().Options)) 10561 return GetNegatedExpression(N0, DAG, LegalOperations); 10562 10563 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10564 // constant pool values. 10565 if (!TLI.isFNegFree(VT) && 10566 N0.getOpcode() == ISD::BITCAST && 10567 N0.getNode()->hasOneUse()) { 10568 SDValue Int = N0.getOperand(0); 10569 EVT IntVT = Int.getValueType(); 10570 if (IntVT.isInteger() && !IntVT.isVector()) { 10571 APInt SignMask; 10572 if (N0.getValueType().isVector()) { 10573 // For a vector, get a mask such as 0x80... per scalar element 10574 // and splat it. 10575 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10576 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10577 } else { 10578 // For a scalar, just generate 0x80... 10579 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10580 } 10581 SDLoc DL0(N0); 10582 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10583 DAG.getConstant(SignMask, DL0, IntVT)); 10584 AddToWorklist(Int.getNode()); 10585 return DAG.getBitcast(VT, Int); 10586 } 10587 } 10588 10589 // (fneg (fmul c, x)) -> (fmul -c, x) 10590 if (N0.getOpcode() == ISD::FMUL && 10591 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10592 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10593 if (CFP1) { 10594 APFloat CVal = CFP1->getValueAPF(); 10595 CVal.changeSign(); 10596 if (Level >= AfterLegalizeDAG && 10597 (TLI.isFPImmLegal(CVal, VT) || 10598 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10599 return DAG.getNode( 10600 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10601 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10602 N0->getFlags()); 10603 } 10604 } 10605 10606 return SDValue(); 10607 } 10608 10609 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10610 SDValue N0 = N->getOperand(0); 10611 SDValue N1 = N->getOperand(1); 10612 EVT VT = N->getValueType(0); 10613 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10614 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10615 10616 if (N0CFP && N1CFP) { 10617 const APFloat &C0 = N0CFP->getValueAPF(); 10618 const APFloat &C1 = N1CFP->getValueAPF(); 10619 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10620 } 10621 10622 // Canonicalize to constant on RHS. 10623 if (isConstantFPBuildVectorOrConstantFP(N0) && 10624 !isConstantFPBuildVectorOrConstantFP(N1)) 10625 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10626 10627 return SDValue(); 10628 } 10629 10630 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10631 SDValue N0 = N->getOperand(0); 10632 SDValue N1 = N->getOperand(1); 10633 EVT VT = N->getValueType(0); 10634 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10635 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10636 10637 if (N0CFP && N1CFP) { 10638 const APFloat &C0 = N0CFP->getValueAPF(); 10639 const APFloat &C1 = N1CFP->getValueAPF(); 10640 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10641 } 10642 10643 // Canonicalize to constant on RHS. 10644 if (isConstantFPBuildVectorOrConstantFP(N0) && 10645 !isConstantFPBuildVectorOrConstantFP(N1)) 10646 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10647 10648 return SDValue(); 10649 } 10650 10651 SDValue DAGCombiner::visitFABS(SDNode *N) { 10652 SDValue N0 = N->getOperand(0); 10653 EVT VT = N->getValueType(0); 10654 10655 // fold (fabs c1) -> fabs(c1) 10656 if (isConstantFPBuildVectorOrConstantFP(N0)) 10657 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10658 10659 // fold (fabs (fabs x)) -> (fabs x) 10660 if (N0.getOpcode() == ISD::FABS) 10661 return N->getOperand(0); 10662 10663 // fold (fabs (fneg x)) -> (fabs x) 10664 // fold (fabs (fcopysign x, y)) -> (fabs x) 10665 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10666 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10667 10668 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10669 // constant pool values. 10670 if (!TLI.isFAbsFree(VT) && 10671 N0.getOpcode() == ISD::BITCAST && 10672 N0.getNode()->hasOneUse()) { 10673 SDValue Int = N0.getOperand(0); 10674 EVT IntVT = Int.getValueType(); 10675 if (IntVT.isInteger() && !IntVT.isVector()) { 10676 APInt SignMask; 10677 if (N0.getValueType().isVector()) { 10678 // For a vector, get a mask such as 0x7f... per scalar element 10679 // and splat it. 10680 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 10681 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10682 } else { 10683 // For a scalar, just generate 0x7f... 10684 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 10685 } 10686 SDLoc DL(N0); 10687 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10688 DAG.getConstant(SignMask, DL, IntVT)); 10689 AddToWorklist(Int.getNode()); 10690 return DAG.getBitcast(N->getValueType(0), Int); 10691 } 10692 } 10693 10694 return SDValue(); 10695 } 10696 10697 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10698 SDValue Chain = N->getOperand(0); 10699 SDValue N1 = N->getOperand(1); 10700 SDValue N2 = N->getOperand(2); 10701 10702 // If N is a constant we could fold this into a fallthrough or unconditional 10703 // branch. However that doesn't happen very often in normal code, because 10704 // Instcombine/SimplifyCFG should have handled the available opportunities. 10705 // If we did this folding here, it would be necessary to update the 10706 // MachineBasicBlock CFG, which is awkward. 10707 10708 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10709 // on the target. 10710 if (N1.getOpcode() == ISD::SETCC && 10711 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10712 N1.getOperand(0).getValueType())) { 10713 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10714 Chain, N1.getOperand(2), 10715 N1.getOperand(0), N1.getOperand(1), N2); 10716 } 10717 10718 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10719 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10720 (N1.getOperand(0).hasOneUse() && 10721 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10722 SDNode *Trunc = nullptr; 10723 if (N1.getOpcode() == ISD::TRUNCATE) { 10724 // Look pass the truncate. 10725 Trunc = N1.getNode(); 10726 N1 = N1.getOperand(0); 10727 } 10728 10729 // Match this pattern so that we can generate simpler code: 10730 // 10731 // %a = ... 10732 // %b = and i32 %a, 2 10733 // %c = srl i32 %b, 1 10734 // brcond i32 %c ... 10735 // 10736 // into 10737 // 10738 // %a = ... 10739 // %b = and i32 %a, 2 10740 // %c = setcc eq %b, 0 10741 // brcond %c ... 10742 // 10743 // This applies only when the AND constant value has one bit set and the 10744 // SRL constant is equal to the log2 of the AND constant. The back-end is 10745 // smart enough to convert the result into a TEST/JMP sequence. 10746 SDValue Op0 = N1.getOperand(0); 10747 SDValue Op1 = N1.getOperand(1); 10748 10749 if (Op0.getOpcode() == ISD::AND && 10750 Op1.getOpcode() == ISD::Constant) { 10751 SDValue AndOp1 = Op0.getOperand(1); 10752 10753 if (AndOp1.getOpcode() == ISD::Constant) { 10754 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10755 10756 if (AndConst.isPowerOf2() && 10757 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10758 SDLoc DL(N); 10759 SDValue SetCC = 10760 DAG.getSetCC(DL, 10761 getSetCCResultType(Op0.getValueType()), 10762 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10763 ISD::SETNE); 10764 10765 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10766 MVT::Other, Chain, SetCC, N2); 10767 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10768 // will convert it back to (X & C1) >> C2. 10769 CombineTo(N, NewBRCond, false); 10770 // Truncate is dead. 10771 if (Trunc) 10772 deleteAndRecombine(Trunc); 10773 // Replace the uses of SRL with SETCC 10774 WorklistRemover DeadNodes(*this); 10775 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10776 deleteAndRecombine(N1.getNode()); 10777 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10778 } 10779 } 10780 } 10781 10782 if (Trunc) 10783 // Restore N1 if the above transformation doesn't match. 10784 N1 = N->getOperand(1); 10785 } 10786 10787 // Transform br(xor(x, y)) -> br(x != y) 10788 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10789 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10790 SDNode *TheXor = N1.getNode(); 10791 SDValue Op0 = TheXor->getOperand(0); 10792 SDValue Op1 = TheXor->getOperand(1); 10793 if (Op0.getOpcode() == Op1.getOpcode()) { 10794 // Avoid missing important xor optimizations. 10795 if (SDValue Tmp = visitXOR(TheXor)) { 10796 if (Tmp.getNode() != TheXor) { 10797 DEBUG(dbgs() << "\nReplacing.8 "; 10798 TheXor->dump(&DAG); 10799 dbgs() << "\nWith: "; 10800 Tmp.getNode()->dump(&DAG); 10801 dbgs() << '\n'); 10802 WorklistRemover DeadNodes(*this); 10803 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10804 deleteAndRecombine(TheXor); 10805 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10806 MVT::Other, Chain, Tmp, N2); 10807 } 10808 10809 // visitXOR has changed XOR's operands or replaced the XOR completely, 10810 // bail out. 10811 return SDValue(N, 0); 10812 } 10813 } 10814 10815 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10816 bool Equal = false; 10817 if (isOneConstant(Op0) && Op0.hasOneUse() && 10818 Op0.getOpcode() == ISD::XOR) { 10819 TheXor = Op0.getNode(); 10820 Equal = true; 10821 } 10822 10823 EVT SetCCVT = N1.getValueType(); 10824 if (LegalTypes) 10825 SetCCVT = getSetCCResultType(SetCCVT); 10826 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10827 SetCCVT, 10828 Op0, Op1, 10829 Equal ? ISD::SETEQ : ISD::SETNE); 10830 // Replace the uses of XOR with SETCC 10831 WorklistRemover DeadNodes(*this); 10832 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10833 deleteAndRecombine(N1.getNode()); 10834 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10835 MVT::Other, Chain, SetCC, N2); 10836 } 10837 } 10838 10839 return SDValue(); 10840 } 10841 10842 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10843 // 10844 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10845 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10846 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10847 10848 // If N is a constant we could fold this into a fallthrough or unconditional 10849 // branch. However that doesn't happen very often in normal code, because 10850 // Instcombine/SimplifyCFG should have handled the available opportunities. 10851 // If we did this folding here, it would be necessary to update the 10852 // MachineBasicBlock CFG, which is awkward. 10853 10854 // Use SimplifySetCC to simplify SETCC's. 10855 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10856 CondLHS, CondRHS, CC->get(), SDLoc(N), 10857 false); 10858 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10859 10860 // fold to a simpler setcc 10861 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10862 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10863 N->getOperand(0), Simp.getOperand(2), 10864 Simp.getOperand(0), Simp.getOperand(1), 10865 N->getOperand(4)); 10866 10867 return SDValue(); 10868 } 10869 10870 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10871 /// and that N may be folded in the load / store addressing mode. 10872 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10873 SelectionDAG &DAG, 10874 const TargetLowering &TLI) { 10875 EVT VT; 10876 unsigned AS; 10877 10878 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10879 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10880 return false; 10881 VT = LD->getMemoryVT(); 10882 AS = LD->getAddressSpace(); 10883 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10884 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10885 return false; 10886 VT = ST->getMemoryVT(); 10887 AS = ST->getAddressSpace(); 10888 } else 10889 return false; 10890 10891 TargetLowering::AddrMode AM; 10892 if (N->getOpcode() == ISD::ADD) { 10893 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10894 if (Offset) 10895 // [reg +/- imm] 10896 AM.BaseOffs = Offset->getSExtValue(); 10897 else 10898 // [reg +/- reg] 10899 AM.Scale = 1; 10900 } else if (N->getOpcode() == ISD::SUB) { 10901 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10902 if (Offset) 10903 // [reg +/- imm] 10904 AM.BaseOffs = -Offset->getSExtValue(); 10905 else 10906 // [reg +/- reg] 10907 AM.Scale = 1; 10908 } else 10909 return false; 10910 10911 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10912 VT.getTypeForEVT(*DAG.getContext()), AS); 10913 } 10914 10915 /// Try turning a load/store into a pre-indexed load/store when the base 10916 /// pointer is an add or subtract and it has other uses besides the load/store. 10917 /// After the transformation, the new indexed load/store has effectively folded 10918 /// the add/subtract in and all of its other uses are redirected to the 10919 /// new load/store. 10920 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10921 if (Level < AfterLegalizeDAG) 10922 return false; 10923 10924 bool isLoad = true; 10925 SDValue Ptr; 10926 EVT VT; 10927 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10928 if (LD->isIndexed()) 10929 return false; 10930 VT = LD->getMemoryVT(); 10931 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10932 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10933 return false; 10934 Ptr = LD->getBasePtr(); 10935 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10936 if (ST->isIndexed()) 10937 return false; 10938 VT = ST->getMemoryVT(); 10939 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10940 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10941 return false; 10942 Ptr = ST->getBasePtr(); 10943 isLoad = false; 10944 } else { 10945 return false; 10946 } 10947 10948 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10949 // out. There is no reason to make this a preinc/predec. 10950 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10951 Ptr.getNode()->hasOneUse()) 10952 return false; 10953 10954 // Ask the target to do addressing mode selection. 10955 SDValue BasePtr; 10956 SDValue Offset; 10957 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10958 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10959 return false; 10960 10961 // Backends without true r+i pre-indexed forms may need to pass a 10962 // constant base with a variable offset so that constant coercion 10963 // will work with the patterns in canonical form. 10964 bool Swapped = false; 10965 if (isa<ConstantSDNode>(BasePtr)) { 10966 std::swap(BasePtr, Offset); 10967 Swapped = true; 10968 } 10969 10970 // Don't create a indexed load / store with zero offset. 10971 if (isNullConstant(Offset)) 10972 return false; 10973 10974 // Try turning it into a pre-indexed load / store except when: 10975 // 1) The new base ptr is a frame index. 10976 // 2) If N is a store and the new base ptr is either the same as or is a 10977 // predecessor of the value being stored. 10978 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10979 // that would create a cycle. 10980 // 4) All uses are load / store ops that use it as old base ptr. 10981 10982 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10983 // (plus the implicit offset) to a register to preinc anyway. 10984 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10985 return false; 10986 10987 // Check #2. 10988 if (!isLoad) { 10989 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10990 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10991 return false; 10992 } 10993 10994 // Caches for hasPredecessorHelper. 10995 SmallPtrSet<const SDNode *, 32> Visited; 10996 SmallVector<const SDNode *, 16> Worklist; 10997 Worklist.push_back(N); 10998 10999 // If the offset is a constant, there may be other adds of constants that 11000 // can be folded with this one. We should do this to avoid having to keep 11001 // a copy of the original base pointer. 11002 SmallVector<SDNode *, 16> OtherUses; 11003 if (isa<ConstantSDNode>(Offset)) 11004 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 11005 UE = BasePtr.getNode()->use_end(); 11006 UI != UE; ++UI) { 11007 SDUse &Use = UI.getUse(); 11008 // Skip the use that is Ptr and uses of other results from BasePtr's 11009 // node (important for nodes that return multiple results). 11010 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 11011 continue; 11012 11013 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 11014 continue; 11015 11016 if (Use.getUser()->getOpcode() != ISD::ADD && 11017 Use.getUser()->getOpcode() != ISD::SUB) { 11018 OtherUses.clear(); 11019 break; 11020 } 11021 11022 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 11023 if (!isa<ConstantSDNode>(Op1)) { 11024 OtherUses.clear(); 11025 break; 11026 } 11027 11028 // FIXME: In some cases, we can be smarter about this. 11029 if (Op1.getValueType() != Offset.getValueType()) { 11030 OtherUses.clear(); 11031 break; 11032 } 11033 11034 OtherUses.push_back(Use.getUser()); 11035 } 11036 11037 if (Swapped) 11038 std::swap(BasePtr, Offset); 11039 11040 // Now check for #3 and #4. 11041 bool RealUse = false; 11042 11043 for (SDNode *Use : Ptr.getNode()->uses()) { 11044 if (Use == N) 11045 continue; 11046 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11047 return false; 11048 11049 // If Ptr may be folded in addressing mode of other use, then it's 11050 // not profitable to do this transformation. 11051 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11052 RealUse = true; 11053 } 11054 11055 if (!RealUse) 11056 return false; 11057 11058 SDValue Result; 11059 if (isLoad) 11060 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11061 BasePtr, Offset, AM); 11062 else 11063 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11064 BasePtr, Offset, AM); 11065 ++PreIndexedNodes; 11066 ++NodesCombined; 11067 DEBUG(dbgs() << "\nReplacing.4 "; 11068 N->dump(&DAG); 11069 dbgs() << "\nWith: "; 11070 Result.getNode()->dump(&DAG); 11071 dbgs() << '\n'); 11072 WorklistRemover DeadNodes(*this); 11073 if (isLoad) { 11074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11075 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11076 } else { 11077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11078 } 11079 11080 // Finally, since the node is now dead, remove it from the graph. 11081 deleteAndRecombine(N); 11082 11083 if (Swapped) 11084 std::swap(BasePtr, Offset); 11085 11086 // Replace other uses of BasePtr that can be updated to use Ptr 11087 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11088 unsigned OffsetIdx = 1; 11089 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11090 OffsetIdx = 0; 11091 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11092 BasePtr.getNode() && "Expected BasePtr operand"); 11093 11094 // We need to replace ptr0 in the following expression: 11095 // x0 * offset0 + y0 * ptr0 = t0 11096 // knowing that 11097 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11098 // 11099 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11100 // indexed load/store and the expresion that needs to be re-written. 11101 // 11102 // Therefore, we have: 11103 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11104 11105 ConstantSDNode *CN = 11106 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11107 int X0, X1, Y0, Y1; 11108 const APInt &Offset0 = CN->getAPIntValue(); 11109 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11110 11111 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11112 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11113 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11114 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11115 11116 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11117 11118 APInt CNV = Offset0; 11119 if (X0 < 0) CNV = -CNV; 11120 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11121 else CNV = CNV - Offset1; 11122 11123 SDLoc DL(OtherUses[i]); 11124 11125 // We can now generate the new expression. 11126 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11127 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11128 11129 SDValue NewUse = DAG.getNode(Opcode, 11130 DL, 11131 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11132 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11133 deleteAndRecombine(OtherUses[i]); 11134 } 11135 11136 // Replace the uses of Ptr with uses of the updated base value. 11137 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11138 deleteAndRecombine(Ptr.getNode()); 11139 11140 return true; 11141 } 11142 11143 /// Try to combine a load/store with a add/sub of the base pointer node into a 11144 /// post-indexed load/store. The transformation folded the add/subtract into the 11145 /// new indexed load/store effectively and all of its uses are redirected to the 11146 /// new load/store. 11147 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11148 if (Level < AfterLegalizeDAG) 11149 return false; 11150 11151 bool isLoad = true; 11152 SDValue Ptr; 11153 EVT VT; 11154 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11155 if (LD->isIndexed()) 11156 return false; 11157 VT = LD->getMemoryVT(); 11158 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11159 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11160 return false; 11161 Ptr = LD->getBasePtr(); 11162 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11163 if (ST->isIndexed()) 11164 return false; 11165 VT = ST->getMemoryVT(); 11166 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11167 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11168 return false; 11169 Ptr = ST->getBasePtr(); 11170 isLoad = false; 11171 } else { 11172 return false; 11173 } 11174 11175 if (Ptr.getNode()->hasOneUse()) 11176 return false; 11177 11178 for (SDNode *Op : Ptr.getNode()->uses()) { 11179 if (Op == N || 11180 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11181 continue; 11182 11183 SDValue BasePtr; 11184 SDValue Offset; 11185 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11186 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11187 // Don't create a indexed load / store with zero offset. 11188 if (isNullConstant(Offset)) 11189 continue; 11190 11191 // Try turning it into a post-indexed load / store except when 11192 // 1) All uses are load / store ops that use it as base ptr (and 11193 // it may be folded as addressing mmode). 11194 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11195 // nor a successor of N. Otherwise, if Op is folded that would 11196 // create a cycle. 11197 11198 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11199 continue; 11200 11201 // Check for #1. 11202 bool TryNext = false; 11203 for (SDNode *Use : BasePtr.getNode()->uses()) { 11204 if (Use == Ptr.getNode()) 11205 continue; 11206 11207 // If all the uses are load / store addresses, then don't do the 11208 // transformation. 11209 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11210 bool RealUse = false; 11211 for (SDNode *UseUse : Use->uses()) { 11212 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11213 RealUse = true; 11214 } 11215 11216 if (!RealUse) { 11217 TryNext = true; 11218 break; 11219 } 11220 } 11221 } 11222 11223 if (TryNext) 11224 continue; 11225 11226 // Check for #2 11227 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11228 SDValue Result = isLoad 11229 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11230 BasePtr, Offset, AM) 11231 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11232 BasePtr, Offset, AM); 11233 ++PostIndexedNodes; 11234 ++NodesCombined; 11235 DEBUG(dbgs() << "\nReplacing.5 "; 11236 N->dump(&DAG); 11237 dbgs() << "\nWith: "; 11238 Result.getNode()->dump(&DAG); 11239 dbgs() << '\n'); 11240 WorklistRemover DeadNodes(*this); 11241 if (isLoad) { 11242 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11243 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11244 } else { 11245 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11246 } 11247 11248 // Finally, since the node is now dead, remove it from the graph. 11249 deleteAndRecombine(N); 11250 11251 // Replace the uses of Use with uses of the updated base value. 11252 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11253 Result.getValue(isLoad ? 1 : 0)); 11254 deleteAndRecombine(Op); 11255 return true; 11256 } 11257 } 11258 } 11259 11260 return false; 11261 } 11262 11263 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11264 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11265 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11266 assert(AM != ISD::UNINDEXED); 11267 SDValue BP = LD->getOperand(1); 11268 SDValue Inc = LD->getOperand(2); 11269 11270 // Some backends use TargetConstants for load offsets, but don't expect 11271 // TargetConstants in general ADD nodes. We can convert these constants into 11272 // regular Constants (if the constant is not opaque). 11273 assert((Inc.getOpcode() != ISD::TargetConstant || 11274 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11275 "Cannot split out indexing using opaque target constants"); 11276 if (Inc.getOpcode() == ISD::TargetConstant) { 11277 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11278 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11279 ConstInc->getValueType(0)); 11280 } 11281 11282 unsigned Opc = 11283 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11284 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11285 } 11286 11287 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11288 LoadSDNode *LD = cast<LoadSDNode>(N); 11289 SDValue Chain = LD->getChain(); 11290 SDValue Ptr = LD->getBasePtr(); 11291 11292 // If load is not volatile and there are no uses of the loaded value (and 11293 // the updated indexed value in case of indexed loads), change uses of the 11294 // chain value into uses of the chain input (i.e. delete the dead load). 11295 if (!LD->isVolatile()) { 11296 if (N->getValueType(1) == MVT::Other) { 11297 // Unindexed loads. 11298 if (!N->hasAnyUseOfValue(0)) { 11299 // It's not safe to use the two value CombineTo variant here. e.g. 11300 // v1, chain2 = load chain1, loc 11301 // v2, chain3 = load chain2, loc 11302 // v3 = add v2, c 11303 // Now we replace use of chain2 with chain1. This makes the second load 11304 // isomorphic to the one we are deleting, and thus makes this load live. 11305 DEBUG(dbgs() << "\nReplacing.6 "; 11306 N->dump(&DAG); 11307 dbgs() << "\nWith chain: "; 11308 Chain.getNode()->dump(&DAG); 11309 dbgs() << "\n"); 11310 WorklistRemover DeadNodes(*this); 11311 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11312 AddUsersToWorklist(Chain.getNode()); 11313 if (N->use_empty()) 11314 deleteAndRecombine(N); 11315 11316 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11317 } 11318 } else { 11319 // Indexed loads. 11320 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11321 11322 // If this load has an opaque TargetConstant offset, then we cannot split 11323 // the indexing into an add/sub directly (that TargetConstant may not be 11324 // valid for a different type of node, and we cannot convert an opaque 11325 // target constant into a regular constant). 11326 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11327 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11328 11329 if (!N->hasAnyUseOfValue(0) && 11330 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11331 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11332 SDValue Index; 11333 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11334 Index = SplitIndexingFromLoad(LD); 11335 // Try to fold the base pointer arithmetic into subsequent loads and 11336 // stores. 11337 AddUsersToWorklist(N); 11338 } else 11339 Index = DAG.getUNDEF(N->getValueType(1)); 11340 DEBUG(dbgs() << "\nReplacing.7 "; 11341 N->dump(&DAG); 11342 dbgs() << "\nWith: "; 11343 Undef.getNode()->dump(&DAG); 11344 dbgs() << " and 2 other values\n"); 11345 WorklistRemover DeadNodes(*this); 11346 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11347 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11348 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11349 deleteAndRecombine(N); 11350 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11351 } 11352 } 11353 } 11354 11355 // If this load is directly stored, replace the load value with the stored 11356 // value. 11357 // TODO: Handle store large -> read small portion. 11358 // TODO: Handle TRUNCSTORE/LOADEXT 11359 if (OptLevel != CodeGenOpt::None && 11360 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11361 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11362 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11363 if (PrevST->getBasePtr() == Ptr && 11364 PrevST->getValue().getValueType() == N->getValueType(0)) 11365 return CombineTo(N, PrevST->getOperand(1), Chain); 11366 } 11367 } 11368 11369 // Try to infer better alignment information than the load already has. 11370 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11371 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11372 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11373 SDValue NewLoad = DAG.getExtLoad( 11374 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11375 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11376 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11377 if (NewLoad.getNode() != N) 11378 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11379 } 11380 } 11381 } 11382 11383 if (LD->isUnindexed()) { 11384 // Walk up chain skipping non-aliasing memory nodes. 11385 SDValue BetterChain = FindBetterChain(N, Chain); 11386 11387 // If there is a better chain. 11388 if (Chain != BetterChain) { 11389 SDValue ReplLoad; 11390 11391 // Replace the chain to void dependency. 11392 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11393 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11394 BetterChain, Ptr, LD->getMemOperand()); 11395 } else { 11396 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11397 LD->getValueType(0), 11398 BetterChain, Ptr, LD->getMemoryVT(), 11399 LD->getMemOperand()); 11400 } 11401 11402 // Create token factor to keep old chain connected. 11403 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11404 MVT::Other, Chain, ReplLoad.getValue(1)); 11405 11406 // Make sure the new and old chains are cleaned up. 11407 AddToWorklist(Token.getNode()); 11408 11409 // Replace uses with load result and token factor. Don't add users 11410 // to work list. 11411 return CombineTo(N, ReplLoad.getValue(0), Token, false); 11412 } 11413 } 11414 11415 // Try transforming N to an indexed load. 11416 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11417 return SDValue(N, 0); 11418 11419 // Try to slice up N to more direct loads if the slices are mapped to 11420 // different register banks or pairing can take place. 11421 if (SliceUpLoad(N)) 11422 return SDValue(N, 0); 11423 11424 return SDValue(); 11425 } 11426 11427 namespace { 11428 /// \brief Helper structure used to slice a load in smaller loads. 11429 /// Basically a slice is obtained from the following sequence: 11430 /// Origin = load Ty1, Base 11431 /// Shift = srl Ty1 Origin, CstTy Amount 11432 /// Inst = trunc Shift to Ty2 11433 /// 11434 /// Then, it will be rewriten into: 11435 /// Slice = load SliceTy, Base + SliceOffset 11436 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11437 /// 11438 /// SliceTy is deduced from the number of bits that are actually used to 11439 /// build Inst. 11440 struct LoadedSlice { 11441 /// \brief Helper structure used to compute the cost of a slice. 11442 struct Cost { 11443 /// Are we optimizing for code size. 11444 bool ForCodeSize; 11445 /// Various cost. 11446 unsigned Loads; 11447 unsigned Truncates; 11448 unsigned CrossRegisterBanksCopies; 11449 unsigned ZExts; 11450 unsigned Shift; 11451 11452 Cost(bool ForCodeSize = false) 11453 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 11454 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 11455 11456 /// \brief Get the cost of one isolated slice. 11457 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11458 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 11459 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 11460 EVT TruncType = LS.Inst->getValueType(0); 11461 EVT LoadedType = LS.getLoadedType(); 11462 if (TruncType != LoadedType && 11463 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11464 ZExts = 1; 11465 } 11466 11467 /// \brief Account for slicing gain in the current cost. 11468 /// Slicing provide a few gains like removing a shift or a 11469 /// truncate. This method allows to grow the cost of the original 11470 /// load with the gain from this slice. 11471 void addSliceGain(const LoadedSlice &LS) { 11472 // Each slice saves a truncate. 11473 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11474 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11475 LS.Inst->getValueType(0))) 11476 ++Truncates; 11477 // If there is a shift amount, this slice gets rid of it. 11478 if (LS.Shift) 11479 ++Shift; 11480 // If this slice can merge a cross register bank copy, account for it. 11481 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11482 ++CrossRegisterBanksCopies; 11483 } 11484 11485 Cost &operator+=(const Cost &RHS) { 11486 Loads += RHS.Loads; 11487 Truncates += RHS.Truncates; 11488 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11489 ZExts += RHS.ZExts; 11490 Shift += RHS.Shift; 11491 return *this; 11492 } 11493 11494 bool operator==(const Cost &RHS) const { 11495 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11496 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11497 ZExts == RHS.ZExts && Shift == RHS.Shift; 11498 } 11499 11500 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11501 11502 bool operator<(const Cost &RHS) const { 11503 // Assume cross register banks copies are as expensive as loads. 11504 // FIXME: Do we want some more target hooks? 11505 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11506 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11507 // Unless we are optimizing for code size, consider the 11508 // expensive operation first. 11509 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11510 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11511 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11512 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11513 } 11514 11515 bool operator>(const Cost &RHS) const { return RHS < *this; } 11516 11517 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11518 11519 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11520 }; 11521 // The last instruction that represent the slice. This should be a 11522 // truncate instruction. 11523 SDNode *Inst; 11524 // The original load instruction. 11525 LoadSDNode *Origin; 11526 // The right shift amount in bits from the original load. 11527 unsigned Shift; 11528 // The DAG from which Origin came from. 11529 // This is used to get some contextual information about legal types, etc. 11530 SelectionDAG *DAG; 11531 11532 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11533 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11534 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11535 11536 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11537 /// \return Result is \p BitWidth and has used bits set to 1 and 11538 /// not used bits set to 0. 11539 APInt getUsedBits() const { 11540 // Reproduce the trunc(lshr) sequence: 11541 // - Start from the truncated value. 11542 // - Zero extend to the desired bit width. 11543 // - Shift left. 11544 assert(Origin && "No original load to compare against."); 11545 unsigned BitWidth = Origin->getValueSizeInBits(0); 11546 assert(Inst && "This slice is not bound to an instruction"); 11547 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11548 "Extracted slice is bigger than the whole type!"); 11549 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11550 UsedBits.setAllBits(); 11551 UsedBits = UsedBits.zext(BitWidth); 11552 UsedBits <<= Shift; 11553 return UsedBits; 11554 } 11555 11556 /// \brief Get the size of the slice to be loaded in bytes. 11557 unsigned getLoadedSize() const { 11558 unsigned SliceSize = getUsedBits().countPopulation(); 11559 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11560 return SliceSize / 8; 11561 } 11562 11563 /// \brief Get the type that will be loaded for this slice. 11564 /// Note: This may not be the final type for the slice. 11565 EVT getLoadedType() const { 11566 assert(DAG && "Missing context"); 11567 LLVMContext &Ctxt = *DAG->getContext(); 11568 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11569 } 11570 11571 /// \brief Get the alignment of the load used for this slice. 11572 unsigned getAlignment() const { 11573 unsigned Alignment = Origin->getAlignment(); 11574 unsigned Offset = getOffsetFromBase(); 11575 if (Offset != 0) 11576 Alignment = MinAlign(Alignment, Alignment + Offset); 11577 return Alignment; 11578 } 11579 11580 /// \brief Check if this slice can be rewritten with legal operations. 11581 bool isLegal() const { 11582 // An invalid slice is not legal. 11583 if (!Origin || !Inst || !DAG) 11584 return false; 11585 11586 // Offsets are for indexed load only, we do not handle that. 11587 if (!Origin->getOffset().isUndef()) 11588 return false; 11589 11590 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11591 11592 // Check that the type is legal. 11593 EVT SliceType = getLoadedType(); 11594 if (!TLI.isTypeLegal(SliceType)) 11595 return false; 11596 11597 // Check that the load is legal for this type. 11598 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11599 return false; 11600 11601 // Check that the offset can be computed. 11602 // 1. Check its type. 11603 EVT PtrType = Origin->getBasePtr().getValueType(); 11604 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11605 return false; 11606 11607 // 2. Check that it fits in the immediate. 11608 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11609 return false; 11610 11611 // 3. Check that the computation is legal. 11612 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11613 return false; 11614 11615 // Check that the zext is legal if it needs one. 11616 EVT TruncateType = Inst->getValueType(0); 11617 if (TruncateType != SliceType && 11618 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11619 return false; 11620 11621 return true; 11622 } 11623 11624 /// \brief Get the offset in bytes of this slice in the original chunk of 11625 /// bits. 11626 /// \pre DAG != nullptr. 11627 uint64_t getOffsetFromBase() const { 11628 assert(DAG && "Missing context."); 11629 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11630 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11631 uint64_t Offset = Shift / 8; 11632 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11633 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11634 "The size of the original loaded type is not a multiple of a" 11635 " byte."); 11636 // If Offset is bigger than TySizeInBytes, it means we are loading all 11637 // zeros. This should have been optimized before in the process. 11638 assert(TySizeInBytes > Offset && 11639 "Invalid shift amount for given loaded size"); 11640 if (IsBigEndian) 11641 Offset = TySizeInBytes - Offset - getLoadedSize(); 11642 return Offset; 11643 } 11644 11645 /// \brief Generate the sequence of instructions to load the slice 11646 /// represented by this object and redirect the uses of this slice to 11647 /// this new sequence of instructions. 11648 /// \pre this->Inst && this->Origin are valid Instructions and this 11649 /// object passed the legal check: LoadedSlice::isLegal returned true. 11650 /// \return The last instruction of the sequence used to load the slice. 11651 SDValue loadSlice() const { 11652 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11653 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11654 SDValue BaseAddr = OldBaseAddr; 11655 // Get the offset in that chunk of bytes w.r.t. the endianness. 11656 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11657 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11658 if (Offset) { 11659 // BaseAddr = BaseAddr + Offset. 11660 EVT ArithType = BaseAddr.getValueType(); 11661 SDLoc DL(Origin); 11662 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11663 DAG->getConstant(Offset, DL, ArithType)); 11664 } 11665 11666 // Create the type of the loaded slice according to its size. 11667 EVT SliceType = getLoadedType(); 11668 11669 // Create the load for the slice. 11670 SDValue LastInst = 11671 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11672 Origin->getPointerInfo().getWithOffset(Offset), 11673 getAlignment(), Origin->getMemOperand()->getFlags()); 11674 // If the final type is not the same as the loaded type, this means that 11675 // we have to pad with zero. Create a zero extend for that. 11676 EVT FinalType = Inst->getValueType(0); 11677 if (SliceType != FinalType) 11678 LastInst = 11679 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11680 return LastInst; 11681 } 11682 11683 /// \brief Check if this slice can be merged with an expensive cross register 11684 /// bank copy. E.g., 11685 /// i = load i32 11686 /// f = bitcast i32 i to float 11687 bool canMergeExpensiveCrossRegisterBankCopy() const { 11688 if (!Inst || !Inst->hasOneUse()) 11689 return false; 11690 SDNode *Use = *Inst->use_begin(); 11691 if (Use->getOpcode() != ISD::BITCAST) 11692 return false; 11693 assert(DAG && "Missing context"); 11694 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11695 EVT ResVT = Use->getValueType(0); 11696 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11697 const TargetRegisterClass *ArgRC = 11698 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11699 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11700 return false; 11701 11702 // At this point, we know that we perform a cross-register-bank copy. 11703 // Check if it is expensive. 11704 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11705 // Assume bitcasts are cheap, unless both register classes do not 11706 // explicitly share a common sub class. 11707 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11708 return false; 11709 11710 // Check if it will be merged with the load. 11711 // 1. Check the alignment constraint. 11712 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11713 ResVT.getTypeForEVT(*DAG->getContext())); 11714 11715 if (RequiredAlignment > getAlignment()) 11716 return false; 11717 11718 // 2. Check that the load is a legal operation for that type. 11719 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11720 return false; 11721 11722 // 3. Check that we do not have a zext in the way. 11723 if (Inst->getValueType(0) != getLoadedType()) 11724 return false; 11725 11726 return true; 11727 } 11728 }; 11729 } 11730 11731 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11732 /// \p UsedBits looks like 0..0 1..1 0..0. 11733 static bool areUsedBitsDense(const APInt &UsedBits) { 11734 // If all the bits are one, this is dense! 11735 if (UsedBits.isAllOnesValue()) 11736 return true; 11737 11738 // Get rid of the unused bits on the right. 11739 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11740 // Get rid of the unused bits on the left. 11741 if (NarrowedUsedBits.countLeadingZeros()) 11742 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11743 // Check that the chunk of bits is completely used. 11744 return NarrowedUsedBits.isAllOnesValue(); 11745 } 11746 11747 /// \brief Check whether or not \p First and \p Second are next to each other 11748 /// in memory. This means that there is no hole between the bits loaded 11749 /// by \p First and the bits loaded by \p Second. 11750 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11751 const LoadedSlice &Second) { 11752 assert(First.Origin == Second.Origin && First.Origin && 11753 "Unable to match different memory origins."); 11754 APInt UsedBits = First.getUsedBits(); 11755 assert((UsedBits & Second.getUsedBits()) == 0 && 11756 "Slices are not supposed to overlap."); 11757 UsedBits |= Second.getUsedBits(); 11758 return areUsedBitsDense(UsedBits); 11759 } 11760 11761 /// \brief Adjust the \p GlobalLSCost according to the target 11762 /// paring capabilities and the layout of the slices. 11763 /// \pre \p GlobalLSCost should account for at least as many loads as 11764 /// there is in the slices in \p LoadedSlices. 11765 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11766 LoadedSlice::Cost &GlobalLSCost) { 11767 unsigned NumberOfSlices = LoadedSlices.size(); 11768 // If there is less than 2 elements, no pairing is possible. 11769 if (NumberOfSlices < 2) 11770 return; 11771 11772 // Sort the slices so that elements that are likely to be next to each 11773 // other in memory are next to each other in the list. 11774 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11775 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11776 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11777 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11778 }); 11779 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11780 // First (resp. Second) is the first (resp. Second) potentially candidate 11781 // to be placed in a paired load. 11782 const LoadedSlice *First = nullptr; 11783 const LoadedSlice *Second = nullptr; 11784 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11785 // Set the beginning of the pair. 11786 First = Second) { 11787 11788 Second = &LoadedSlices[CurrSlice]; 11789 11790 // If First is NULL, it means we start a new pair. 11791 // Get to the next slice. 11792 if (!First) 11793 continue; 11794 11795 EVT LoadedType = First->getLoadedType(); 11796 11797 // If the types of the slices are different, we cannot pair them. 11798 if (LoadedType != Second->getLoadedType()) 11799 continue; 11800 11801 // Check if the target supplies paired loads for this type. 11802 unsigned RequiredAlignment = 0; 11803 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11804 // move to the next pair, this type is hopeless. 11805 Second = nullptr; 11806 continue; 11807 } 11808 // Check if we meet the alignment requirement. 11809 if (RequiredAlignment > First->getAlignment()) 11810 continue; 11811 11812 // Check that both loads are next to each other in memory. 11813 if (!areSlicesNextToEachOther(*First, *Second)) 11814 continue; 11815 11816 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11817 --GlobalLSCost.Loads; 11818 // Move to the next pair. 11819 Second = nullptr; 11820 } 11821 } 11822 11823 /// \brief Check the profitability of all involved LoadedSlice. 11824 /// Currently, it is considered profitable if there is exactly two 11825 /// involved slices (1) which are (2) next to each other in memory, and 11826 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11827 /// 11828 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11829 /// the elements themselves. 11830 /// 11831 /// FIXME: When the cost model will be mature enough, we can relax 11832 /// constraints (1) and (2). 11833 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11834 const APInt &UsedBits, bool ForCodeSize) { 11835 unsigned NumberOfSlices = LoadedSlices.size(); 11836 if (StressLoadSlicing) 11837 return NumberOfSlices > 1; 11838 11839 // Check (1). 11840 if (NumberOfSlices != 2) 11841 return false; 11842 11843 // Check (2). 11844 if (!areUsedBitsDense(UsedBits)) 11845 return false; 11846 11847 // Check (3). 11848 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11849 // The original code has one big load. 11850 OrigCost.Loads = 1; 11851 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11852 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11853 // Accumulate the cost of all the slices. 11854 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11855 GlobalSlicingCost += SliceCost; 11856 11857 // Account as cost in the original configuration the gain obtained 11858 // with the current slices. 11859 OrigCost.addSliceGain(LS); 11860 } 11861 11862 // If the target supports paired load, adjust the cost accordingly. 11863 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11864 return OrigCost > GlobalSlicingCost; 11865 } 11866 11867 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11868 /// operations, split it in the various pieces being extracted. 11869 /// 11870 /// This sort of thing is introduced by SROA. 11871 /// This slicing takes care not to insert overlapping loads. 11872 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11873 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11874 if (Level < AfterLegalizeDAG) 11875 return false; 11876 11877 LoadSDNode *LD = cast<LoadSDNode>(N); 11878 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11879 !LD->getValueType(0).isInteger()) 11880 return false; 11881 11882 // Keep track of already used bits to detect overlapping values. 11883 // In that case, we will just abort the transformation. 11884 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11885 11886 SmallVector<LoadedSlice, 4> LoadedSlices; 11887 11888 // Check if this load is used as several smaller chunks of bits. 11889 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11890 // of computation for each trunc. 11891 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11892 UI != UIEnd; ++UI) { 11893 // Skip the uses of the chain. 11894 if (UI.getUse().getResNo() != 0) 11895 continue; 11896 11897 SDNode *User = *UI; 11898 unsigned Shift = 0; 11899 11900 // Check if this is a trunc(lshr). 11901 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11902 isa<ConstantSDNode>(User->getOperand(1))) { 11903 Shift = User->getConstantOperandVal(1); 11904 User = *User->use_begin(); 11905 } 11906 11907 // At this point, User is a Truncate, iff we encountered, trunc or 11908 // trunc(lshr). 11909 if (User->getOpcode() != ISD::TRUNCATE) 11910 return false; 11911 11912 // The width of the type must be a power of 2 and greater than 8-bits. 11913 // Otherwise the load cannot be represented in LLVM IR. 11914 // Moreover, if we shifted with a non-8-bits multiple, the slice 11915 // will be across several bytes. We do not support that. 11916 unsigned Width = User->getValueSizeInBits(0); 11917 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11918 return 0; 11919 11920 // Build the slice for this chain of computations. 11921 LoadedSlice LS(User, LD, Shift, &DAG); 11922 APInt CurrentUsedBits = LS.getUsedBits(); 11923 11924 // Check if this slice overlaps with another. 11925 if ((CurrentUsedBits & UsedBits) != 0) 11926 return false; 11927 // Update the bits used globally. 11928 UsedBits |= CurrentUsedBits; 11929 11930 // Check if the new slice would be legal. 11931 if (!LS.isLegal()) 11932 return false; 11933 11934 // Record the slice. 11935 LoadedSlices.push_back(LS); 11936 } 11937 11938 // Abort slicing if it does not seem to be profitable. 11939 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11940 return false; 11941 11942 ++SlicedLoads; 11943 11944 // Rewrite each chain to use an independent load. 11945 // By construction, each chain can be represented by a unique load. 11946 11947 // Prepare the argument for the new token factor for all the slices. 11948 SmallVector<SDValue, 8> ArgChains; 11949 for (SmallVectorImpl<LoadedSlice>::const_iterator 11950 LSIt = LoadedSlices.begin(), 11951 LSItEnd = LoadedSlices.end(); 11952 LSIt != LSItEnd; ++LSIt) { 11953 SDValue SliceInst = LSIt->loadSlice(); 11954 CombineTo(LSIt->Inst, SliceInst, true); 11955 if (SliceInst.getOpcode() != ISD::LOAD) 11956 SliceInst = SliceInst.getOperand(0); 11957 assert(SliceInst->getOpcode() == ISD::LOAD && 11958 "It takes more than a zext to get to the loaded slice!!"); 11959 ArgChains.push_back(SliceInst.getValue(1)); 11960 } 11961 11962 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11963 ArgChains); 11964 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11965 AddToWorklist(Chain.getNode()); 11966 return true; 11967 } 11968 11969 /// Check to see if V is (and load (ptr), imm), where the load is having 11970 /// specific bytes cleared out. If so, return the byte size being masked out 11971 /// and the shift amount. 11972 static std::pair<unsigned, unsigned> 11973 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11974 std::pair<unsigned, unsigned> Result(0, 0); 11975 11976 // Check for the structure we're looking for. 11977 if (V->getOpcode() != ISD::AND || 11978 !isa<ConstantSDNode>(V->getOperand(1)) || 11979 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11980 return Result; 11981 11982 // Check the chain and pointer. 11983 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11984 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11985 11986 // The store should be chained directly to the load or be an operand of a 11987 // tokenfactor. 11988 if (LD == Chain.getNode()) 11989 ; // ok. 11990 else if (Chain->getOpcode() != ISD::TokenFactor) 11991 return Result; // Fail. 11992 else { 11993 bool isOk = false; 11994 for (const SDValue &ChainOp : Chain->op_values()) 11995 if (ChainOp.getNode() == LD) { 11996 isOk = true; 11997 break; 11998 } 11999 if (!isOk) return Result; 12000 } 12001 12002 // This only handles simple types. 12003 if (V.getValueType() != MVT::i16 && 12004 V.getValueType() != MVT::i32 && 12005 V.getValueType() != MVT::i64) 12006 return Result; 12007 12008 // Check the constant mask. Invert it so that the bits being masked out are 12009 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 12010 // follow the sign bit for uniformity. 12011 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 12012 unsigned NotMaskLZ = countLeadingZeros(NotMask); 12013 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 12014 unsigned NotMaskTZ = countTrailingZeros(NotMask); 12015 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 12016 if (NotMaskLZ == 64) return Result; // All zero mask. 12017 12018 // See if we have a continuous run of bits. If so, we have 0*1+0* 12019 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 12020 return Result; 12021 12022 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 12023 if (V.getValueType() != MVT::i64 && NotMaskLZ) 12024 NotMaskLZ -= 64-V.getValueSizeInBits(); 12025 12026 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 12027 switch (MaskedBytes) { 12028 case 1: 12029 case 2: 12030 case 4: break; 12031 default: return Result; // All one mask, or 5-byte mask. 12032 } 12033 12034 // Verify that the first bit starts at a multiple of mask so that the access 12035 // is aligned the same as the access width. 12036 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 12037 12038 Result.first = MaskedBytes; 12039 Result.second = NotMaskTZ/8; 12040 return Result; 12041 } 12042 12043 12044 /// Check to see if IVal is something that provides a value as specified by 12045 /// MaskInfo. If so, replace the specified store with a narrower store of 12046 /// truncated IVal. 12047 static SDNode * 12048 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12049 SDValue IVal, StoreSDNode *St, 12050 DAGCombiner *DC) { 12051 unsigned NumBytes = MaskInfo.first; 12052 unsigned ByteShift = MaskInfo.second; 12053 SelectionDAG &DAG = DC->getDAG(); 12054 12055 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12056 // that uses this. If not, this is not a replacement. 12057 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12058 ByteShift*8, (ByteShift+NumBytes)*8); 12059 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12060 12061 // Check that it is legal on the target to do this. It is legal if the new 12062 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12063 // legalization. 12064 MVT VT = MVT::getIntegerVT(NumBytes*8); 12065 if (!DC->isTypeLegal(VT)) 12066 return nullptr; 12067 12068 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12069 // shifted by ByteShift and truncated down to NumBytes. 12070 if (ByteShift) { 12071 SDLoc DL(IVal); 12072 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12073 DAG.getConstant(ByteShift*8, DL, 12074 DC->getShiftAmountTy(IVal.getValueType()))); 12075 } 12076 12077 // Figure out the offset for the store and the alignment of the access. 12078 unsigned StOffset; 12079 unsigned NewAlign = St->getAlignment(); 12080 12081 if (DAG.getDataLayout().isLittleEndian()) 12082 StOffset = ByteShift; 12083 else 12084 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12085 12086 SDValue Ptr = St->getBasePtr(); 12087 if (StOffset) { 12088 SDLoc DL(IVal); 12089 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12090 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12091 NewAlign = MinAlign(NewAlign, StOffset); 12092 } 12093 12094 // Truncate down to the new size. 12095 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12096 12097 ++OpsNarrowed; 12098 return DAG 12099 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12100 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12101 .getNode(); 12102 } 12103 12104 12105 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12106 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12107 /// narrowing the load and store if it would end up being a win for performance 12108 /// or code size. 12109 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12110 StoreSDNode *ST = cast<StoreSDNode>(N); 12111 if (ST->isVolatile()) 12112 return SDValue(); 12113 12114 SDValue Chain = ST->getChain(); 12115 SDValue Value = ST->getValue(); 12116 SDValue Ptr = ST->getBasePtr(); 12117 EVT VT = Value.getValueType(); 12118 12119 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12120 return SDValue(); 12121 12122 unsigned Opc = Value.getOpcode(); 12123 12124 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12125 // is a byte mask indicating a consecutive number of bytes, check to see if 12126 // Y is known to provide just those bytes. If so, we try to replace the 12127 // load + replace + store sequence with a single (narrower) store, which makes 12128 // the load dead. 12129 if (Opc == ISD::OR) { 12130 std::pair<unsigned, unsigned> MaskedLoad; 12131 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12132 if (MaskedLoad.first) 12133 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12134 Value.getOperand(1), ST,this)) 12135 return SDValue(NewST, 0); 12136 12137 // Or is commutative, so try swapping X and Y. 12138 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12139 if (MaskedLoad.first) 12140 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12141 Value.getOperand(0), ST,this)) 12142 return SDValue(NewST, 0); 12143 } 12144 12145 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12146 Value.getOperand(1).getOpcode() != ISD::Constant) 12147 return SDValue(); 12148 12149 SDValue N0 = Value.getOperand(0); 12150 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12151 Chain == SDValue(N0.getNode(), 1)) { 12152 LoadSDNode *LD = cast<LoadSDNode>(N0); 12153 if (LD->getBasePtr() != Ptr || 12154 LD->getPointerInfo().getAddrSpace() != 12155 ST->getPointerInfo().getAddrSpace()) 12156 return SDValue(); 12157 12158 // Find the type to narrow it the load / op / store to. 12159 SDValue N1 = Value.getOperand(1); 12160 unsigned BitWidth = N1.getValueSizeInBits(); 12161 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12162 if (Opc == ISD::AND) 12163 Imm ^= APInt::getAllOnesValue(BitWidth); 12164 if (Imm == 0 || Imm.isAllOnesValue()) 12165 return SDValue(); 12166 unsigned ShAmt = Imm.countTrailingZeros(); 12167 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12168 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12169 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12170 // The narrowing should be profitable, the load/store operation should be 12171 // legal (or custom) and the store size should be equal to the NewVT width. 12172 while (NewBW < BitWidth && 12173 (NewVT.getStoreSizeInBits() != NewBW || 12174 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12175 !TLI.isNarrowingProfitable(VT, NewVT))) { 12176 NewBW = NextPowerOf2(NewBW); 12177 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12178 } 12179 if (NewBW >= BitWidth) 12180 return SDValue(); 12181 12182 // If the lsb changed does not start at the type bitwidth boundary, 12183 // start at the previous one. 12184 if (ShAmt % NewBW) 12185 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12186 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12187 std::min(BitWidth, ShAmt + NewBW)); 12188 if ((Imm & Mask) == Imm) { 12189 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12190 if (Opc == ISD::AND) 12191 NewImm ^= APInt::getAllOnesValue(NewBW); 12192 uint64_t PtrOff = ShAmt / 8; 12193 // For big endian targets, we need to adjust the offset to the pointer to 12194 // load the correct bytes. 12195 if (DAG.getDataLayout().isBigEndian()) 12196 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12197 12198 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12199 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12200 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12201 return SDValue(); 12202 12203 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12204 Ptr.getValueType(), Ptr, 12205 DAG.getConstant(PtrOff, SDLoc(LD), 12206 Ptr.getValueType())); 12207 SDValue NewLD = 12208 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12209 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12210 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12211 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12212 DAG.getConstant(NewImm, SDLoc(Value), 12213 NewVT)); 12214 SDValue NewST = 12215 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12216 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12217 12218 AddToWorklist(NewPtr.getNode()); 12219 AddToWorklist(NewLD.getNode()); 12220 AddToWorklist(NewVal.getNode()); 12221 WorklistRemover DeadNodes(*this); 12222 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12223 ++OpsNarrowed; 12224 return NewST; 12225 } 12226 } 12227 12228 return SDValue(); 12229 } 12230 12231 /// For a given floating point load / store pair, if the load value isn't used 12232 /// by any other operations, then consider transforming the pair to integer 12233 /// load / store operations if the target deems the transformation profitable. 12234 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12235 StoreSDNode *ST = cast<StoreSDNode>(N); 12236 SDValue Chain = ST->getChain(); 12237 SDValue Value = ST->getValue(); 12238 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12239 Value.hasOneUse() && 12240 Chain == SDValue(Value.getNode(), 1)) { 12241 LoadSDNode *LD = cast<LoadSDNode>(Value); 12242 EVT VT = LD->getMemoryVT(); 12243 if (!VT.isFloatingPoint() || 12244 VT != ST->getMemoryVT() || 12245 LD->isNonTemporal() || 12246 ST->isNonTemporal() || 12247 LD->getPointerInfo().getAddrSpace() != 0 || 12248 ST->getPointerInfo().getAddrSpace() != 0) 12249 return SDValue(); 12250 12251 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12252 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12253 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12254 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12255 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12256 return SDValue(); 12257 12258 unsigned LDAlign = LD->getAlignment(); 12259 unsigned STAlign = ST->getAlignment(); 12260 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12261 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12262 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12263 return SDValue(); 12264 12265 SDValue NewLD = 12266 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12267 LD->getPointerInfo(), LDAlign); 12268 12269 SDValue NewST = 12270 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12271 ST->getPointerInfo(), STAlign); 12272 12273 AddToWorklist(NewLD.getNode()); 12274 AddToWorklist(NewST.getNode()); 12275 WorklistRemover DeadNodes(*this); 12276 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12277 ++LdStFP2Int; 12278 return NewST; 12279 } 12280 12281 return SDValue(); 12282 } 12283 12284 // This is a helper function for visitMUL to check the profitability 12285 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12286 // MulNode is the original multiply, AddNode is (add x, c1), 12287 // and ConstNode is c2. 12288 // 12289 // If the (add x, c1) has multiple uses, we could increase 12290 // the number of adds if we make this transformation. 12291 // It would only be worth doing this if we can remove a 12292 // multiply in the process. Check for that here. 12293 // To illustrate: 12294 // (A + c1) * c3 12295 // (A + c2) * c3 12296 // We're checking for cases where we have common "c3 * A" expressions. 12297 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12298 SDValue &AddNode, 12299 SDValue &ConstNode) { 12300 APInt Val; 12301 12302 // If the add only has one use, this would be OK to do. 12303 if (AddNode.getNode()->hasOneUse()) 12304 return true; 12305 12306 // Walk all the users of the constant with which we're multiplying. 12307 for (SDNode *Use : ConstNode->uses()) { 12308 12309 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12310 continue; 12311 12312 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12313 SDNode *OtherOp; 12314 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12315 12316 // OtherOp is what we're multiplying against the constant. 12317 if (Use->getOperand(0) == ConstNode) 12318 OtherOp = Use->getOperand(1).getNode(); 12319 else 12320 OtherOp = Use->getOperand(0).getNode(); 12321 12322 // Check to see if multiply is with the same operand of our "add". 12323 // 12324 // ConstNode = CONST 12325 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12326 // ... 12327 // AddNode = (A + c1) <-- MulVar is A. 12328 // = AddNode * ConstNode <-- current visiting instruction. 12329 // 12330 // If we make this transformation, we will have a common 12331 // multiply (ConstNode * A) that we can save. 12332 if (OtherOp == MulVar) 12333 return true; 12334 12335 // Now check to see if a future expansion will give us a common 12336 // multiply. 12337 // 12338 // ConstNode = CONST 12339 // AddNode = (A + c1) 12340 // ... = AddNode * ConstNode <-- current visiting instruction. 12341 // ... 12342 // OtherOp = (A + c2) 12343 // Use = OtherOp * ConstNode <-- visiting Use. 12344 // 12345 // If we make this transformation, we will have a common 12346 // multiply (CONST * A) after we also do the same transformation 12347 // to the "t2" instruction. 12348 if (OtherOp->getOpcode() == ISD::ADD && 12349 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12350 OtherOp->getOperand(0).getNode() == MulVar) 12351 return true; 12352 } 12353 } 12354 12355 // Didn't find a case where this would be profitable. 12356 return false; 12357 } 12358 12359 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12360 unsigned NumStores) { 12361 SmallVector<SDValue, 8> Chains; 12362 SmallPtrSet<const SDNode *, 8> Visited; 12363 SDLoc StoreDL(StoreNodes[0].MemNode); 12364 12365 for (unsigned i = 0; i < NumStores; ++i) { 12366 Visited.insert(StoreNodes[i].MemNode); 12367 } 12368 12369 // don't include nodes that are children 12370 for (unsigned i = 0; i < NumStores; ++i) { 12371 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12372 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12373 } 12374 12375 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12376 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12377 } 12378 12379 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12380 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 12381 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 12382 // Make sure we have something to merge. 12383 if (NumStores < 2) 12384 return false; 12385 12386 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12387 12388 // The latest Node in the DAG. 12389 SDLoc DL(StoreNodes[0].MemNode); 12390 12391 SDValue StoredVal; 12392 if (UseVector) { 12393 bool IsVec = MemVT.isVector(); 12394 unsigned Elts = NumStores; 12395 if (IsVec) { 12396 // When merging vector stores, get the total number of elements. 12397 Elts *= MemVT.getVectorNumElements(); 12398 } 12399 // Get the type for the merged vector store. 12400 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12401 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 12402 12403 if (IsConstantSrc) { 12404 SmallVector<SDValue, 8> BuildVector; 12405 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 12406 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12407 SDValue Val = St->getValue(); 12408 if (MemVT.getScalarType().isInteger()) 12409 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue())) 12410 Val = DAG.getConstant( 12411 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(), 12412 SDLoc(CFP), MemVT); 12413 BuildVector.push_back(Val); 12414 } 12415 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector); 12416 } else { 12417 SmallVector<SDValue, 8> Ops; 12418 for (unsigned i = 0; i < NumStores; ++i) { 12419 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12420 SDValue Val = St->getValue(); 12421 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 12422 if (Val.getValueType() != MemVT) 12423 return false; 12424 Ops.push_back(Val); 12425 } 12426 12427 // Build the extracted vector elements back into a vector. 12428 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 12429 DL, Ty, Ops); } 12430 } else { 12431 // We should always use a vector store when merging extracted vector 12432 // elements, so this path implies a store of constants. 12433 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12434 12435 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 12436 APInt StoreInt(SizeInBits, 0); 12437 12438 // Construct a single integer constant which is made of the smaller 12439 // constant inputs. 12440 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12441 for (unsigned i = 0; i < NumStores; ++i) { 12442 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12443 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12444 12445 SDValue Val = St->getValue(); 12446 StoreInt <<= ElementSizeBytes * 8; 12447 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12448 StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits); 12449 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12450 StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits); 12451 } else { 12452 llvm_unreachable("Invalid constant element type"); 12453 } 12454 } 12455 12456 // Create the new Load and Store operations. 12457 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12458 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12459 } 12460 12461 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12462 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12463 12464 // make sure we use trunc store if it's necessary to be legal. 12465 SDValue NewStore; 12466 if (UseVector || !UseTrunc) { 12467 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 12468 FirstInChain->getPointerInfo(), 12469 FirstInChain->getAlignment()); 12470 } else { // Must be realized as a trunc store 12471 EVT LegalizedStoredValueTy = 12472 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 12473 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits(); 12474 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 12475 SDValue ExtendedStoreVal = 12476 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 12477 LegalizedStoredValueTy); 12478 NewStore = DAG.getTruncStore( 12479 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 12480 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 12481 FirstInChain->getAlignment(), 12482 FirstInChain->getMemOperand()->getFlags()); 12483 } 12484 12485 // Replace all merged stores with the new store. 12486 for (unsigned i = 0; i < NumStores; ++i) 12487 CombineTo(StoreNodes[i].MemNode, NewStore); 12488 12489 AddToWorklist(NewChain.getNode()); 12490 return true; 12491 } 12492 12493 void DAGCombiner::getStoreMergeCandidates( 12494 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12495 // This holds the base pointer, index, and the offset in bytes from the base 12496 // pointer. 12497 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12498 EVT MemVT = St->getMemoryVT(); 12499 12500 // We must have a base and an offset. 12501 if (!BasePtr.Base.getNode()) 12502 return; 12503 12504 // Do not handle stores to undef base pointers. 12505 if (BasePtr.Base.isUndef()) 12506 return; 12507 12508 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) || 12509 isa<ConstantFPSDNode>(St->getValue()); 12510 bool IsExtractVecSrc = 12511 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12512 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12513 bool IsLoadSrc = isa<LoadSDNode>(St->getValue()); 12514 BaseIndexOffset LBasePtr; 12515 // Match on loadbaseptr if relevant. 12516 if (IsLoadSrc) 12517 LBasePtr = BaseIndexOffset::match( 12518 cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG); 12519 12520 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool { 12521 if (Other->isVolatile() || Other->isIndexed()) 12522 return false; 12523 // We can merge constant floats to equivalent integers 12524 if (Other->getMemoryVT() != MemVT) 12525 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) && 12526 isa<ConstantFPSDNode>(Other->getValue()))) 12527 return false; 12528 if (IsLoadSrc) { 12529 // The Load's Base Ptr must also match 12530 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) { 12531 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG); 12532 if (!(LBasePtr.equalBaseIndex(LPtr))) 12533 return false; 12534 } else 12535 return false; 12536 } 12537 if (IsConstantSrc) 12538 if (!(isa<ConstantSDNode>(Other->getValue()) || 12539 isa<ConstantFPSDNode>(Other->getValue()))) 12540 return false; 12541 if (IsExtractVecSrc) 12542 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12543 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR)) 12544 return false; 12545 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12546 return (Ptr.equalBaseIndex(BasePtr)); 12547 }; 12548 // We looking for a root node which is an ancestor to all mergable 12549 // stores. We search up through a load, to our root and then down 12550 // through all children. For instance we will find Store{1,2,3} if 12551 // St is Store1, Store2. or Store3 where the root is not a load 12552 // which always true for nonvolatile ops. TODO: Expand 12553 // the search to find all valid candidates through multiple layers of loads. 12554 // 12555 // Root 12556 // |-------|-------| 12557 // Load Load Store3 12558 // | | 12559 // Store1 Store2 12560 // 12561 // FIXME: We should be able to climb and 12562 // descend TokenFactors to find candidates as well. 12563 12564 SDNode *RootNode = (St->getChain()).getNode(); 12565 12566 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12567 RootNode = Ldn->getChain().getNode(); 12568 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12569 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12570 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 12571 if (I2.getOperandNo() == 0) 12572 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 12573 BaseIndexOffset Ptr; 12574 if (CandidateMatch(OtherST, Ptr)) 12575 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12576 } 12577 } else 12578 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12579 if (I.getOperandNo() == 0) 12580 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12581 BaseIndexOffset Ptr; 12582 if (CandidateMatch(OtherST, Ptr)) 12583 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12584 } 12585 } 12586 12587 // We need to check that merging these stores does not cause a loop 12588 // in the DAG. Any store candidate may depend on another candidate 12589 // indirectly through its operand (we already consider dependencies 12590 // through the chain). Check in parallel by searching up from 12591 // non-chain operands of candidates. 12592 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12593 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 12594 SmallPtrSet<const SDNode *, 16> Visited; 12595 SmallVector<const SDNode *, 8> Worklist; 12596 // search ops of store candidates 12597 for (unsigned i = 0; i < NumStores; ++i) { 12598 SDNode *n = StoreNodes[i].MemNode; 12599 // Potential loops may happen only through non-chain operands 12600 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12601 Worklist.push_back(n->getOperand(j).getNode()); 12602 } 12603 // search through DAG. We can stop early if we find a storenode 12604 for (unsigned i = 0; i < NumStores; ++i) { 12605 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12606 return false; 12607 } 12608 return true; 12609 } 12610 12611 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12612 if (OptLevel == CodeGenOpt::None) 12613 return false; 12614 12615 EVT MemVT = St->getMemoryVT(); 12616 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12617 12618 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 12619 return false; 12620 12621 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12622 Attribute::NoImplicitFloat); 12623 12624 // This function cannot currently deal with non-byte-sized memory sizes. 12625 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12626 return false; 12627 12628 if (!MemVT.isSimple()) 12629 return false; 12630 12631 // Perform an early exit check. Do not bother looking at stored values that 12632 // are not constants, loads, or extracted vector elements. 12633 SDValue StoredVal = St->getValue(); 12634 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12635 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12636 isa<ConstantFPSDNode>(StoredVal); 12637 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12638 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12639 12640 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12641 return false; 12642 12643 // Don't merge vectors into wider vectors if the source data comes from loads. 12644 // TODO: This restriction can be lifted by using logic similar to the 12645 // ExtractVecSrc case. 12646 if (MemVT.isVector() && IsLoadSrc) 12647 return false; 12648 12649 SmallVector<MemOpLink, 8> StoreNodes; 12650 // Find potential store merge candidates by searching through chain sub-DAG 12651 getStoreMergeCandidates(St, StoreNodes); 12652 12653 // Check if there is anything to merge. 12654 if (StoreNodes.size() < 2) 12655 return false; 12656 12657 // Sort the memory operands according to their distance from the 12658 // base pointer. 12659 std::sort(StoreNodes.begin(), StoreNodes.end(), 12660 [](MemOpLink LHS, MemOpLink RHS) { 12661 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12662 }); 12663 12664 // Store Merge attempts to merge the lowest stores. This generally 12665 // works out as if successful, as the remaining stores are checked 12666 // after the first collection of stores is merged. However, in the 12667 // case that a non-mergeable store is found first, e.g., {p[-2], 12668 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 12669 // mergeable cases. To prevent this, we prune such stores from the 12670 // front of StoreNodes here. 12671 12672 bool RV = false; 12673 while (StoreNodes.size() > 1) { 12674 unsigned StartIdx = 0; 12675 while ((StartIdx + 1 < StoreNodes.size()) && 12676 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 12677 StoreNodes[StartIdx + 1].OffsetFromBase) 12678 ++StartIdx; 12679 12680 // Bail if we don't have enough candidates to merge. 12681 if (StartIdx + 1 >= StoreNodes.size()) 12682 return RV; 12683 12684 if (StartIdx) 12685 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 12686 12687 // Scan the memory operations on the chain and find the first 12688 // non-consecutive store memory address. 12689 unsigned NumConsecutiveStores = 1; 12690 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12691 // Check that the addresses are consecutive starting from the second 12692 // element in the list of stores. 12693 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12694 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12695 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12696 break; 12697 NumConsecutiveStores = i + 1; 12698 } 12699 12700 if (NumConsecutiveStores < 2) { 12701 StoreNodes.erase(StoreNodes.begin(), 12702 StoreNodes.begin() + NumConsecutiveStores); 12703 continue; 12704 } 12705 12706 // Check that we can merge these candidates without causing a cycle 12707 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 12708 NumConsecutiveStores)) { 12709 StoreNodes.erase(StoreNodes.begin(), 12710 StoreNodes.begin() + NumConsecutiveStores); 12711 continue; 12712 } 12713 12714 // The node with the lowest store address. 12715 LLVMContext &Context = *DAG.getContext(); 12716 const DataLayout &DL = DAG.getDataLayout(); 12717 12718 // Store the constants into memory as one consecutive store. 12719 if (IsConstantSrc) { 12720 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12721 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12722 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12723 unsigned LastLegalType = 1; 12724 unsigned LastLegalVectorType = 1; 12725 bool LastIntegerTrunc = false; 12726 bool NonZero = false; 12727 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12728 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 12729 SDValue StoredVal = ST->getValue(); 12730 12731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12732 NonZero |= !C->isNullValue(); 12733 } else if (ConstantFPSDNode *C = 12734 dyn_cast<ConstantFPSDNode>(StoredVal)) { 12735 NonZero |= !C->getConstantFPValue()->isNullValue(); 12736 } else { 12737 // Non-constant. 12738 break; 12739 } 12740 12741 // Find a legal type for the constant store. 12742 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12743 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12744 bool IsFast = false; 12745 if (TLI.isTypeLegal(StoreTy) && 12746 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12747 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12748 FirstStoreAlign, &IsFast) && 12749 IsFast) { 12750 LastIntegerTrunc = false; 12751 LastLegalType = i + 1; 12752 // Or check whether a truncstore is legal. 12753 } else if (TLI.getTypeAction(Context, StoreTy) == 12754 TargetLowering::TypePromoteInteger) { 12755 EVT LegalizedStoredValueTy = 12756 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12757 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12758 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) && 12759 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12760 FirstStoreAS, FirstStoreAlign, &IsFast) && 12761 IsFast) { 12762 LastIntegerTrunc = true; 12763 LastLegalType = i + 1; 12764 } 12765 } 12766 12767 // We only use vectors if the constant is known to be zero or the target 12768 // allows it and the function is not marked with the noimplicitfloat 12769 // attribute. 12770 if ((!NonZero || 12771 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 12772 !NoVectors) { 12773 // Find a legal type for the vector store. 12774 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1); 12775 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) && 12776 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12777 FirstStoreAlign, &IsFast) && 12778 IsFast) 12779 LastLegalVectorType = i + 1; 12780 } 12781 } 12782 12783 // Check if we found a legal integer type that creates a meaningful merge. 12784 if (LastLegalType < 2 && LastLegalVectorType < 2) { 12785 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12786 continue; 12787 } 12788 12789 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12790 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 12791 12792 bool Merged = MergeStoresOfConstantsOrVecElts( 12793 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc); 12794 if (!Merged) { 12795 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12796 continue; 12797 } 12798 // Remove merged stores for next iteration. 12799 RV = true; 12800 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12801 continue; 12802 } 12803 12804 // When extracting multiple vector elements, try to store them 12805 // in one vector store rather than a sequence of scalar stores. 12806 if (IsExtractVecSrc) { 12807 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12808 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12809 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12810 unsigned NumStoresToMerge = 1; 12811 bool IsVec = MemVT.isVector(); 12812 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12813 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12814 unsigned StoreValOpcode = St->getValue().getOpcode(); 12815 // This restriction could be loosened. 12816 // Bail out if any stored values are not elements extracted from a 12817 // vector. It should be possible to handle mixed sources, but load 12818 // sources need more careful handling (see the block of code below that 12819 // handles consecutive loads). 12820 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12821 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12822 return RV; 12823 12824 // Find a legal type for the vector store. 12825 unsigned Elts = i + 1; 12826 if (IsVec) { 12827 // When merging vector stores, get the total number of elements. 12828 Elts *= MemVT.getVectorNumElements(); 12829 } 12830 EVT Ty = 12831 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12832 bool IsFast; 12833 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) && 12834 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12835 FirstStoreAlign, &IsFast) && 12836 IsFast) 12837 NumStoresToMerge = i + 1; 12838 } 12839 12840 bool Merged = MergeStoresOfConstantsOrVecElts( 12841 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 12842 if (!Merged) { 12843 StoreNodes.erase(StoreNodes.begin(), 12844 StoreNodes.begin() + NumStoresToMerge); 12845 continue; 12846 } 12847 // Remove merged stores for next iteration. 12848 StoreNodes.erase(StoreNodes.begin(), 12849 StoreNodes.begin() + NumStoresToMerge); 12850 RV = true; 12851 continue; 12852 } 12853 12854 // Below we handle the case of multiple consecutive stores that 12855 // come from multiple consecutive loads. We merge them into a single 12856 // wide load and a single wide store. 12857 12858 // Look for load nodes which are used by the stored values. 12859 SmallVector<MemOpLink, 8> LoadNodes; 12860 12861 // Find acceptable loads. Loads need to have the same chain (token factor), 12862 // must not be zext, volatile, indexed, and they must be consecutive. 12863 BaseIndexOffset LdBasePtr; 12864 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12865 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12866 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12867 if (!Ld) 12868 break; 12869 12870 // Loads must only have one use. 12871 if (!Ld->hasNUsesOfValue(1, 0)) 12872 break; 12873 12874 // The memory operands must not be volatile. 12875 if (Ld->isVolatile() || Ld->isIndexed()) 12876 break; 12877 12878 // We do not accept ext loads. 12879 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12880 break; 12881 12882 // The stored memory type must be the same. 12883 if (Ld->getMemoryVT() != MemVT) 12884 break; 12885 12886 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12887 // If this is not the first ptr that we check. 12888 if (LdBasePtr.Base.getNode()) { 12889 // The base ptr must be the same. 12890 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12891 break; 12892 } else { 12893 // Check that all other base pointers are the same as this one. 12894 LdBasePtr = LdPtr; 12895 } 12896 12897 // We found a potential memory operand to merge. 12898 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset)); 12899 } 12900 12901 if (LoadNodes.size() < 2) { 12902 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12903 continue; 12904 } 12905 12906 // If we have load/store pair instructions and we only have two values, 12907 // don't bother merging. 12908 unsigned RequiredAlignment; 12909 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12910 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 12911 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 12912 continue; 12913 } 12914 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12915 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12916 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12917 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12918 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12919 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12920 12921 // Scan the memory operations on the chain and find the first 12922 // non-consecutive load memory address. These variables hold the index in 12923 // the store node array. 12924 unsigned LastConsecutiveLoad = 1; 12925 // This variable refers to the size and not index in the array. 12926 unsigned LastLegalVectorType = 1; 12927 unsigned LastLegalIntegerType = 1; 12928 bool DoIntegerTruncate = false; 12929 StartAddress = LoadNodes[0].OffsetFromBase; 12930 SDValue FirstChain = FirstLoad->getChain(); 12931 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12932 // All loads must share the same chain. 12933 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12934 break; 12935 12936 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12937 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12938 break; 12939 LastConsecutiveLoad = i; 12940 // Find a legal type for the vector store. 12941 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1); 12942 bool IsFastSt, IsFastLd; 12943 if (TLI.isTypeLegal(StoreTy) && 12944 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12945 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12946 FirstStoreAlign, &IsFastSt) && 12947 IsFastSt && 12948 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12949 FirstLoadAlign, &IsFastLd) && 12950 IsFastLd) { 12951 LastLegalVectorType = i + 1; 12952 } 12953 12954 // Find a legal type for the integer store. 12955 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12956 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12957 if (TLI.isTypeLegal(StoreTy) && 12958 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12959 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12960 FirstStoreAlign, &IsFastSt) && 12961 IsFastSt && 12962 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12963 FirstLoadAlign, &IsFastLd) && 12964 IsFastLd) { 12965 LastLegalIntegerType = i + 1; 12966 DoIntegerTruncate = false; 12967 // Or check whether a truncstore and extload is legal. 12968 } else if (TLI.getTypeAction(Context, StoreTy) == 12969 TargetLowering::TypePromoteInteger) { 12970 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 12971 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12972 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) && 12973 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 12974 StoreTy) && 12975 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 12976 StoreTy) && 12977 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12978 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12979 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12980 IsFastSt && 12981 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12982 FirstLoadAlign, &IsFastLd) && 12983 IsFastLd) { 12984 LastLegalIntegerType = i + 1; 12985 DoIntegerTruncate = true; 12986 } 12987 } 12988 } 12989 12990 // Only use vector types if the vector type is larger than the integer type. 12991 // If they are the same, use integers. 12992 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12993 unsigned LastLegalType = 12994 std::max(LastLegalVectorType, LastLegalIntegerType); 12995 12996 // We add +1 here because the LastXXX variables refer to location while 12997 // the NumElem refers to array/index size. 12998 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 12999 NumElem = std::min(LastLegalType, NumElem); 13000 13001 if (NumElem < 2) { 13002 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 13003 continue; 13004 } 13005 13006 // Find if it is better to use vectors or integers to load and store 13007 // to memory. 13008 EVT JointMemOpVT; 13009 if (UseVectorTy) { 13010 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 13011 } else { 13012 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 13013 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 13014 } 13015 13016 SDLoc LoadDL(LoadNodes[0].MemNode); 13017 SDLoc StoreDL(StoreNodes[0].MemNode); 13018 13019 // The merged loads are required to have the same incoming chain, so 13020 // using the first's chain is acceptable. 13021 13022 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 13023 AddToWorklist(NewStoreChain.getNode()); 13024 13025 SDValue NewLoad, NewStore; 13026 if (UseVectorTy || !DoIntegerTruncate) { 13027 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 13028 FirstLoad->getBasePtr(), 13029 FirstLoad->getPointerInfo(), FirstLoadAlign); 13030 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad, 13031 FirstInChain->getBasePtr(), 13032 FirstInChain->getPointerInfo(), FirstStoreAlign); 13033 } else { // This must be the truncstore/extload case 13034 EVT ExtendedTy = 13035 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 13036 NewLoad = 13037 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(), 13038 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 13039 JointMemOpVT, FirstLoadAlign); 13040 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 13041 FirstInChain->getBasePtr(), 13042 FirstInChain->getPointerInfo(), JointMemOpVT, 13043 FirstInChain->getAlignment(), 13044 FirstInChain->getMemOperand()->getFlags()); 13045 } 13046 13047 // Transfer chain users from old loads to the new load. 13048 for (unsigned i = 0; i < NumElem; ++i) { 13049 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 13050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 13051 SDValue(NewLoad.getNode(), 1)); 13052 } 13053 13054 // Replace the all stores with the new store. 13055 for (unsigned i = 0; i < NumElem; ++i) 13056 CombineTo(StoreNodes[i].MemNode, NewStore); 13057 RV = true; 13058 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 13059 continue; 13060 } 13061 return RV; 13062 } 13063 13064 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 13065 SDLoc SL(ST); 13066 SDValue ReplStore; 13067 13068 // Replace the chain to avoid dependency. 13069 if (ST->isTruncatingStore()) { 13070 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 13071 ST->getBasePtr(), ST->getMemoryVT(), 13072 ST->getMemOperand()); 13073 } else { 13074 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 13075 ST->getMemOperand()); 13076 } 13077 13078 // Create token to keep both nodes around. 13079 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 13080 MVT::Other, ST->getChain(), ReplStore); 13081 13082 // Make sure the new and old chains are cleaned up. 13083 AddToWorklist(Token.getNode()); 13084 13085 // Don't add users to work list. 13086 return CombineTo(ST, Token, false); 13087 } 13088 13089 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 13090 SDValue Value = ST->getValue(); 13091 if (Value.getOpcode() == ISD::TargetConstantFP) 13092 return SDValue(); 13093 13094 SDLoc DL(ST); 13095 13096 SDValue Chain = ST->getChain(); 13097 SDValue Ptr = ST->getBasePtr(); 13098 13099 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 13100 13101 // NOTE: If the original store is volatile, this transform must not increase 13102 // the number of stores. For example, on x86-32 an f64 can be stored in one 13103 // processor operation but an i64 (which is not legal) requires two. So the 13104 // transform should not be done in this case. 13105 13106 SDValue Tmp; 13107 switch (CFP->getSimpleValueType(0).SimpleTy) { 13108 default: 13109 llvm_unreachable("Unknown FP type"); 13110 case MVT::f16: // We don't do this for these yet. 13111 case MVT::f80: 13112 case MVT::f128: 13113 case MVT::ppcf128: 13114 return SDValue(); 13115 case MVT::f32: 13116 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13117 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13118 ; 13119 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13120 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13121 MVT::i32); 13122 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13123 } 13124 13125 return SDValue(); 13126 case MVT::f64: 13127 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13128 !ST->isVolatile()) || 13129 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13130 ; 13131 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13132 getZExtValue(), SDLoc(CFP), MVT::i64); 13133 return DAG.getStore(Chain, DL, Tmp, 13134 Ptr, ST->getMemOperand()); 13135 } 13136 13137 if (!ST->isVolatile() && 13138 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13139 // Many FP stores are not made apparent until after legalize, e.g. for 13140 // argument passing. Since this is so common, custom legalize the 13141 // 64-bit integer store into two 32-bit stores. 13142 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13143 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13144 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13145 if (DAG.getDataLayout().isBigEndian()) 13146 std::swap(Lo, Hi); 13147 13148 unsigned Alignment = ST->getAlignment(); 13149 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13150 AAMDNodes AAInfo = ST->getAAInfo(); 13151 13152 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13153 ST->getAlignment(), MMOFlags, AAInfo); 13154 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13155 DAG.getConstant(4, DL, Ptr.getValueType())); 13156 Alignment = MinAlign(Alignment, 4U); 13157 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13158 ST->getPointerInfo().getWithOffset(4), 13159 Alignment, MMOFlags, AAInfo); 13160 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13161 St0, St1); 13162 } 13163 13164 return SDValue(); 13165 } 13166 } 13167 13168 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13169 StoreSDNode *ST = cast<StoreSDNode>(N); 13170 SDValue Chain = ST->getChain(); 13171 SDValue Value = ST->getValue(); 13172 SDValue Ptr = ST->getBasePtr(); 13173 13174 // If this is a store of a bit convert, store the input value if the 13175 // resultant store does not need a higher alignment than the original. 13176 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13177 ST->isUnindexed()) { 13178 EVT SVT = Value.getOperand(0).getValueType(); 13179 if (((!LegalOperations && !ST->isVolatile()) || 13180 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13181 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13182 unsigned OrigAlign = ST->getAlignment(); 13183 bool Fast = false; 13184 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13185 ST->getAddressSpace(), OrigAlign, &Fast) && 13186 Fast) { 13187 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13188 ST->getPointerInfo(), OrigAlign, 13189 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13190 } 13191 } 13192 } 13193 13194 // Turn 'store undef, Ptr' -> nothing. 13195 if (Value.isUndef() && ST->isUnindexed()) 13196 return Chain; 13197 13198 // Try to infer better alignment information than the store already has. 13199 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13200 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13201 if (Align > ST->getAlignment()) { 13202 SDValue NewStore = 13203 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13204 ST->getMemoryVT(), Align, 13205 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13206 if (NewStore.getNode() != N) 13207 return CombineTo(ST, NewStore, true); 13208 } 13209 } 13210 } 13211 13212 // Try transforming a pair floating point load / store ops to integer 13213 // load / store ops. 13214 if (SDValue NewST = TransformFPLoadStorePair(N)) 13215 return NewST; 13216 13217 if (ST->isUnindexed()) { 13218 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13219 // adjacent stores. 13220 if (findBetterNeighborChains(ST)) { 13221 // replaceStoreChain uses CombineTo, which handled all of the worklist 13222 // manipulation. Return the original node to not do anything else. 13223 return SDValue(ST, 0); 13224 } 13225 Chain = ST->getChain(); 13226 } 13227 13228 // FIXME: is there such a thing as a truncating indexed store? 13229 if (ST->isTruncatingStore() && ST->isUnindexed() && 13230 Value.getValueType().isInteger()) { 13231 // See if we can simplify the input to this truncstore with knowledge that 13232 // only the low bits are being used. For example: 13233 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13234 SDValue Shorter = GetDemandedBits( 13235 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13236 ST->getMemoryVT().getScalarSizeInBits())); 13237 AddToWorklist(Value.getNode()); 13238 if (Shorter.getNode()) 13239 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13240 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13241 13242 // Otherwise, see if we can simplify the operation with 13243 // SimplifyDemandedBits, which only works if the value has a single use. 13244 if (SimplifyDemandedBits( 13245 Value, 13246 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13247 ST->getMemoryVT().getScalarSizeInBits()))) { 13248 // Re-visit the store if anything changed and the store hasn't been merged 13249 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13250 // node back to the worklist if necessary, but we also need to re-visit 13251 // the Store node itself. 13252 if (N->getOpcode() != ISD::DELETED_NODE) 13253 AddToWorklist(N); 13254 return SDValue(N, 0); 13255 } 13256 } 13257 13258 // If this is a load followed by a store to the same location, then the store 13259 // is dead/noop. 13260 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13261 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13262 ST->isUnindexed() && !ST->isVolatile() && 13263 // There can't be any side effects between the load and store, such as 13264 // a call or store. 13265 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13266 // The store is dead, remove it. 13267 return Chain; 13268 } 13269 } 13270 13271 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13272 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13273 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13274 ST->getMemoryVT() == ST1->getMemoryVT()) { 13275 // If this is a store followed by a store with the same value to the same 13276 // location, then the store is dead/noop. 13277 if (ST1->getValue() == Value) { 13278 // The store is dead, remove it. 13279 return Chain; 13280 } 13281 13282 // If this is a store who's preceeding store to the same location 13283 // and no one other node is chained to that store we can effectively 13284 // drop the store. Do not remove stores to undef as they may be used as 13285 // data sinks. 13286 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13287 !ST1->getBasePtr().isUndef()) { 13288 // ST1 is fully overwritten and can be elided. Combine with it's chain 13289 // value. 13290 CombineTo(ST1, ST1->getChain()); 13291 return SDValue(); 13292 } 13293 } 13294 } 13295 13296 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13297 // truncating store. We can do this even if this is already a truncstore. 13298 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13299 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13300 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13301 ST->getMemoryVT())) { 13302 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13303 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13304 } 13305 13306 // Only perform this optimization before the types are legal, because we 13307 // don't want to perform this optimization on every DAGCombine invocation. 13308 if (!LegalTypes) { 13309 for (;;) { 13310 // There can be multiple store sequences on the same chain. 13311 // Keep trying to merge store sequences until we are unable to do so 13312 // or until we merge the last store on the chain. 13313 bool Changed = MergeConsecutiveStores(ST); 13314 if (!Changed) break; 13315 // Return N as merge only uses CombineTo and no worklist clean 13316 // up is necessary. 13317 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13318 return SDValue(N, 0); 13319 } 13320 } 13321 13322 // Try transforming N to an indexed store. 13323 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13324 return SDValue(N, 0); 13325 13326 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13327 // 13328 // Make sure to do this only after attempting to merge stores in order to 13329 // avoid changing the types of some subset of stores due to visit order, 13330 // preventing their merging. 13331 if (isa<ConstantFPSDNode>(ST->getValue())) { 13332 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13333 return NewSt; 13334 } 13335 13336 if (SDValue NewSt = splitMergedValStore(ST)) 13337 return NewSt; 13338 13339 return ReduceLoadOpStoreWidth(N); 13340 } 13341 13342 /// For the instruction sequence of store below, F and I values 13343 /// are bundled together as an i64 value before being stored into memory. 13344 /// Sometimes it is more efficent to generate separate stores for F and I, 13345 /// which can remove the bitwise instructions or sink them to colder places. 13346 /// 13347 /// (store (or (zext (bitcast F to i32) to i64), 13348 /// (shl (zext I to i64), 32)), addr) --> 13349 /// (store F, addr) and (store I, addr+4) 13350 /// 13351 /// Similarly, splitting for other merged store can also be beneficial, like: 13352 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13353 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13354 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13355 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13356 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13357 /// 13358 /// We allow each target to determine specifically which kind of splitting is 13359 /// supported. 13360 /// 13361 /// The store patterns are commonly seen from the simple code snippet below 13362 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13363 /// void goo(const std::pair<int, float> &); 13364 /// hoo() { 13365 /// ... 13366 /// goo(std::make_pair(tmp, ftmp)); 13367 /// ... 13368 /// } 13369 /// 13370 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13371 if (OptLevel == CodeGenOpt::None) 13372 return SDValue(); 13373 13374 SDValue Val = ST->getValue(); 13375 SDLoc DL(ST); 13376 13377 // Match OR operand. 13378 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13379 return SDValue(); 13380 13381 // Match SHL operand and get Lower and Higher parts of Val. 13382 SDValue Op1 = Val.getOperand(0); 13383 SDValue Op2 = Val.getOperand(1); 13384 SDValue Lo, Hi; 13385 if (Op1.getOpcode() != ISD::SHL) { 13386 std::swap(Op1, Op2); 13387 if (Op1.getOpcode() != ISD::SHL) 13388 return SDValue(); 13389 } 13390 Lo = Op2; 13391 Hi = Op1.getOperand(0); 13392 if (!Op1.hasOneUse()) 13393 return SDValue(); 13394 13395 // Match shift amount to HalfValBitSize. 13396 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13397 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13398 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13399 return SDValue(); 13400 13401 // Lo and Hi are zero-extended from int with size less equal than 32 13402 // to i64. 13403 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13404 !Lo.getOperand(0).getValueType().isScalarInteger() || 13405 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13406 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13407 !Hi.getOperand(0).getValueType().isScalarInteger() || 13408 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13409 return SDValue(); 13410 13411 // Use the EVT of low and high parts before bitcast as the input 13412 // of target query. 13413 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13414 ? Lo.getOperand(0).getValueType() 13415 : Lo.getValueType(); 13416 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13417 ? Hi.getOperand(0).getValueType() 13418 : Hi.getValueType(); 13419 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13420 return SDValue(); 13421 13422 // Start to split store. 13423 unsigned Alignment = ST->getAlignment(); 13424 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13425 AAMDNodes AAInfo = ST->getAAInfo(); 13426 13427 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13428 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13429 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13430 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13431 13432 SDValue Chain = ST->getChain(); 13433 SDValue Ptr = ST->getBasePtr(); 13434 // Lower value store. 13435 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13436 ST->getAlignment(), MMOFlags, AAInfo); 13437 Ptr = 13438 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13439 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13440 // Higher value store. 13441 SDValue St1 = 13442 DAG.getStore(St0, DL, Hi, Ptr, 13443 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13444 Alignment / 2, MMOFlags, AAInfo); 13445 return St1; 13446 } 13447 13448 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 13449 SDValue InVec = N->getOperand(0); 13450 SDValue InVal = N->getOperand(1); 13451 SDValue EltNo = N->getOperand(2); 13452 SDLoc DL(N); 13453 13454 // If the inserted element is an UNDEF, just use the input vector. 13455 if (InVal.isUndef()) 13456 return InVec; 13457 13458 EVT VT = InVec.getValueType(); 13459 13460 // Check that we know which element is being inserted 13461 if (!isa<ConstantSDNode>(EltNo)) 13462 return SDValue(); 13463 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13464 13465 // Canonicalize insert_vector_elt dag nodes. 13466 // Example: 13467 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 13468 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 13469 // 13470 // Do this only if the child insert_vector node has one use; also 13471 // do this only if indices are both constants and Idx1 < Idx0. 13472 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 13473 && isa<ConstantSDNode>(InVec.getOperand(2))) { 13474 unsigned OtherElt = InVec.getConstantOperandVal(2); 13475 if (Elt < OtherElt) { 13476 // Swap nodes. 13477 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 13478 InVec.getOperand(0), InVal, EltNo); 13479 AddToWorklist(NewOp.getNode()); 13480 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 13481 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 13482 } 13483 } 13484 13485 // If we can't generate a legal BUILD_VECTOR, exit 13486 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13487 return SDValue(); 13488 13489 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13490 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13491 // vector elements. 13492 SmallVector<SDValue, 8> Ops; 13493 // Do not combine these two vectors if the output vector will not replace 13494 // the input vector. 13495 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13496 Ops.append(InVec.getNode()->op_begin(), 13497 InVec.getNode()->op_end()); 13498 } else if (InVec.isUndef()) { 13499 unsigned NElts = VT.getVectorNumElements(); 13500 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13501 } else { 13502 return SDValue(); 13503 } 13504 13505 // Insert the element 13506 if (Elt < Ops.size()) { 13507 // All the operands of BUILD_VECTOR must have the same type; 13508 // we enforce that here. 13509 EVT OpVT = Ops[0].getValueType(); 13510 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13511 } 13512 13513 // Return the new vector 13514 return DAG.getBuildVector(VT, DL, Ops); 13515 } 13516 13517 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13518 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13519 assert(!OriginalLoad->isVolatile()); 13520 13521 EVT ResultVT = EVE->getValueType(0); 13522 EVT VecEltVT = InVecVT.getVectorElementType(); 13523 unsigned Align = OriginalLoad->getAlignment(); 13524 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13525 VecEltVT.getTypeForEVT(*DAG.getContext())); 13526 13527 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13528 return SDValue(); 13529 13530 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13531 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13532 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13533 return SDValue(); 13534 13535 Align = NewAlign; 13536 13537 SDValue NewPtr = OriginalLoad->getBasePtr(); 13538 SDValue Offset; 13539 EVT PtrType = NewPtr.getValueType(); 13540 MachinePointerInfo MPI; 13541 SDLoc DL(EVE); 13542 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13543 int Elt = ConstEltNo->getZExtValue(); 13544 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13545 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13546 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13547 } else { 13548 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13549 Offset = DAG.getNode( 13550 ISD::MUL, DL, PtrType, Offset, 13551 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13552 MPI = OriginalLoad->getPointerInfo(); 13553 } 13554 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13555 13556 // The replacement we need to do here is a little tricky: we need to 13557 // replace an extractelement of a load with a load. 13558 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13559 // Note that this replacement assumes that the extractvalue is the only 13560 // use of the load; that's okay because we don't want to perform this 13561 // transformation in other cases anyway. 13562 SDValue Load; 13563 SDValue Chain; 13564 if (ResultVT.bitsGT(VecEltVT)) { 13565 // If the result type of vextract is wider than the load, then issue an 13566 // extending load instead. 13567 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13568 VecEltVT) 13569 ? ISD::ZEXTLOAD 13570 : ISD::EXTLOAD; 13571 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13572 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13573 Align, OriginalLoad->getMemOperand()->getFlags(), 13574 OriginalLoad->getAAInfo()); 13575 Chain = Load.getValue(1); 13576 } else { 13577 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13578 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13579 OriginalLoad->getAAInfo()); 13580 Chain = Load.getValue(1); 13581 if (ResultVT.bitsLT(VecEltVT)) 13582 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13583 else 13584 Load = DAG.getBitcast(ResultVT, Load); 13585 } 13586 WorklistRemover DeadNodes(*this); 13587 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13588 SDValue To[] = { Load, Chain }; 13589 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13590 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13591 // worklist explicitly as well. 13592 AddToWorklist(Load.getNode()); 13593 AddUsersToWorklist(Load.getNode()); // Add users too 13594 // Make sure to revisit this node to clean it up; it will usually be dead. 13595 AddToWorklist(EVE); 13596 ++OpsNarrowed; 13597 return SDValue(EVE, 0); 13598 } 13599 13600 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13601 // (vextract (scalar_to_vector val, 0) -> val 13602 SDValue InVec = N->getOperand(0); 13603 EVT VT = InVec.getValueType(); 13604 EVT NVT = N->getValueType(0); 13605 13606 if (InVec.isUndef()) 13607 return DAG.getUNDEF(NVT); 13608 13609 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13610 // Check if the result type doesn't match the inserted element type. A 13611 // SCALAR_TO_VECTOR may truncate the inserted element and the 13612 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13613 SDValue InOp = InVec.getOperand(0); 13614 if (InOp.getValueType() != NVT) { 13615 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13616 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13617 } 13618 return InOp; 13619 } 13620 13621 SDValue EltNo = N->getOperand(1); 13622 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13623 13624 // extract_vector_elt (build_vector x, y), 1 -> y 13625 if (ConstEltNo && 13626 InVec.getOpcode() == ISD::BUILD_VECTOR && 13627 TLI.isTypeLegal(VT) && 13628 (InVec.hasOneUse() || 13629 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13630 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13631 EVT InEltVT = Elt.getValueType(); 13632 13633 // Sometimes build_vector's scalar input types do not match result type. 13634 if (NVT == InEltVT) 13635 return Elt; 13636 13637 // TODO: It may be useful to truncate if free if the build_vector implicitly 13638 // converts. 13639 } 13640 13641 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13642 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13643 ConstEltNo->isNullValue() && VT.isInteger()) { 13644 SDValue BCSrc = InVec.getOperand(0); 13645 if (BCSrc.getValueType().isScalarInteger()) 13646 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13647 } 13648 13649 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13650 // 13651 // This only really matters if the index is non-constant since other combines 13652 // on the constant elements already work. 13653 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13654 EltNo == InVec.getOperand(2)) { 13655 SDValue Elt = InVec.getOperand(1); 13656 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13657 } 13658 13659 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13660 // We only perform this optimization before the op legalization phase because 13661 // we may introduce new vector instructions which are not backed by TD 13662 // patterns. For example on AVX, extracting elements from a wide vector 13663 // without using extract_subvector. However, if we can find an underlying 13664 // scalar value, then we can always use that. 13665 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13666 int NumElem = VT.getVectorNumElements(); 13667 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13668 // Find the new index to extract from. 13669 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13670 13671 // Extracting an undef index is undef. 13672 if (OrigElt == -1) 13673 return DAG.getUNDEF(NVT); 13674 13675 // Select the right vector half to extract from. 13676 SDValue SVInVec; 13677 if (OrigElt < NumElem) { 13678 SVInVec = InVec->getOperand(0); 13679 } else { 13680 SVInVec = InVec->getOperand(1); 13681 OrigElt -= NumElem; 13682 } 13683 13684 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13685 SDValue InOp = SVInVec.getOperand(OrigElt); 13686 if (InOp.getValueType() != NVT) { 13687 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13688 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13689 } 13690 13691 return InOp; 13692 } 13693 13694 // FIXME: We should handle recursing on other vector shuffles and 13695 // scalar_to_vector here as well. 13696 13697 if (!LegalOperations) { 13698 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13699 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13700 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13701 } 13702 } 13703 13704 bool BCNumEltsChanged = false; 13705 EVT ExtVT = VT.getVectorElementType(); 13706 EVT LVT = ExtVT; 13707 13708 // If the result of load has to be truncated, then it's not necessarily 13709 // profitable. 13710 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13711 return SDValue(); 13712 13713 if (InVec.getOpcode() == ISD::BITCAST) { 13714 // Don't duplicate a load with other uses. 13715 if (!InVec.hasOneUse()) 13716 return SDValue(); 13717 13718 EVT BCVT = InVec.getOperand(0).getValueType(); 13719 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13720 return SDValue(); 13721 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13722 BCNumEltsChanged = true; 13723 InVec = InVec.getOperand(0); 13724 ExtVT = BCVT.getVectorElementType(); 13725 } 13726 13727 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13728 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13729 ISD::isNormalLoad(InVec.getNode()) && 13730 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13731 SDValue Index = N->getOperand(1); 13732 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13733 if (!OrigLoad->isVolatile()) { 13734 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13735 OrigLoad); 13736 } 13737 } 13738 } 13739 13740 // Perform only after legalization to ensure build_vector / vector_shuffle 13741 // optimizations have already been done. 13742 if (!LegalOperations) return SDValue(); 13743 13744 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13745 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13746 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13747 13748 if (ConstEltNo) { 13749 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13750 13751 LoadSDNode *LN0 = nullptr; 13752 const ShuffleVectorSDNode *SVN = nullptr; 13753 if (ISD::isNormalLoad(InVec.getNode())) { 13754 LN0 = cast<LoadSDNode>(InVec); 13755 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13756 InVec.getOperand(0).getValueType() == ExtVT && 13757 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13758 // Don't duplicate a load with other uses. 13759 if (!InVec.hasOneUse()) 13760 return SDValue(); 13761 13762 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13763 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13764 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13765 // => 13766 // (load $addr+1*size) 13767 13768 // Don't duplicate a load with other uses. 13769 if (!InVec.hasOneUse()) 13770 return SDValue(); 13771 13772 // If the bit convert changed the number of elements, it is unsafe 13773 // to examine the mask. 13774 if (BCNumEltsChanged) 13775 return SDValue(); 13776 13777 // Select the input vector, guarding against out of range extract vector. 13778 unsigned NumElems = VT.getVectorNumElements(); 13779 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13780 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13781 13782 if (InVec.getOpcode() == ISD::BITCAST) { 13783 // Don't duplicate a load with other uses. 13784 if (!InVec.hasOneUse()) 13785 return SDValue(); 13786 13787 InVec = InVec.getOperand(0); 13788 } 13789 if (ISD::isNormalLoad(InVec.getNode())) { 13790 LN0 = cast<LoadSDNode>(InVec); 13791 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13792 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13793 } 13794 } 13795 13796 // Make sure we found a non-volatile load and the extractelement is 13797 // the only use. 13798 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13799 return SDValue(); 13800 13801 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13802 if (Elt == -1) 13803 return DAG.getUNDEF(LVT); 13804 13805 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13806 } 13807 13808 return SDValue(); 13809 } 13810 13811 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13812 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13813 // We perform this optimization post type-legalization because 13814 // the type-legalizer often scalarizes integer-promoted vectors. 13815 // Performing this optimization before may create bit-casts which 13816 // will be type-legalized to complex code sequences. 13817 // We perform this optimization only before the operation legalizer because we 13818 // may introduce illegal operations. 13819 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13820 return SDValue(); 13821 13822 unsigned NumInScalars = N->getNumOperands(); 13823 SDLoc DL(N); 13824 EVT VT = N->getValueType(0); 13825 13826 // Check to see if this is a BUILD_VECTOR of a bunch of values 13827 // which come from any_extend or zero_extend nodes. If so, we can create 13828 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13829 // optimizations. We do not handle sign-extend because we can't fill the sign 13830 // using shuffles. 13831 EVT SourceType = MVT::Other; 13832 bool AllAnyExt = true; 13833 13834 for (unsigned i = 0; i != NumInScalars; ++i) { 13835 SDValue In = N->getOperand(i); 13836 // Ignore undef inputs. 13837 if (In.isUndef()) continue; 13838 13839 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13840 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13841 13842 // Abort if the element is not an extension. 13843 if (!ZeroExt && !AnyExt) { 13844 SourceType = MVT::Other; 13845 break; 13846 } 13847 13848 // The input is a ZeroExt or AnyExt. Check the original type. 13849 EVT InTy = In.getOperand(0).getValueType(); 13850 13851 // Check that all of the widened source types are the same. 13852 if (SourceType == MVT::Other) 13853 // First time. 13854 SourceType = InTy; 13855 else if (InTy != SourceType) { 13856 // Multiple income types. Abort. 13857 SourceType = MVT::Other; 13858 break; 13859 } 13860 13861 // Check if all of the extends are ANY_EXTENDs. 13862 AllAnyExt &= AnyExt; 13863 } 13864 13865 // In order to have valid types, all of the inputs must be extended from the 13866 // same source type and all of the inputs must be any or zero extend. 13867 // Scalar sizes must be a power of two. 13868 EVT OutScalarTy = VT.getScalarType(); 13869 bool ValidTypes = SourceType != MVT::Other && 13870 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13871 isPowerOf2_32(SourceType.getSizeInBits()); 13872 13873 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13874 // turn into a single shuffle instruction. 13875 if (!ValidTypes) 13876 return SDValue(); 13877 13878 bool isLE = DAG.getDataLayout().isLittleEndian(); 13879 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13880 assert(ElemRatio > 1 && "Invalid element size ratio"); 13881 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13882 DAG.getConstant(0, DL, SourceType); 13883 13884 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13885 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13886 13887 // Populate the new build_vector 13888 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13889 SDValue Cast = N->getOperand(i); 13890 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13891 Cast.getOpcode() == ISD::ZERO_EXTEND || 13892 Cast.isUndef()) && "Invalid cast opcode"); 13893 SDValue In; 13894 if (Cast.isUndef()) 13895 In = DAG.getUNDEF(SourceType); 13896 else 13897 In = Cast->getOperand(0); 13898 unsigned Index = isLE ? (i * ElemRatio) : 13899 (i * ElemRatio + (ElemRatio - 1)); 13900 13901 assert(Index < Ops.size() && "Invalid index"); 13902 Ops[Index] = In; 13903 } 13904 13905 // The type of the new BUILD_VECTOR node. 13906 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13907 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13908 "Invalid vector size"); 13909 // Check if the new vector type is legal. 13910 if (!isTypeLegal(VecVT)) return SDValue(); 13911 13912 // Make the new BUILD_VECTOR. 13913 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13914 13915 // The new BUILD_VECTOR node has the potential to be further optimized. 13916 AddToWorklist(BV.getNode()); 13917 // Bitcast to the desired type. 13918 return DAG.getBitcast(VT, BV); 13919 } 13920 13921 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13922 EVT VT = N->getValueType(0); 13923 13924 unsigned NumInScalars = N->getNumOperands(); 13925 SDLoc DL(N); 13926 13927 EVT SrcVT = MVT::Other; 13928 unsigned Opcode = ISD::DELETED_NODE; 13929 unsigned NumDefs = 0; 13930 13931 for (unsigned i = 0; i != NumInScalars; ++i) { 13932 SDValue In = N->getOperand(i); 13933 unsigned Opc = In.getOpcode(); 13934 13935 if (Opc == ISD::UNDEF) 13936 continue; 13937 13938 // If all scalar values are floats and converted from integers. 13939 if (Opcode == ISD::DELETED_NODE && 13940 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13941 Opcode = Opc; 13942 } 13943 13944 if (Opc != Opcode) 13945 return SDValue(); 13946 13947 EVT InVT = In.getOperand(0).getValueType(); 13948 13949 // If all scalar values are typed differently, bail out. It's chosen to 13950 // simplify BUILD_VECTOR of integer types. 13951 if (SrcVT == MVT::Other) 13952 SrcVT = InVT; 13953 if (SrcVT != InVT) 13954 return SDValue(); 13955 NumDefs++; 13956 } 13957 13958 // If the vector has just one element defined, it's not worth to fold it into 13959 // a vectorized one. 13960 if (NumDefs < 2) 13961 return SDValue(); 13962 13963 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13964 && "Should only handle conversion from integer to float."); 13965 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13966 13967 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13968 13969 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13970 return SDValue(); 13971 13972 // Just because the floating-point vector type is legal does not necessarily 13973 // mean that the corresponding integer vector type is. 13974 if (!isTypeLegal(NVT)) 13975 return SDValue(); 13976 13977 SmallVector<SDValue, 8> Opnds; 13978 for (unsigned i = 0; i != NumInScalars; ++i) { 13979 SDValue In = N->getOperand(i); 13980 13981 if (In.isUndef()) 13982 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13983 else 13984 Opnds.push_back(In.getOperand(0)); 13985 } 13986 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13987 AddToWorklist(BV.getNode()); 13988 13989 return DAG.getNode(Opcode, DL, VT, BV); 13990 } 13991 13992 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13993 ArrayRef<int> VectorMask, 13994 SDValue VecIn1, SDValue VecIn2, 13995 unsigned LeftIdx) { 13996 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13997 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13998 13999 EVT VT = N->getValueType(0); 14000 EVT InVT1 = VecIn1.getValueType(); 14001 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 14002 14003 unsigned Vec2Offset = InVT1.getVectorNumElements(); 14004 unsigned NumElems = VT.getVectorNumElements(); 14005 unsigned ShuffleNumElems = NumElems; 14006 14007 // We can't generate a shuffle node with mismatched input and output types. 14008 // Try to make the types match the type of the output. 14009 if (InVT1 != VT || InVT2 != VT) { 14010 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 14011 // If the output vector length is a multiple of both input lengths, 14012 // we can concatenate them and pad the rest with undefs. 14013 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 14014 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 14015 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 14016 ConcatOps[0] = VecIn1; 14017 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 14018 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 14019 VecIn2 = SDValue(); 14020 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 14021 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 14022 return SDValue(); 14023 14024 if (!VecIn2.getNode()) { 14025 // If we only have one input vector, and it's twice the size of the 14026 // output, split it in two. 14027 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 14028 DAG.getConstant(NumElems, DL, IdxTy)); 14029 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 14030 // Since we now have shorter input vectors, adjust the offset of the 14031 // second vector's start. 14032 Vec2Offset = NumElems; 14033 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 14034 // VecIn1 is wider than the output, and we have another, possibly 14035 // smaller input. Pad the smaller input with undefs, shuffle at the 14036 // input vector width, and extract the output. 14037 // The shuffle type is different than VT, so check legality again. 14038 if (LegalOperations && 14039 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 14040 return SDValue(); 14041 14042 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 14043 // lower it back into a BUILD_VECTOR. So if the inserted type is 14044 // illegal, don't even try. 14045 if (InVT1 != InVT2) { 14046 if (!TLI.isTypeLegal(InVT2)) 14047 return SDValue(); 14048 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 14049 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 14050 } 14051 ShuffleNumElems = NumElems * 2; 14052 } else { 14053 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 14054 // than VecIn1. We can't handle this for now - this case will disappear 14055 // when we start sorting the vectors by type. 14056 return SDValue(); 14057 } 14058 } else { 14059 // TODO: Support cases where the length mismatch isn't exactly by a 14060 // factor of 2. 14061 // TODO: Move this check upwards, so that if we have bad type 14062 // mismatches, we don't create any DAG nodes. 14063 return SDValue(); 14064 } 14065 } 14066 14067 // Initialize mask to undef. 14068 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 14069 14070 // Only need to run up to the number of elements actually used, not the 14071 // total number of elements in the shuffle - if we are shuffling a wider 14072 // vector, the high lanes should be set to undef. 14073 for (unsigned i = 0; i != NumElems; ++i) { 14074 if (VectorMask[i] <= 0) 14075 continue; 14076 14077 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 14078 if (VectorMask[i] == (int)LeftIdx) { 14079 Mask[i] = ExtIndex; 14080 } else if (VectorMask[i] == (int)LeftIdx + 1) { 14081 Mask[i] = Vec2Offset + ExtIndex; 14082 } 14083 } 14084 14085 // The type the input vectors may have changed above. 14086 InVT1 = VecIn1.getValueType(); 14087 14088 // If we already have a VecIn2, it should have the same type as VecIn1. 14089 // If we don't, get an undef/zero vector of the appropriate type. 14090 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 14091 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 14092 14093 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 14094 if (ShuffleNumElems > NumElems) 14095 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 14096 14097 return Shuffle; 14098 } 14099 14100 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 14101 // operations. If the types of the vectors we're extracting from allow it, 14102 // turn this into a vector_shuffle node. 14103 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 14104 SDLoc DL(N); 14105 EVT VT = N->getValueType(0); 14106 14107 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 14108 if (!isTypeLegal(VT)) 14109 return SDValue(); 14110 14111 // May only combine to shuffle after legalize if shuffle is legal. 14112 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 14113 return SDValue(); 14114 14115 bool UsesZeroVector = false; 14116 unsigned NumElems = N->getNumOperands(); 14117 14118 // Record, for each element of the newly built vector, which input vector 14119 // that element comes from. -1 stands for undef, 0 for the zero vector, 14120 // and positive values for the input vectors. 14121 // VectorMask maps each element to its vector number, and VecIn maps vector 14122 // numbers to their initial SDValues. 14123 14124 SmallVector<int, 8> VectorMask(NumElems, -1); 14125 SmallVector<SDValue, 8> VecIn; 14126 VecIn.push_back(SDValue()); 14127 14128 for (unsigned i = 0; i != NumElems; ++i) { 14129 SDValue Op = N->getOperand(i); 14130 14131 if (Op.isUndef()) 14132 continue; 14133 14134 // See if we can use a blend with a zero vector. 14135 // TODO: Should we generalize this to a blend with an arbitrary constant 14136 // vector? 14137 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14138 UsesZeroVector = true; 14139 VectorMask[i] = 0; 14140 continue; 14141 } 14142 14143 // Not an undef or zero. If the input is something other than an 14144 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14145 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14146 !isa<ConstantSDNode>(Op.getOperand(1))) 14147 return SDValue(); 14148 14149 SDValue ExtractedFromVec = Op.getOperand(0); 14150 14151 // All inputs must have the same element type as the output. 14152 if (VT.getVectorElementType() != 14153 ExtractedFromVec.getValueType().getVectorElementType()) 14154 return SDValue(); 14155 14156 // Have we seen this input vector before? 14157 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14158 // a map back from SDValues to numbers isn't worth it. 14159 unsigned Idx = std::distance( 14160 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14161 if (Idx == VecIn.size()) 14162 VecIn.push_back(ExtractedFromVec); 14163 14164 VectorMask[i] = Idx; 14165 } 14166 14167 // If we didn't find at least one input vector, bail out. 14168 if (VecIn.size() < 2) 14169 return SDValue(); 14170 14171 // TODO: We want to sort the vectors by descending length, so that adjacent 14172 // pairs have similar length, and the longer vector is always first in the 14173 // pair. 14174 14175 // TODO: Should this fire if some of the input vectors has illegal type (like 14176 // it does now), or should we let legalization run its course first? 14177 14178 // Shuffle phase: 14179 // Take pairs of vectors, and shuffle them so that the result has elements 14180 // from these vectors in the correct places. 14181 // For example, given: 14182 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14183 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14184 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14185 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14186 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14187 // We will generate: 14188 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14189 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14190 SmallVector<SDValue, 4> Shuffles; 14191 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14192 unsigned LeftIdx = 2 * In + 1; 14193 SDValue VecLeft = VecIn[LeftIdx]; 14194 SDValue VecRight = 14195 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14196 14197 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14198 VecRight, LeftIdx)) 14199 Shuffles.push_back(Shuffle); 14200 else 14201 return SDValue(); 14202 } 14203 14204 // If we need the zero vector as an "ingredient" in the blend tree, add it 14205 // to the list of shuffles. 14206 if (UsesZeroVector) 14207 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14208 : DAG.getConstantFP(0.0, DL, VT)); 14209 14210 // If we only have one shuffle, we're done. 14211 if (Shuffles.size() == 1) 14212 return Shuffles[0]; 14213 14214 // Update the vector mask to point to the post-shuffle vectors. 14215 for (int &Vec : VectorMask) 14216 if (Vec == 0) 14217 Vec = Shuffles.size() - 1; 14218 else 14219 Vec = (Vec - 1) / 2; 14220 14221 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14222 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14223 // generate: 14224 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14225 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14226 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14227 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14228 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14229 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14230 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14231 14232 // Make sure the initial size of the shuffle list is even. 14233 if (Shuffles.size() % 2) 14234 Shuffles.push_back(DAG.getUNDEF(VT)); 14235 14236 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14237 if (CurSize % 2) { 14238 Shuffles[CurSize] = DAG.getUNDEF(VT); 14239 CurSize++; 14240 } 14241 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14242 int Left = 2 * In; 14243 int Right = 2 * In + 1; 14244 SmallVector<int, 8> Mask(NumElems, -1); 14245 for (unsigned i = 0; i != NumElems; ++i) { 14246 if (VectorMask[i] == Left) { 14247 Mask[i] = i; 14248 VectorMask[i] = In; 14249 } else if (VectorMask[i] == Right) { 14250 Mask[i] = i + NumElems; 14251 VectorMask[i] = In; 14252 } 14253 } 14254 14255 Shuffles[In] = 14256 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14257 } 14258 } 14259 14260 return Shuffles[0]; 14261 } 14262 14263 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14264 EVT VT = N->getValueType(0); 14265 14266 // A vector built entirely of undefs is undef. 14267 if (ISD::allOperandsUndef(N)) 14268 return DAG.getUNDEF(VT); 14269 14270 // Check if we can express BUILD VECTOR via subvector extract. 14271 if (!LegalTypes && (N->getNumOperands() > 1)) { 14272 SDValue Op0 = N->getOperand(0); 14273 auto checkElem = [&](SDValue Op) -> uint64_t { 14274 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14275 (Op0.getOperand(0) == Op.getOperand(0))) 14276 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14277 return CNode->getZExtValue(); 14278 return -1; 14279 }; 14280 14281 int Offset = checkElem(Op0); 14282 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14283 if (Offset + i != checkElem(N->getOperand(i))) { 14284 Offset = -1; 14285 break; 14286 } 14287 } 14288 14289 if ((Offset == 0) && 14290 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14291 return Op0.getOperand(0); 14292 if ((Offset != -1) && 14293 ((Offset % N->getValueType(0).getVectorNumElements()) == 14294 0)) // IDX must be multiple of output size. 14295 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14296 Op0.getOperand(0), Op0.getOperand(1)); 14297 } 14298 14299 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14300 return V; 14301 14302 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14303 return V; 14304 14305 if (SDValue V = reduceBuildVecToShuffle(N)) 14306 return V; 14307 14308 return SDValue(); 14309 } 14310 14311 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14312 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14313 EVT OpVT = N->getOperand(0).getValueType(); 14314 14315 // If the operands are legal vectors, leave them alone. 14316 if (TLI.isTypeLegal(OpVT)) 14317 return SDValue(); 14318 14319 SDLoc DL(N); 14320 EVT VT = N->getValueType(0); 14321 SmallVector<SDValue, 8> Ops; 14322 14323 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14324 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14325 14326 // Keep track of what we encounter. 14327 bool AnyInteger = false; 14328 bool AnyFP = false; 14329 for (const SDValue &Op : N->ops()) { 14330 if (ISD::BITCAST == Op.getOpcode() && 14331 !Op.getOperand(0).getValueType().isVector()) 14332 Ops.push_back(Op.getOperand(0)); 14333 else if (ISD::UNDEF == Op.getOpcode()) 14334 Ops.push_back(ScalarUndef); 14335 else 14336 return SDValue(); 14337 14338 // Note whether we encounter an integer or floating point scalar. 14339 // If it's neither, bail out, it could be something weird like x86mmx. 14340 EVT LastOpVT = Ops.back().getValueType(); 14341 if (LastOpVT.isFloatingPoint()) 14342 AnyFP = true; 14343 else if (LastOpVT.isInteger()) 14344 AnyInteger = true; 14345 else 14346 return SDValue(); 14347 } 14348 14349 // If any of the operands is a floating point scalar bitcast to a vector, 14350 // use floating point types throughout, and bitcast everything. 14351 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14352 if (AnyFP) { 14353 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14354 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14355 if (AnyInteger) { 14356 for (SDValue &Op : Ops) { 14357 if (Op.getValueType() == SVT) 14358 continue; 14359 if (Op.isUndef()) 14360 Op = ScalarUndef; 14361 else 14362 Op = DAG.getBitcast(SVT, Op); 14363 } 14364 } 14365 } 14366 14367 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 14368 VT.getSizeInBits() / SVT.getSizeInBits()); 14369 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 14370 } 14371 14372 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 14373 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 14374 // most two distinct vectors the same size as the result, attempt to turn this 14375 // into a legal shuffle. 14376 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 14377 EVT VT = N->getValueType(0); 14378 EVT OpVT = N->getOperand(0).getValueType(); 14379 int NumElts = VT.getVectorNumElements(); 14380 int NumOpElts = OpVT.getVectorNumElements(); 14381 14382 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 14383 SmallVector<int, 8> Mask; 14384 14385 for (SDValue Op : N->ops()) { 14386 // Peek through any bitcast. 14387 while (Op.getOpcode() == ISD::BITCAST) 14388 Op = Op.getOperand(0); 14389 14390 // UNDEF nodes convert to UNDEF shuffle mask values. 14391 if (Op.isUndef()) { 14392 Mask.append((unsigned)NumOpElts, -1); 14393 continue; 14394 } 14395 14396 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14397 return SDValue(); 14398 14399 // What vector are we extracting the subvector from and at what index? 14400 SDValue ExtVec = Op.getOperand(0); 14401 14402 // We want the EVT of the original extraction to correctly scale the 14403 // extraction index. 14404 EVT ExtVT = ExtVec.getValueType(); 14405 14406 // Peek through any bitcast. 14407 while (ExtVec.getOpcode() == ISD::BITCAST) 14408 ExtVec = ExtVec.getOperand(0); 14409 14410 // UNDEF nodes convert to UNDEF shuffle mask values. 14411 if (ExtVec.isUndef()) { 14412 Mask.append((unsigned)NumOpElts, -1); 14413 continue; 14414 } 14415 14416 if (!isa<ConstantSDNode>(Op.getOperand(1))) 14417 return SDValue(); 14418 int ExtIdx = Op.getConstantOperandVal(1); 14419 14420 // Ensure that we are extracting a subvector from a vector the same 14421 // size as the result. 14422 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 14423 return SDValue(); 14424 14425 // Scale the subvector index to account for any bitcast. 14426 int NumExtElts = ExtVT.getVectorNumElements(); 14427 if (0 == (NumExtElts % NumElts)) 14428 ExtIdx /= (NumExtElts / NumElts); 14429 else if (0 == (NumElts % NumExtElts)) 14430 ExtIdx *= (NumElts / NumExtElts); 14431 else 14432 return SDValue(); 14433 14434 // At most we can reference 2 inputs in the final shuffle. 14435 if (SV0.isUndef() || SV0 == ExtVec) { 14436 SV0 = ExtVec; 14437 for (int i = 0; i != NumOpElts; ++i) 14438 Mask.push_back(i + ExtIdx); 14439 } else if (SV1.isUndef() || SV1 == ExtVec) { 14440 SV1 = ExtVec; 14441 for (int i = 0; i != NumOpElts; ++i) 14442 Mask.push_back(i + ExtIdx + NumElts); 14443 } else { 14444 return SDValue(); 14445 } 14446 } 14447 14448 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 14449 return SDValue(); 14450 14451 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 14452 DAG.getBitcast(VT, SV1), Mask); 14453 } 14454 14455 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 14456 // If we only have one input vector, we don't need to do any concatenation. 14457 if (N->getNumOperands() == 1) 14458 return N->getOperand(0); 14459 14460 // Check if all of the operands are undefs. 14461 EVT VT = N->getValueType(0); 14462 if (ISD::allOperandsUndef(N)) 14463 return DAG.getUNDEF(VT); 14464 14465 // Optimize concat_vectors where all but the first of the vectors are undef. 14466 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 14467 return Op.isUndef(); 14468 })) { 14469 SDValue In = N->getOperand(0); 14470 assert(In.getValueType().isVector() && "Must concat vectors"); 14471 14472 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 14473 if (In->getOpcode() == ISD::BITCAST && 14474 !In->getOperand(0)->getValueType(0).isVector()) { 14475 SDValue Scalar = In->getOperand(0); 14476 14477 // If the bitcast type isn't legal, it might be a trunc of a legal type; 14478 // look through the trunc so we can still do the transform: 14479 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 14480 if (Scalar->getOpcode() == ISD::TRUNCATE && 14481 !TLI.isTypeLegal(Scalar.getValueType()) && 14482 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 14483 Scalar = Scalar->getOperand(0); 14484 14485 EVT SclTy = Scalar->getValueType(0); 14486 14487 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 14488 return SDValue(); 14489 14490 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 14491 if (VNTNumElms < 2) 14492 return SDValue(); 14493 14494 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 14495 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 14496 return SDValue(); 14497 14498 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 14499 return DAG.getBitcast(VT, Res); 14500 } 14501 } 14502 14503 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 14504 // We have already tested above for an UNDEF only concatenation. 14505 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 14506 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 14507 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 14508 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 14509 }; 14510 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 14511 SmallVector<SDValue, 8> Opnds; 14512 EVT SVT = VT.getScalarType(); 14513 14514 EVT MinVT = SVT; 14515 if (!SVT.isFloatingPoint()) { 14516 // If BUILD_VECTOR are from built from integer, they may have different 14517 // operand types. Get the smallest type and truncate all operands to it. 14518 bool FoundMinVT = false; 14519 for (const SDValue &Op : N->ops()) 14520 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14521 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14522 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14523 FoundMinVT = true; 14524 } 14525 assert(FoundMinVT && "Concat vector type mismatch"); 14526 } 14527 14528 for (const SDValue &Op : N->ops()) { 14529 EVT OpVT = Op.getValueType(); 14530 unsigned NumElts = OpVT.getVectorNumElements(); 14531 14532 if (ISD::UNDEF == Op.getOpcode()) 14533 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14534 14535 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14536 if (SVT.isFloatingPoint()) { 14537 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14538 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14539 } else { 14540 for (unsigned i = 0; i != NumElts; ++i) 14541 Opnds.push_back( 14542 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14543 } 14544 } 14545 } 14546 14547 assert(VT.getVectorNumElements() == Opnds.size() && 14548 "Concat vector type mismatch"); 14549 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14550 } 14551 14552 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14553 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14554 return V; 14555 14556 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14557 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14558 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14559 return V; 14560 14561 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14562 // nodes often generate nop CONCAT_VECTOR nodes. 14563 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14564 // place the incoming vectors at the exact same location. 14565 SDValue SingleSource = SDValue(); 14566 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14567 14568 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14569 SDValue Op = N->getOperand(i); 14570 14571 if (Op.isUndef()) 14572 continue; 14573 14574 // Check if this is the identity extract: 14575 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14576 return SDValue(); 14577 14578 // Find the single incoming vector for the extract_subvector. 14579 if (SingleSource.getNode()) { 14580 if (Op.getOperand(0) != SingleSource) 14581 return SDValue(); 14582 } else { 14583 SingleSource = Op.getOperand(0); 14584 14585 // Check the source type is the same as the type of the result. 14586 // If not, this concat may extend the vector, so we can not 14587 // optimize it away. 14588 if (SingleSource.getValueType() != N->getValueType(0)) 14589 return SDValue(); 14590 } 14591 14592 unsigned IdentityIndex = i * PartNumElem; 14593 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14594 // The extract index must be constant. 14595 if (!CS) 14596 return SDValue(); 14597 14598 // Check that we are reading from the identity index. 14599 if (CS->getZExtValue() != IdentityIndex) 14600 return SDValue(); 14601 } 14602 14603 if (SingleSource.getNode()) 14604 return SingleSource; 14605 14606 return SDValue(); 14607 } 14608 14609 /// If we are extracting a subvector produced by a wide binary operator with at 14610 /// at least one operand that was the result of a vector concatenation, then try 14611 /// to use the narrow vector operands directly to avoid the concatenation and 14612 /// extraction. 14613 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 14614 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 14615 // some of these bailouts with other transforms. 14616 14617 // The extract index must be a constant, so we can map it to a concat operand. 14618 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 14619 if (!ExtractIndex) 14620 return SDValue(); 14621 14622 // Only handle the case where we are doubling and then halving. A larger ratio 14623 // may require more than two narrow binops to replace the wide binop. 14624 EVT VT = Extract->getValueType(0); 14625 unsigned NumElems = VT.getVectorNumElements(); 14626 assert((ExtractIndex->getZExtValue() % NumElems) == 0 && 14627 "Extract index is not a multiple of the vector length."); 14628 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2) 14629 return SDValue(); 14630 14631 // We are looking for an optionally bitcasted wide vector binary operator 14632 // feeding an extract subvector. 14633 SDValue BinOp = Extract->getOperand(0); 14634 if (BinOp.getOpcode() == ISD::BITCAST) 14635 BinOp = BinOp.getOperand(0); 14636 14637 // TODO: The motivating case for this transform is an x86 AVX1 target. That 14638 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 14639 // flavors, but no other 256-bit integer support. This could be extended to 14640 // handle any binop, but that may require fixing/adding other folds to avoid 14641 // codegen regressions. 14642 unsigned BOpcode = BinOp.getOpcode(); 14643 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 14644 return SDValue(); 14645 14646 // The binop must be a vector type, so we can chop it in half. 14647 EVT WideBVT = BinOp.getValueType(); 14648 if (!WideBVT.isVector()) 14649 return SDValue(); 14650 14651 // Bail out if the target does not support a narrower version of the binop. 14652 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 14653 WideBVT.getVectorNumElements() / 2); 14654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14655 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 14656 return SDValue(); 14657 14658 // Peek through bitcasts of the binary operator operands if needed. 14659 SDValue LHS = BinOp.getOperand(0); 14660 if (LHS.getOpcode() == ISD::BITCAST) 14661 LHS = LHS.getOperand(0); 14662 14663 SDValue RHS = BinOp.getOperand(1); 14664 if (RHS.getOpcode() == ISD::BITCAST) 14665 RHS = RHS.getOperand(0); 14666 14667 // We need at least one concatenation operation of a binop operand to make 14668 // this transform worthwhile. The concat must double the input vector sizes. 14669 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 14670 bool ConcatL = 14671 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 14672 bool ConcatR = 14673 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 14674 if (!ConcatL && !ConcatR) 14675 return SDValue(); 14676 14677 // If one of the binop operands was not the result of a concat, we must 14678 // extract a half-sized operand for our new narrow binop. We can't just reuse 14679 // the original extract index operand because we may have bitcasted. 14680 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems; 14681 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 14682 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 14683 SDLoc DL(Extract); 14684 14685 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 14686 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N) 14687 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN 14688 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 14689 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 14690 BinOp.getOperand(0), 14691 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 14692 14693 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 14694 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 14695 BinOp.getOperand(1), 14696 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT)); 14697 14698 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 14699 return DAG.getBitcast(VT, NarrowBinOp); 14700 } 14701 14702 /// If we are extracting a subvector from a wide vector load, convert to a 14703 /// narrow load to eliminate the extraction: 14704 /// (extract_subvector (load wide vector)) --> (load narrow vector) 14705 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 14706 // TODO: Add support for big-endian. The offset calculation must be adjusted. 14707 if (DAG.getDataLayout().isBigEndian()) 14708 return SDValue(); 14709 14710 // TODO: The one-use check is overly conservative. Check the cost of the 14711 // extract instead or remove that condition entirely. 14712 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 14713 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 14714 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() || 14715 !ExtIdx) 14716 return SDValue(); 14717 14718 // The narrow load will be offset from the base address of the old load if 14719 // we are extracting from something besides index 0 (little-endian). 14720 EVT VT = Extract->getValueType(0); 14721 SDLoc DL(Extract); 14722 SDValue BaseAddr = Ld->getOperand(1); 14723 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 14724 14725 // TODO: Use "BaseIndexOffset" to make this more effective. 14726 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 14727 MachineFunction &MF = DAG.getMachineFunction(); 14728 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 14729 VT.getStoreSize()); 14730 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 14731 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 14732 return NewLd; 14733 } 14734 14735 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14736 EVT NVT = N->getValueType(0); 14737 SDValue V = N->getOperand(0); 14738 14739 // Extract from UNDEF is UNDEF. 14740 if (V.isUndef()) 14741 return DAG.getUNDEF(NVT); 14742 14743 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 14744 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 14745 return NarrowLoad; 14746 14747 // Combine: 14748 // (extract_subvec (concat V1, V2, ...), i) 14749 // Into: 14750 // Vi if possible 14751 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14752 // type. 14753 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14754 isa<ConstantSDNode>(N->getOperand(1)) && 14755 V->getOperand(0).getValueType() == NVT) { 14756 unsigned Idx = N->getConstantOperandVal(1); 14757 unsigned NumElems = NVT.getVectorNumElements(); 14758 assert((Idx % NumElems) == 0 && 14759 "IDX in concat is not a multiple of the result vector length."); 14760 return V->getOperand(Idx / NumElems); 14761 } 14762 14763 // Skip bitcasting 14764 if (V->getOpcode() == ISD::BITCAST) 14765 V = V.getOperand(0); 14766 14767 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14768 // Handle only simple case where vector being inserted and vector 14769 // being extracted are of same size. 14770 EVT SmallVT = V->getOperand(1).getValueType(); 14771 if (!NVT.bitsEq(SmallVT)) 14772 return SDValue(); 14773 14774 // Only handle cases where both indexes are constants. 14775 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14776 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14777 14778 if (InsIdx && ExtIdx) { 14779 // Combine: 14780 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14781 // Into: 14782 // indices are equal or bit offsets are equal => V1 14783 // otherwise => (extract_subvec V1, ExtIdx) 14784 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14785 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14786 return DAG.getBitcast(NVT, V->getOperand(1)); 14787 return DAG.getNode( 14788 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14789 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14790 N->getOperand(1)); 14791 } 14792 } 14793 14794 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 14795 return NarrowBOp; 14796 14797 return SDValue(); 14798 } 14799 14800 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14801 SDValue V, SelectionDAG &DAG) { 14802 SDLoc DL(V); 14803 EVT VT = V.getValueType(); 14804 14805 switch (V.getOpcode()) { 14806 default: 14807 return V; 14808 14809 case ISD::CONCAT_VECTORS: { 14810 EVT OpVT = V->getOperand(0).getValueType(); 14811 int OpSize = OpVT.getVectorNumElements(); 14812 SmallBitVector OpUsedElements(OpSize, false); 14813 bool FoundSimplification = false; 14814 SmallVector<SDValue, 4> NewOps; 14815 NewOps.reserve(V->getNumOperands()); 14816 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14817 SDValue Op = V->getOperand(i); 14818 bool OpUsed = false; 14819 for (int j = 0; j < OpSize; ++j) 14820 if (UsedElements[i * OpSize + j]) { 14821 OpUsedElements[j] = true; 14822 OpUsed = true; 14823 } 14824 NewOps.push_back( 14825 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14826 : DAG.getUNDEF(OpVT)); 14827 FoundSimplification |= Op == NewOps.back(); 14828 OpUsedElements.reset(); 14829 } 14830 if (FoundSimplification) 14831 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14832 return V; 14833 } 14834 14835 case ISD::INSERT_SUBVECTOR: { 14836 SDValue BaseV = V->getOperand(0); 14837 SDValue SubV = V->getOperand(1); 14838 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14839 if (!IdxN) 14840 return V; 14841 14842 int SubSize = SubV.getValueType().getVectorNumElements(); 14843 int Idx = IdxN->getZExtValue(); 14844 bool SubVectorUsed = false; 14845 SmallBitVector SubUsedElements(SubSize, false); 14846 for (int i = 0; i < SubSize; ++i) 14847 if (UsedElements[i + Idx]) { 14848 SubVectorUsed = true; 14849 SubUsedElements[i] = true; 14850 UsedElements[i + Idx] = false; 14851 } 14852 14853 // Now recurse on both the base and sub vectors. 14854 SDValue SimplifiedSubV = 14855 SubVectorUsed 14856 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14857 : DAG.getUNDEF(SubV.getValueType()); 14858 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14859 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14860 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14861 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14862 return V; 14863 } 14864 } 14865 } 14866 14867 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14868 SDValue N1, SelectionDAG &DAG) { 14869 EVT VT = SVN->getValueType(0); 14870 int NumElts = VT.getVectorNumElements(); 14871 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14872 for (int M : SVN->getMask()) 14873 if (M >= 0 && M < NumElts) 14874 N0UsedElements[M] = true; 14875 else if (M >= NumElts) 14876 N1UsedElements[M - NumElts] = true; 14877 14878 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14879 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14880 if (S0 == N0 && S1 == N1) 14881 return SDValue(); 14882 14883 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14884 } 14885 14886 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14887 // or turn a shuffle of a single concat into simpler shuffle then concat. 14888 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14889 EVT VT = N->getValueType(0); 14890 unsigned NumElts = VT.getVectorNumElements(); 14891 14892 SDValue N0 = N->getOperand(0); 14893 SDValue N1 = N->getOperand(1); 14894 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14895 14896 SmallVector<SDValue, 4> Ops; 14897 EVT ConcatVT = N0.getOperand(0).getValueType(); 14898 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14899 unsigned NumConcats = NumElts / NumElemsPerConcat; 14900 14901 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14902 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14903 // half vector elements. 14904 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14905 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14906 SVN->getMask().end(), [](int i) { return i == -1; })) { 14907 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14908 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14909 N1 = DAG.getUNDEF(ConcatVT); 14910 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14911 } 14912 14913 // Look at every vector that's inserted. We're looking for exact 14914 // subvector-sized copies from a concatenated vector 14915 for (unsigned I = 0; I != NumConcats; ++I) { 14916 // Make sure we're dealing with a copy. 14917 unsigned Begin = I * NumElemsPerConcat; 14918 bool AllUndef = true, NoUndef = true; 14919 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14920 if (SVN->getMaskElt(J) >= 0) 14921 AllUndef = false; 14922 else 14923 NoUndef = false; 14924 } 14925 14926 if (NoUndef) { 14927 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14928 return SDValue(); 14929 14930 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14931 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14932 return SDValue(); 14933 14934 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14935 if (FirstElt < N0.getNumOperands()) 14936 Ops.push_back(N0.getOperand(FirstElt)); 14937 else 14938 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14939 14940 } else if (AllUndef) { 14941 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14942 } else { // Mixed with general masks and undefs, can't do optimization. 14943 return SDValue(); 14944 } 14945 } 14946 14947 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14948 } 14949 14950 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14951 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14952 // 14953 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14954 // a simplification in some sense, but it isn't appropriate in general: some 14955 // BUILD_VECTORs are substantially cheaper than others. The general case 14956 // of a BUILD_VECTOR requires inserting each element individually (or 14957 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14958 // all constants is a single constant pool load. A BUILD_VECTOR where each 14959 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14960 // are undef lowers to a small number of element insertions. 14961 // 14962 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14963 // We don't fold shuffles where one side is a non-zero constant, and we don't 14964 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14965 // non-constant operands. This seems to work out reasonably well in practice. 14966 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14967 SelectionDAG &DAG, 14968 const TargetLowering &TLI) { 14969 EVT VT = SVN->getValueType(0); 14970 unsigned NumElts = VT.getVectorNumElements(); 14971 SDValue N0 = SVN->getOperand(0); 14972 SDValue N1 = SVN->getOperand(1); 14973 14974 if (!N0->hasOneUse() || !N1->hasOneUse()) 14975 return SDValue(); 14976 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14977 // discussed above. 14978 if (!N1.isUndef()) { 14979 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14980 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14981 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14982 return SDValue(); 14983 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14984 return SDValue(); 14985 } 14986 14987 SmallVector<SDValue, 8> Ops; 14988 SmallSet<SDValue, 16> DuplicateOps; 14989 for (int M : SVN->getMask()) { 14990 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14991 if (M >= 0) { 14992 int Idx = M < (int)NumElts ? M : M - NumElts; 14993 SDValue &S = (M < (int)NumElts ? N0 : N1); 14994 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14995 Op = S.getOperand(Idx); 14996 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14997 if (Idx == 0) 14998 Op = S.getOperand(0); 14999 } else { 15000 // Operand can't be combined - bail out. 15001 return SDValue(); 15002 } 15003 } 15004 15005 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 15006 // fine, but it's likely to generate low-quality code if the target can't 15007 // reconstruct an appropriate shuffle. 15008 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 15009 if (!DuplicateOps.insert(Op).second) 15010 return SDValue(); 15011 15012 Ops.push_back(Op); 15013 } 15014 // BUILD_VECTOR requires all inputs to be of the same type, find the 15015 // maximum type and extend them all. 15016 EVT SVT = VT.getScalarType(); 15017 if (SVT.isInteger()) 15018 for (SDValue &Op : Ops) 15019 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 15020 if (SVT != VT.getScalarType()) 15021 for (SDValue &Op : Ops) 15022 Op = TLI.isZExtFree(Op.getValueType(), SVT) 15023 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 15024 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 15025 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 15026 } 15027 15028 // Match shuffles that can be converted to any_vector_extend_in_reg. 15029 // This is often generated during legalization. 15030 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 15031 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 15032 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 15033 SelectionDAG &DAG, 15034 const TargetLowering &TLI, 15035 bool LegalOperations) { 15036 EVT VT = SVN->getValueType(0); 15037 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15038 15039 // TODO Add support for big-endian when we have a test case. 15040 if (!VT.isInteger() || IsBigEndian) 15041 return SDValue(); 15042 15043 unsigned NumElts = VT.getVectorNumElements(); 15044 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15045 ArrayRef<int> Mask = SVN->getMask(); 15046 SDValue N0 = SVN->getOperand(0); 15047 15048 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 15049 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 15050 for (unsigned i = 0; i != NumElts; ++i) { 15051 if (Mask[i] < 0) 15052 continue; 15053 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 15054 continue; 15055 return false; 15056 } 15057 return true; 15058 }; 15059 15060 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 15061 // power-of-2 extensions as they are the most likely. 15062 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 15063 if (!isAnyExtend(Scale)) 15064 continue; 15065 15066 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 15067 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 15068 if (!LegalOperations || 15069 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 15070 return DAG.getBitcast(VT, 15071 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 15072 } 15073 15074 return SDValue(); 15075 } 15076 15077 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 15078 // each source element of a large type into the lowest elements of a smaller 15079 // destination type. This is often generated during legalization. 15080 // If the source node itself was a '*_extend_vector_inreg' node then we should 15081 // then be able to remove it. 15082 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 15083 SelectionDAG &DAG) { 15084 EVT VT = SVN->getValueType(0); 15085 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 15086 15087 // TODO Add support for big-endian when we have a test case. 15088 if (!VT.isInteger() || IsBigEndian) 15089 return SDValue(); 15090 15091 SDValue N0 = SVN->getOperand(0); 15092 while (N0.getOpcode() == ISD::BITCAST) 15093 N0 = N0.getOperand(0); 15094 15095 unsigned Opcode = N0.getOpcode(); 15096 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 15097 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 15098 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 15099 return SDValue(); 15100 15101 SDValue N00 = N0.getOperand(0); 15102 ArrayRef<int> Mask = SVN->getMask(); 15103 unsigned NumElts = VT.getVectorNumElements(); 15104 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 15105 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 15106 15107 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 15108 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 15109 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 15110 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 15111 for (unsigned i = 0; i != NumElts; ++i) { 15112 if (Mask[i] < 0) 15113 continue; 15114 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 15115 continue; 15116 return false; 15117 } 15118 return true; 15119 }; 15120 15121 // At the moment we just handle the case where we've truncated back to the 15122 // same size as before the extension. 15123 // TODO: handle more extension/truncation cases as cases arise. 15124 if (EltSizeInBits != ExtSrcSizeInBits) 15125 return SDValue(); 15126 15127 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 15128 // power-of-2 truncations as they are the most likely. 15129 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 15130 if (isTruncate(Scale)) 15131 return DAG.getBitcast(VT, N00); 15132 15133 return SDValue(); 15134 } 15135 15136 // Combine shuffles of splat-shuffles of the form: 15137 // shuffle (shuffle V, undef, splat-mask), undef, M 15138 // If splat-mask contains undef elements, we need to be careful about 15139 // introducing undef's in the folded mask which are not the result of composing 15140 // the masks of the shuffles. 15141 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 15142 ShuffleVectorSDNode *Splat, 15143 SelectionDAG &DAG) { 15144 ArrayRef<int> SplatMask = Splat->getMask(); 15145 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 15146 15147 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 15148 // every undef mask element in the splat-shuffle has a corresponding undef 15149 // element in the user-shuffle's mask or if the composition of mask elements 15150 // would result in undef. 15151 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 15152 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 15153 // In this case it is not legal to simplify to the splat-shuffle because we 15154 // may be exposing the users of the shuffle an undef element at index 1 15155 // which was not there before the combine. 15156 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 15157 // In this case the composition of masks yields SplatMask, so it's ok to 15158 // simplify to the splat-shuffle. 15159 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 15160 // In this case the composed mask includes all undef elements of SplatMask 15161 // and in addition sets element zero to undef. It is safe to simplify to 15162 // the splat-shuffle. 15163 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 15164 ArrayRef<int> SplatMask) { 15165 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 15166 if (UserMask[i] != -1 && SplatMask[i] == -1 && 15167 SplatMask[UserMask[i]] != -1) 15168 return false; 15169 return true; 15170 }; 15171 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 15172 return SDValue(Splat, 0); 15173 15174 // Create a new shuffle with a mask that is composed of the two shuffles' 15175 // masks. 15176 SmallVector<int, 32> NewMask; 15177 for (int Idx : UserMask) 15178 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 15179 15180 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 15181 Splat->getOperand(0), Splat->getOperand(1), 15182 NewMask); 15183 } 15184 15185 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 15186 EVT VT = N->getValueType(0); 15187 unsigned NumElts = VT.getVectorNumElements(); 15188 15189 SDValue N0 = N->getOperand(0); 15190 SDValue N1 = N->getOperand(1); 15191 15192 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 15193 15194 // Canonicalize shuffle undef, undef -> undef 15195 if (N0.isUndef() && N1.isUndef()) 15196 return DAG.getUNDEF(VT); 15197 15198 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 15199 15200 // Canonicalize shuffle v, v -> v, undef 15201 if (N0 == N1) { 15202 SmallVector<int, 8> NewMask; 15203 for (unsigned i = 0; i != NumElts; ++i) { 15204 int Idx = SVN->getMaskElt(i); 15205 if (Idx >= (int)NumElts) Idx -= NumElts; 15206 NewMask.push_back(Idx); 15207 } 15208 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 15209 } 15210 15211 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 15212 if (N0.isUndef()) 15213 return DAG.getCommutedVectorShuffle(*SVN); 15214 15215 // Remove references to rhs if it is undef 15216 if (N1.isUndef()) { 15217 bool Changed = false; 15218 SmallVector<int, 8> NewMask; 15219 for (unsigned i = 0; i != NumElts; ++i) { 15220 int Idx = SVN->getMaskElt(i); 15221 if (Idx >= (int)NumElts) { 15222 Idx = -1; 15223 Changed = true; 15224 } 15225 NewMask.push_back(Idx); 15226 } 15227 if (Changed) 15228 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 15229 } 15230 15231 // A shuffle of a single vector that is a splat can always be folded. 15232 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 15233 if (N1->isUndef() && N0Shuf->isSplat()) 15234 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 15235 15236 // If it is a splat, check if the argument vector is another splat or a 15237 // build_vector. 15238 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 15239 SDNode *V = N0.getNode(); 15240 15241 // If this is a bit convert that changes the element type of the vector but 15242 // not the number of vector elements, look through it. Be careful not to 15243 // look though conversions that change things like v4f32 to v2f64. 15244 if (V->getOpcode() == ISD::BITCAST) { 15245 SDValue ConvInput = V->getOperand(0); 15246 if (ConvInput.getValueType().isVector() && 15247 ConvInput.getValueType().getVectorNumElements() == NumElts) 15248 V = ConvInput.getNode(); 15249 } 15250 15251 if (V->getOpcode() == ISD::BUILD_VECTOR) { 15252 assert(V->getNumOperands() == NumElts && 15253 "BUILD_VECTOR has wrong number of operands"); 15254 SDValue Base; 15255 bool AllSame = true; 15256 for (unsigned i = 0; i != NumElts; ++i) { 15257 if (!V->getOperand(i).isUndef()) { 15258 Base = V->getOperand(i); 15259 break; 15260 } 15261 } 15262 // Splat of <u, u, u, u>, return <u, u, u, u> 15263 if (!Base.getNode()) 15264 return N0; 15265 for (unsigned i = 0; i != NumElts; ++i) { 15266 if (V->getOperand(i) != Base) { 15267 AllSame = false; 15268 break; 15269 } 15270 } 15271 // Splat of <x, x, x, x>, return <x, x, x, x> 15272 if (AllSame) 15273 return N0; 15274 15275 // Canonicalize any other splat as a build_vector. 15276 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 15277 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 15278 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 15279 15280 // We may have jumped through bitcasts, so the type of the 15281 // BUILD_VECTOR may not match the type of the shuffle. 15282 if (V->getValueType(0) != VT) 15283 NewBV = DAG.getBitcast(VT, NewBV); 15284 return NewBV; 15285 } 15286 } 15287 15288 // There are various patterns used to build up a vector from smaller vectors, 15289 // subvectors, or elements. Scan chains of these and replace unused insertions 15290 // or components with undef. 15291 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 15292 return S; 15293 15294 // Match shuffles that can be converted to any_vector_extend_in_reg. 15295 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 15296 return V; 15297 15298 // Combine "truncate_vector_in_reg" style shuffles. 15299 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 15300 return V; 15301 15302 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 15303 Level < AfterLegalizeVectorOps && 15304 (N1.isUndef() || 15305 (N1.getOpcode() == ISD::CONCAT_VECTORS && 15306 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 15307 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 15308 return V; 15309 } 15310 15311 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15312 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15313 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15314 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 15315 return Res; 15316 15317 // If this shuffle only has a single input that is a bitcasted shuffle, 15318 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 15319 // back to their original types. 15320 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 15321 N1.isUndef() && Level < AfterLegalizeVectorOps && 15322 TLI.isTypeLegal(VT)) { 15323 15324 // Peek through the bitcast only if there is one user. 15325 SDValue BC0 = N0; 15326 while (BC0.getOpcode() == ISD::BITCAST) { 15327 if (!BC0.hasOneUse()) 15328 break; 15329 BC0 = BC0.getOperand(0); 15330 } 15331 15332 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 15333 if (Scale == 1) 15334 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 15335 15336 SmallVector<int, 8> NewMask; 15337 for (int M : Mask) 15338 for (int s = 0; s != Scale; ++s) 15339 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 15340 return NewMask; 15341 }; 15342 15343 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 15344 EVT SVT = VT.getScalarType(); 15345 EVT InnerVT = BC0->getValueType(0); 15346 EVT InnerSVT = InnerVT.getScalarType(); 15347 15348 // Determine which shuffle works with the smaller scalar type. 15349 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 15350 EVT ScaleSVT = ScaleVT.getScalarType(); 15351 15352 if (TLI.isTypeLegal(ScaleVT) && 15353 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 15354 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 15355 15356 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15357 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15358 15359 // Scale the shuffle masks to the smaller scalar type. 15360 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 15361 SmallVector<int, 8> InnerMask = 15362 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 15363 SmallVector<int, 8> OuterMask = 15364 ScaleShuffleMask(SVN->getMask(), OuterScale); 15365 15366 // Merge the shuffle masks. 15367 SmallVector<int, 8> NewMask; 15368 for (int M : OuterMask) 15369 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 15370 15371 // Test for shuffle mask legality over both commutations. 15372 SDValue SV0 = BC0->getOperand(0); 15373 SDValue SV1 = BC0->getOperand(1); 15374 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15375 if (!LegalMask) { 15376 std::swap(SV0, SV1); 15377 ShuffleVectorSDNode::commuteMask(NewMask); 15378 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15379 } 15380 15381 if (LegalMask) { 15382 SV0 = DAG.getBitcast(ScaleVT, SV0); 15383 SV1 = DAG.getBitcast(ScaleVT, SV1); 15384 return DAG.getBitcast( 15385 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 15386 } 15387 } 15388 } 15389 } 15390 15391 // Canonicalize shuffles according to rules: 15392 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 15393 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 15394 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 15395 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 15396 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 15397 TLI.isTypeLegal(VT)) { 15398 // The incoming shuffle must be of the same type as the result of the 15399 // current shuffle. 15400 assert(N1->getOperand(0).getValueType() == VT && 15401 "Shuffle types don't match"); 15402 15403 SDValue SV0 = N1->getOperand(0); 15404 SDValue SV1 = N1->getOperand(1); 15405 bool HasSameOp0 = N0 == SV0; 15406 bool IsSV1Undef = SV1.isUndef(); 15407 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 15408 // Commute the operands of this shuffle so that next rule 15409 // will trigger. 15410 return DAG.getCommutedVectorShuffle(*SVN); 15411 } 15412 15413 // Try to fold according to rules: 15414 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15415 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15416 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15417 // Don't try to fold shuffles with illegal type. 15418 // Only fold if this shuffle is the only user of the other shuffle. 15419 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 15420 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 15421 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 15422 15423 // Don't try to fold splats; they're likely to simplify somehow, or they 15424 // might be free. 15425 if (OtherSV->isSplat()) 15426 return SDValue(); 15427 15428 // The incoming shuffle must be of the same type as the result of the 15429 // current shuffle. 15430 assert(OtherSV->getOperand(0).getValueType() == VT && 15431 "Shuffle types don't match"); 15432 15433 SDValue SV0, SV1; 15434 SmallVector<int, 4> Mask; 15435 // Compute the combined shuffle mask for a shuffle with SV0 as the first 15436 // operand, and SV1 as the second operand. 15437 for (unsigned i = 0; i != NumElts; ++i) { 15438 int Idx = SVN->getMaskElt(i); 15439 if (Idx < 0) { 15440 // Propagate Undef. 15441 Mask.push_back(Idx); 15442 continue; 15443 } 15444 15445 SDValue CurrentVec; 15446 if (Idx < (int)NumElts) { 15447 // This shuffle index refers to the inner shuffle N0. Lookup the inner 15448 // shuffle mask to identify which vector is actually referenced. 15449 Idx = OtherSV->getMaskElt(Idx); 15450 if (Idx < 0) { 15451 // Propagate Undef. 15452 Mask.push_back(Idx); 15453 continue; 15454 } 15455 15456 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 15457 : OtherSV->getOperand(1); 15458 } else { 15459 // This shuffle index references an element within N1. 15460 CurrentVec = N1; 15461 } 15462 15463 // Simple case where 'CurrentVec' is UNDEF. 15464 if (CurrentVec.isUndef()) { 15465 Mask.push_back(-1); 15466 continue; 15467 } 15468 15469 // Canonicalize the shuffle index. We don't know yet if CurrentVec 15470 // will be the first or second operand of the combined shuffle. 15471 Idx = Idx % NumElts; 15472 if (!SV0.getNode() || SV0 == CurrentVec) { 15473 // Ok. CurrentVec is the left hand side. 15474 // Update the mask accordingly. 15475 SV0 = CurrentVec; 15476 Mask.push_back(Idx); 15477 continue; 15478 } 15479 15480 // Bail out if we cannot convert the shuffle pair into a single shuffle. 15481 if (SV1.getNode() && SV1 != CurrentVec) 15482 return SDValue(); 15483 15484 // Ok. CurrentVec is the right hand side. 15485 // Update the mask accordingly. 15486 SV1 = CurrentVec; 15487 Mask.push_back(Idx + NumElts); 15488 } 15489 15490 // Check if all indices in Mask are Undef. In case, propagate Undef. 15491 bool isUndefMask = true; 15492 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 15493 isUndefMask &= Mask[i] < 0; 15494 15495 if (isUndefMask) 15496 return DAG.getUNDEF(VT); 15497 15498 if (!SV0.getNode()) 15499 SV0 = DAG.getUNDEF(VT); 15500 if (!SV1.getNode()) 15501 SV1 = DAG.getUNDEF(VT); 15502 15503 // Avoid introducing shuffles with illegal mask. 15504 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 15505 ShuffleVectorSDNode::commuteMask(Mask); 15506 15507 if (!TLI.isShuffleMaskLegal(Mask, VT)) 15508 return SDValue(); 15509 15510 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 15511 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 15512 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 15513 std::swap(SV0, SV1); 15514 } 15515 15516 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15517 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15518 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15519 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 15520 } 15521 15522 return SDValue(); 15523 } 15524 15525 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 15526 SDValue InVal = N->getOperand(0); 15527 EVT VT = N->getValueType(0); 15528 15529 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 15530 // with a VECTOR_SHUFFLE. 15531 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15532 SDValue InVec = InVal->getOperand(0); 15533 SDValue EltNo = InVal->getOperand(1); 15534 15535 // FIXME: We could support implicit truncation if the shuffle can be 15536 // scaled to a smaller vector scalar type. 15537 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 15538 if (C0 && VT == InVec.getValueType() && 15539 VT.getScalarType() == InVal.getValueType()) { 15540 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 15541 int Elt = C0->getZExtValue(); 15542 NewMask[0] = Elt; 15543 15544 if (TLI.isShuffleMaskLegal(NewMask, VT)) 15545 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 15546 NewMask); 15547 } 15548 } 15549 15550 return SDValue(); 15551 } 15552 15553 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 15554 EVT VT = N->getValueType(0); 15555 SDValue N0 = N->getOperand(0); 15556 SDValue N1 = N->getOperand(1); 15557 SDValue N2 = N->getOperand(2); 15558 15559 // If inserting an UNDEF, just return the original vector. 15560 if (N1.isUndef()) 15561 return N0; 15562 15563 // If this is an insert of an extracted vector into an undef vector, we can 15564 // just use the input to the extract. 15565 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 15566 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 15567 return N1.getOperand(0); 15568 15569 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 15570 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 15571 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 15572 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 15573 N0.getOperand(1).getValueType() == N1.getValueType() && 15574 N0.getOperand(2) == N2) 15575 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 15576 N1, N2); 15577 15578 if (!isa<ConstantSDNode>(N2)) 15579 return SDValue(); 15580 15581 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 15582 15583 // Canonicalize insert_subvector dag nodes. 15584 // Example: 15585 // (insert_subvector (insert_subvector A, Idx0), Idx1) 15586 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 15587 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 15588 N1.getValueType() == N0.getOperand(1).getValueType() && 15589 isa<ConstantSDNode>(N0.getOperand(2))) { 15590 unsigned OtherIdx = N0.getConstantOperandVal(2); 15591 if (InsIdx < OtherIdx) { 15592 // Swap nodes. 15593 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 15594 N0.getOperand(0), N1, N2); 15595 AddToWorklist(NewOp.getNode()); 15596 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 15597 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 15598 } 15599 } 15600 15601 // If the input vector is a concatenation, and the insert replaces 15602 // one of the pieces, we can optimize into a single concat_vectors. 15603 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 15604 N0.getOperand(0).getValueType() == N1.getValueType()) { 15605 unsigned Factor = N1.getValueType().getVectorNumElements(); 15606 15607 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 15608 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 15609 15610 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15611 } 15612 15613 return SDValue(); 15614 } 15615 15616 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 15617 SDValue N0 = N->getOperand(0); 15618 15619 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 15620 if (N0->getOpcode() == ISD::FP16_TO_FP) 15621 return N0->getOperand(0); 15622 15623 return SDValue(); 15624 } 15625 15626 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 15627 SDValue N0 = N->getOperand(0); 15628 15629 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 15630 if (N0->getOpcode() == ISD::AND) { 15631 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 15632 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 15633 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 15634 N0.getOperand(0)); 15635 } 15636 } 15637 15638 return SDValue(); 15639 } 15640 15641 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 15642 /// with the destination vector and a zero vector. 15643 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 15644 /// vector_shuffle V, Zero, <0, 4, 2, 4> 15645 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 15646 EVT VT = N->getValueType(0); 15647 SDValue LHS = N->getOperand(0); 15648 SDValue RHS = N->getOperand(1); 15649 SDLoc DL(N); 15650 15651 // Make sure we're not running after operation legalization where it 15652 // may have custom lowered the vector shuffles. 15653 if (LegalOperations) 15654 return SDValue(); 15655 15656 if (N->getOpcode() != ISD::AND) 15657 return SDValue(); 15658 15659 if (RHS.getOpcode() == ISD::BITCAST) 15660 RHS = RHS.getOperand(0); 15661 15662 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 15663 return SDValue(); 15664 15665 EVT RVT = RHS.getValueType(); 15666 unsigned NumElts = RHS.getNumOperands(); 15667 15668 // Attempt to create a valid clear mask, splitting the mask into 15669 // sub elements and checking to see if each is 15670 // all zeros or all ones - suitable for shuffle masking. 15671 auto BuildClearMask = [&](int Split) { 15672 int NumSubElts = NumElts * Split; 15673 int NumSubBits = RVT.getScalarSizeInBits() / Split; 15674 15675 SmallVector<int, 8> Indices; 15676 for (int i = 0; i != NumSubElts; ++i) { 15677 int EltIdx = i / Split; 15678 int SubIdx = i % Split; 15679 SDValue Elt = RHS.getOperand(EltIdx); 15680 if (Elt.isUndef()) { 15681 Indices.push_back(-1); 15682 continue; 15683 } 15684 15685 APInt Bits; 15686 if (isa<ConstantSDNode>(Elt)) 15687 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 15688 else if (isa<ConstantFPSDNode>(Elt)) 15689 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 15690 else 15691 return SDValue(); 15692 15693 // Extract the sub element from the constant bit mask. 15694 if (DAG.getDataLayout().isBigEndian()) { 15695 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 15696 } else { 15697 Bits.lshrInPlace(SubIdx * NumSubBits); 15698 } 15699 15700 if (Split > 1) 15701 Bits = Bits.trunc(NumSubBits); 15702 15703 if (Bits.isAllOnesValue()) 15704 Indices.push_back(i); 15705 else if (Bits == 0) 15706 Indices.push_back(i + NumSubElts); 15707 else 15708 return SDValue(); 15709 } 15710 15711 // Let's see if the target supports this vector_shuffle. 15712 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 15713 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 15714 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 15715 return SDValue(); 15716 15717 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 15718 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 15719 DAG.getBitcast(ClearVT, LHS), 15720 Zero, Indices)); 15721 }; 15722 15723 // Determine maximum split level (byte level masking). 15724 int MaxSplit = 1; 15725 if (RVT.getScalarSizeInBits() % 8 == 0) 15726 MaxSplit = RVT.getScalarSizeInBits() / 8; 15727 15728 for (int Split = 1; Split <= MaxSplit; ++Split) 15729 if (RVT.getScalarSizeInBits() % Split == 0) 15730 if (SDValue S = BuildClearMask(Split)) 15731 return S; 15732 15733 return SDValue(); 15734 } 15735 15736 /// Visit a binary vector operation, like ADD. 15737 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15738 assert(N->getValueType(0).isVector() && 15739 "SimplifyVBinOp only works on vectors!"); 15740 15741 SDValue LHS = N->getOperand(0); 15742 SDValue RHS = N->getOperand(1); 15743 SDValue Ops[] = {LHS, RHS}; 15744 15745 // See if we can constant fold the vector operation. 15746 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15747 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15748 return Fold; 15749 15750 // Try to convert a constant mask AND into a shuffle clear mask. 15751 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15752 return Shuffle; 15753 15754 // Type legalization might introduce new shuffles in the DAG. 15755 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15756 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15757 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15758 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15759 LHS.getOperand(1).isUndef() && 15760 RHS.getOperand(1).isUndef()) { 15761 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15762 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15763 15764 if (SVN0->getMask().equals(SVN1->getMask())) { 15765 EVT VT = N->getValueType(0); 15766 SDValue UndefVector = LHS.getOperand(1); 15767 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15768 LHS.getOperand(0), RHS.getOperand(0), 15769 N->getFlags()); 15770 AddUsersToWorklist(N); 15771 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15772 SVN0->getMask()); 15773 } 15774 } 15775 15776 return SDValue(); 15777 } 15778 15779 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15780 SDValue N2) { 15781 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15782 15783 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15784 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15785 15786 // If we got a simplified select_cc node back from SimplifySelectCC, then 15787 // break it down into a new SETCC node, and a new SELECT node, and then return 15788 // the SELECT node, since we were called with a SELECT node. 15789 if (SCC.getNode()) { 15790 // Check to see if we got a select_cc back (to turn into setcc/select). 15791 // Otherwise, just return whatever node we got back, like fabs. 15792 if (SCC.getOpcode() == ISD::SELECT_CC) { 15793 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 15794 N0.getValueType(), 15795 SCC.getOperand(0), SCC.getOperand(1), 15796 SCC.getOperand(4)); 15797 AddToWorklist(SETCC.getNode()); 15798 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 15799 SCC.getOperand(2), SCC.getOperand(3)); 15800 } 15801 15802 return SCC; 15803 } 15804 return SDValue(); 15805 } 15806 15807 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 15808 /// being selected between, see if we can simplify the select. Callers of this 15809 /// should assume that TheSelect is deleted if this returns true. As such, they 15810 /// should return the appropriate thing (e.g. the node) back to the top-level of 15811 /// the DAG combiner loop to avoid it being looked at. 15812 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 15813 SDValue RHS) { 15814 15815 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15816 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 15817 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 15818 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 15819 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 15820 SDValue Sqrt = RHS; 15821 ISD::CondCode CC; 15822 SDValue CmpLHS; 15823 const ConstantFPSDNode *Zero = nullptr; 15824 15825 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 15826 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 15827 CmpLHS = TheSelect->getOperand(0); 15828 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 15829 } else { 15830 // SELECT or VSELECT 15831 SDValue Cmp = TheSelect->getOperand(0); 15832 if (Cmp.getOpcode() == ISD::SETCC) { 15833 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 15834 CmpLHS = Cmp.getOperand(0); 15835 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15836 } 15837 } 15838 if (Zero && Zero->isZero() && 15839 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15840 CC == ISD::SETULT || CC == ISD::SETLT)) { 15841 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15842 CombineTo(TheSelect, Sqrt); 15843 return true; 15844 } 15845 } 15846 } 15847 // Cannot simplify select with vector condition 15848 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15849 15850 // If this is a select from two identical things, try to pull the operation 15851 // through the select. 15852 if (LHS.getOpcode() != RHS.getOpcode() || 15853 !LHS.hasOneUse() || !RHS.hasOneUse()) 15854 return false; 15855 15856 // If this is a load and the token chain is identical, replace the select 15857 // of two loads with a load through a select of the address to load from. 15858 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15859 // constants have been dropped into the constant pool. 15860 if (LHS.getOpcode() == ISD::LOAD) { 15861 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15862 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15863 15864 // Token chains must be identical. 15865 if (LHS.getOperand(0) != RHS.getOperand(0) || 15866 // Do not let this transformation reduce the number of volatile loads. 15867 LLD->isVolatile() || RLD->isVolatile() || 15868 // FIXME: If either is a pre/post inc/dec load, 15869 // we'd need to split out the address adjustment. 15870 LLD->isIndexed() || RLD->isIndexed() || 15871 // If this is an EXTLOAD, the VT's must match. 15872 LLD->getMemoryVT() != RLD->getMemoryVT() || 15873 // If this is an EXTLOAD, the kind of extension must match. 15874 (LLD->getExtensionType() != RLD->getExtensionType() && 15875 // The only exception is if one of the extensions is anyext. 15876 LLD->getExtensionType() != ISD::EXTLOAD && 15877 RLD->getExtensionType() != ISD::EXTLOAD) || 15878 // FIXME: this discards src value information. This is 15879 // over-conservative. It would be beneficial to be able to remember 15880 // both potential memory locations. Since we are discarding 15881 // src value info, don't do the transformation if the memory 15882 // locations are not in the default address space. 15883 LLD->getPointerInfo().getAddrSpace() != 0 || 15884 RLD->getPointerInfo().getAddrSpace() != 0 || 15885 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15886 LLD->getBasePtr().getValueType())) 15887 return false; 15888 15889 // Check that the select condition doesn't reach either load. If so, 15890 // folding this will induce a cycle into the DAG. If not, this is safe to 15891 // xform, so create a select of the addresses. 15892 SDValue Addr; 15893 if (TheSelect->getOpcode() == ISD::SELECT) { 15894 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15895 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15896 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15897 return false; 15898 // The loads must not depend on one another. 15899 if (LLD->isPredecessorOf(RLD) || 15900 RLD->isPredecessorOf(LLD)) 15901 return false; 15902 Addr = DAG.getSelect(SDLoc(TheSelect), 15903 LLD->getBasePtr().getValueType(), 15904 TheSelect->getOperand(0), LLD->getBasePtr(), 15905 RLD->getBasePtr()); 15906 } else { // Otherwise SELECT_CC 15907 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15908 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15909 15910 if ((LLD->hasAnyUseOfValue(1) && 15911 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15912 (RLD->hasAnyUseOfValue(1) && 15913 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15914 return false; 15915 15916 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15917 LLD->getBasePtr().getValueType(), 15918 TheSelect->getOperand(0), 15919 TheSelect->getOperand(1), 15920 LLD->getBasePtr(), RLD->getBasePtr(), 15921 TheSelect->getOperand(4)); 15922 } 15923 15924 SDValue Load; 15925 // It is safe to replace the two loads if they have different alignments, 15926 // but the new load must be the minimum (most restrictive) alignment of the 15927 // inputs. 15928 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15929 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15930 if (!RLD->isInvariant()) 15931 MMOFlags &= ~MachineMemOperand::MOInvariant; 15932 if (!RLD->isDereferenceable()) 15933 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15934 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15935 // FIXME: Discards pointer and AA info. 15936 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15937 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15938 MMOFlags); 15939 } else { 15940 // FIXME: Discards pointer and AA info. 15941 Load = DAG.getExtLoad( 15942 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15943 : LLD->getExtensionType(), 15944 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15945 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15946 } 15947 15948 // Users of the select now use the result of the load. 15949 CombineTo(TheSelect, Load); 15950 15951 // Users of the old loads now use the new load's chain. We know the 15952 // old-load value is dead now. 15953 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15954 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15955 return true; 15956 } 15957 15958 return false; 15959 } 15960 15961 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15962 /// bitwise 'and'. 15963 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15964 SDValue N1, SDValue N2, SDValue N3, 15965 ISD::CondCode CC) { 15966 // If this is a select where the false operand is zero and the compare is a 15967 // check of the sign bit, see if we can perform the "gzip trick": 15968 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15969 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15970 EVT XType = N0.getValueType(); 15971 EVT AType = N2.getValueType(); 15972 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15973 return SDValue(); 15974 15975 // If the comparison is testing for a positive value, we have to invert 15976 // the sign bit mask, so only do that transform if the target has a bitwise 15977 // 'and not' instruction (the invert is free). 15978 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15979 // (X > -1) ? A : 0 15980 // (X > 0) ? X : 0 <-- This is canonical signed max. 15981 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15982 return SDValue(); 15983 } else if (CC == ISD::SETLT) { 15984 // (X < 0) ? A : 0 15985 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15986 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15987 return SDValue(); 15988 } else { 15989 return SDValue(); 15990 } 15991 15992 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15993 // constant. 15994 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15995 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15996 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15997 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15998 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15999 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 16000 AddToWorklist(Shift.getNode()); 16001 16002 if (XType.bitsGT(AType)) { 16003 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16004 AddToWorklist(Shift.getNode()); 16005 } 16006 16007 if (CC == ISD::SETGT) 16008 Shift = DAG.getNOT(DL, Shift, AType); 16009 16010 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16011 } 16012 16013 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 16014 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 16015 AddToWorklist(Shift.getNode()); 16016 16017 if (XType.bitsGT(AType)) { 16018 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 16019 AddToWorklist(Shift.getNode()); 16020 } 16021 16022 if (CC == ISD::SETGT) 16023 Shift = DAG.getNOT(DL, Shift, AType); 16024 16025 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 16026 } 16027 16028 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 16029 /// where 'cond' is the comparison specified by CC. 16030 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 16031 SDValue N2, SDValue N3, ISD::CondCode CC, 16032 bool NotExtCompare) { 16033 // (x ? y : y) -> y. 16034 if (N2 == N3) return N2; 16035 16036 EVT VT = N2.getValueType(); 16037 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 16038 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 16039 16040 // Determine if the condition we're dealing with is constant 16041 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 16042 N0, N1, CC, DL, false); 16043 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 16044 16045 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 16046 // fold select_cc true, x, y -> x 16047 // fold select_cc false, x, y -> y 16048 return !SCCC->isNullValue() ? N2 : N3; 16049 } 16050 16051 // Check to see if we can simplify the select into an fabs node 16052 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 16053 // Allow either -0.0 or 0.0 16054 if (CFP->isZero()) { 16055 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 16056 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 16057 N0 == N2 && N3.getOpcode() == ISD::FNEG && 16058 N2 == N3.getOperand(0)) 16059 return DAG.getNode(ISD::FABS, DL, VT, N0); 16060 16061 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 16062 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 16063 N0 == N3 && N2.getOpcode() == ISD::FNEG && 16064 N2.getOperand(0) == N3) 16065 return DAG.getNode(ISD::FABS, DL, VT, N3); 16066 } 16067 } 16068 16069 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 16070 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 16071 // in it. This is a win when the constant is not otherwise available because 16072 // it replaces two constant pool loads with one. We only do this if the FP 16073 // type is known to be legal, because if it isn't, then we are before legalize 16074 // types an we want the other legalization to happen first (e.g. to avoid 16075 // messing with soft float) and if the ConstantFP is not legal, because if 16076 // it is legal, we may not need to store the FP constant in a constant pool. 16077 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 16078 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 16079 if (TLI.isTypeLegal(N2.getValueType()) && 16080 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 16081 TargetLowering::Legal && 16082 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 16083 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 16084 // If both constants have multiple uses, then we won't need to do an 16085 // extra load, they are likely around in registers for other users. 16086 (TV->hasOneUse() || FV->hasOneUse())) { 16087 Constant *Elts[] = { 16088 const_cast<ConstantFP*>(FV->getConstantFPValue()), 16089 const_cast<ConstantFP*>(TV->getConstantFPValue()) 16090 }; 16091 Type *FPTy = Elts[0]->getType(); 16092 const DataLayout &TD = DAG.getDataLayout(); 16093 16094 // Create a ConstantArray of the two constants. 16095 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 16096 SDValue CPIdx = 16097 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 16098 TD.getPrefTypeAlignment(FPTy)); 16099 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 16100 16101 // Get the offsets to the 0 and 1 element of the array so that we can 16102 // select between them. 16103 SDValue Zero = DAG.getIntPtrConstant(0, DL); 16104 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 16105 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 16106 16107 SDValue Cond = DAG.getSetCC(DL, 16108 getSetCCResultType(N0.getValueType()), 16109 N0, N1, CC); 16110 AddToWorklist(Cond.getNode()); 16111 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 16112 Cond, One, Zero); 16113 AddToWorklist(CstOffset.getNode()); 16114 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 16115 CstOffset); 16116 AddToWorklist(CPIdx.getNode()); 16117 return DAG.getLoad( 16118 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 16119 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 16120 Alignment); 16121 } 16122 } 16123 16124 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 16125 return V; 16126 16127 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 16128 // where y is has a single bit set. 16129 // A plaintext description would be, we can turn the SELECT_CC into an AND 16130 // when the condition can be materialized as an all-ones register. Any 16131 // single bit-test can be materialized as an all-ones register with 16132 // shift-left and shift-right-arith. 16133 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 16134 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 16135 SDValue AndLHS = N0->getOperand(0); 16136 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 16137 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 16138 // Shift the tested bit over the sign bit. 16139 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 16140 SDValue ShlAmt = 16141 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 16142 getShiftAmountTy(AndLHS.getValueType())); 16143 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 16144 16145 // Now arithmetic right shift it all the way over, so the result is either 16146 // all-ones, or zero. 16147 SDValue ShrAmt = 16148 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 16149 getShiftAmountTy(Shl.getValueType())); 16150 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 16151 16152 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 16153 } 16154 } 16155 16156 // fold select C, 16, 0 -> shl C, 4 16157 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 16158 TLI.getBooleanContents(N0.getValueType()) == 16159 TargetLowering::ZeroOrOneBooleanContent) { 16160 16161 // If the caller doesn't want us to simplify this into a zext of a compare, 16162 // don't do it. 16163 if (NotExtCompare && N2C->isOne()) 16164 return SDValue(); 16165 16166 // Get a SetCC of the condition 16167 // NOTE: Don't create a SETCC if it's not legal on this target. 16168 if (!LegalOperations || 16169 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 16170 SDValue Temp, SCC; 16171 // cast from setcc result type to select result type 16172 if (LegalTypes) { 16173 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 16174 N0, N1, CC); 16175 if (N2.getValueType().bitsLT(SCC.getValueType())) 16176 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 16177 N2.getValueType()); 16178 else 16179 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16180 N2.getValueType(), SCC); 16181 } else { 16182 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 16183 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 16184 N2.getValueType(), SCC); 16185 } 16186 16187 AddToWorklist(SCC.getNode()); 16188 AddToWorklist(Temp.getNode()); 16189 16190 if (N2C->isOne()) 16191 return Temp; 16192 16193 // shl setcc result by log2 n2c 16194 return DAG.getNode( 16195 ISD::SHL, DL, N2.getValueType(), Temp, 16196 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 16197 getShiftAmountTy(Temp.getValueType()))); 16198 } 16199 } 16200 16201 // Check to see if this is an integer abs. 16202 // select_cc setg[te] X, 0, X, -X -> 16203 // select_cc setgt X, -1, X, -X -> 16204 // select_cc setl[te] X, 0, -X, X -> 16205 // select_cc setlt X, 1, -X, X -> 16206 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 16207 if (N1C) { 16208 ConstantSDNode *SubC = nullptr; 16209 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 16210 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 16211 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 16212 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 16213 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 16214 (N1C->isOne() && CC == ISD::SETLT)) && 16215 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 16216 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 16217 16218 EVT XType = N0.getValueType(); 16219 if (SubC && SubC->isNullValue() && XType.isInteger()) { 16220 SDLoc DL(N0); 16221 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 16222 N0, 16223 DAG.getConstant(XType.getSizeInBits() - 1, DL, 16224 getShiftAmountTy(N0.getValueType()))); 16225 SDValue Add = DAG.getNode(ISD::ADD, DL, 16226 XType, N0, Shift); 16227 AddToWorklist(Shift.getNode()); 16228 AddToWorklist(Add.getNode()); 16229 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 16230 } 16231 } 16232 16233 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 16234 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 16235 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 16236 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 16237 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 16238 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 16239 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 16240 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 16241 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 16242 SDValue ValueOnZero = N2; 16243 SDValue Count = N3; 16244 // If the condition is NE instead of E, swap the operands. 16245 if (CC == ISD::SETNE) 16246 std::swap(ValueOnZero, Count); 16247 // Check if the value on zero is a constant equal to the bits in the type. 16248 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 16249 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 16250 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 16251 // legal, combine to just cttz. 16252 if ((Count.getOpcode() == ISD::CTTZ || 16253 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 16254 N0 == Count.getOperand(0) && 16255 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 16256 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 16257 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 16258 // legal, combine to just ctlz. 16259 if ((Count.getOpcode() == ISD::CTLZ || 16260 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 16261 N0 == Count.getOperand(0) && 16262 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 16263 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 16264 } 16265 } 16266 } 16267 16268 return SDValue(); 16269 } 16270 16271 /// This is a stub for TargetLowering::SimplifySetCC. 16272 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 16273 ISD::CondCode Cond, const SDLoc &DL, 16274 bool foldBooleans) { 16275 TargetLowering::DAGCombinerInfo 16276 DagCombineInfo(DAG, Level, false, this); 16277 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 16278 } 16279 16280 /// Given an ISD::SDIV node expressing a divide by constant, return 16281 /// a DAG expression to select that will generate the same value by multiplying 16282 /// by a magic number. 16283 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16284 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 16285 // when optimising for minimum size, we don't want to expand a div to a mul 16286 // and a shift. 16287 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16288 return SDValue(); 16289 16290 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16291 if (!C) 16292 return SDValue(); 16293 16294 // Avoid division by zero. 16295 if (C->isNullValue()) 16296 return SDValue(); 16297 16298 std::vector<SDNode*> Built; 16299 SDValue S = 16300 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16301 16302 for (SDNode *N : Built) 16303 AddToWorklist(N); 16304 return S; 16305 } 16306 16307 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 16308 /// DAG expression that will generate the same value by right shifting. 16309 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 16310 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16311 if (!C) 16312 return SDValue(); 16313 16314 // Avoid division by zero. 16315 if (C->isNullValue()) 16316 return SDValue(); 16317 16318 std::vector<SDNode *> Built; 16319 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 16320 16321 for (SDNode *N : Built) 16322 AddToWorklist(N); 16323 return S; 16324 } 16325 16326 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 16327 /// expression that will generate the same value by multiplying by a magic 16328 /// number. 16329 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16330 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 16331 // when optimising for minimum size, we don't want to expand a div to a mul 16332 // and a shift. 16333 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16334 return SDValue(); 16335 16336 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16337 if (!C) 16338 return SDValue(); 16339 16340 // Avoid division by zero. 16341 if (C->isNullValue()) 16342 return SDValue(); 16343 16344 std::vector<SDNode*> Built; 16345 SDValue S = 16346 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16347 16348 for (SDNode *N : Built) 16349 AddToWorklist(N); 16350 return S; 16351 } 16352 16353 /// Determines the LogBase2 value for a non-null input value using the 16354 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 16355 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 16356 EVT VT = V.getValueType(); 16357 unsigned EltBits = VT.getScalarSizeInBits(); 16358 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 16359 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 16360 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 16361 return LogBase2; 16362 } 16363 16364 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16365 /// For the reciprocal, we need to find the zero of the function: 16366 /// F(X) = A X - 1 [which has a zero at X = 1/A] 16367 /// => 16368 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 16369 /// does not require additional intermediate precision] 16370 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 16371 if (Level >= AfterLegalizeDAG) 16372 return SDValue(); 16373 16374 // TODO: Handle half and/or extended types? 16375 EVT VT = Op.getValueType(); 16376 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16377 return SDValue(); 16378 16379 // If estimates are explicitly disabled for this function, we're done. 16380 MachineFunction &MF = DAG.getMachineFunction(); 16381 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 16382 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16383 return SDValue(); 16384 16385 // Estimates may be explicitly enabled for this type with a custom number of 16386 // refinement steps. 16387 int Iterations = TLI.getDivRefinementSteps(VT, MF); 16388 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 16389 AddToWorklist(Est.getNode()); 16390 16391 if (Iterations) { 16392 EVT VT = Op.getValueType(); 16393 SDLoc DL(Op); 16394 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 16395 16396 // Newton iterations: Est = Est + Est (1 - Arg * Est) 16397 for (int i = 0; i < Iterations; ++i) { 16398 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 16399 AddToWorklist(NewEst.getNode()); 16400 16401 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 16402 AddToWorklist(NewEst.getNode()); 16403 16404 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16405 AddToWorklist(NewEst.getNode()); 16406 16407 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 16408 AddToWorklist(Est.getNode()); 16409 } 16410 } 16411 return Est; 16412 } 16413 16414 return SDValue(); 16415 } 16416 16417 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16418 /// For the reciprocal sqrt, we need to find the zero of the function: 16419 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16420 /// => 16421 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 16422 /// As a result, we precompute A/2 prior to the iteration loop. 16423 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 16424 unsigned Iterations, 16425 SDNodeFlags Flags, bool Reciprocal) { 16426 EVT VT = Arg.getValueType(); 16427 SDLoc DL(Arg); 16428 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 16429 16430 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 16431 // this entire sequence requires only one FP constant. 16432 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 16433 AddToWorklist(HalfArg.getNode()); 16434 16435 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 16436 AddToWorklist(HalfArg.getNode()); 16437 16438 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 16439 for (unsigned i = 0; i < Iterations; ++i) { 16440 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 16441 AddToWorklist(NewEst.getNode()); 16442 16443 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 16444 AddToWorklist(NewEst.getNode()); 16445 16446 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 16447 AddToWorklist(NewEst.getNode()); 16448 16449 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16450 AddToWorklist(Est.getNode()); 16451 } 16452 16453 // If non-reciprocal square root is requested, multiply the result by Arg. 16454 if (!Reciprocal) { 16455 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 16456 AddToWorklist(Est.getNode()); 16457 } 16458 16459 return Est; 16460 } 16461 16462 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16463 /// For the reciprocal sqrt, we need to find the zero of the function: 16464 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16465 /// => 16466 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 16467 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 16468 unsigned Iterations, 16469 SDNodeFlags Flags, bool Reciprocal) { 16470 EVT VT = Arg.getValueType(); 16471 SDLoc DL(Arg); 16472 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 16473 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 16474 16475 // This routine must enter the loop below to work correctly 16476 // when (Reciprocal == false). 16477 assert(Iterations > 0); 16478 16479 // Newton iterations for reciprocal square root: 16480 // E = (E * -0.5) * ((A * E) * E + -3.0) 16481 for (unsigned i = 0; i < Iterations; ++i) { 16482 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 16483 AddToWorklist(AE.getNode()); 16484 16485 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 16486 AddToWorklist(AEE.getNode()); 16487 16488 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 16489 AddToWorklist(RHS.getNode()); 16490 16491 // When calculating a square root at the last iteration build: 16492 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 16493 // (notice a common subexpression) 16494 SDValue LHS; 16495 if (Reciprocal || (i + 1) < Iterations) { 16496 // RSQRT: LHS = (E * -0.5) 16497 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 16498 } else { 16499 // SQRT: LHS = (A * E) * -0.5 16500 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 16501 } 16502 AddToWorklist(LHS.getNode()); 16503 16504 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 16505 AddToWorklist(Est.getNode()); 16506 } 16507 16508 return Est; 16509 } 16510 16511 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 16512 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 16513 /// Op can be zero. 16514 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 16515 bool Reciprocal) { 16516 if (Level >= AfterLegalizeDAG) 16517 return SDValue(); 16518 16519 // TODO: Handle half and/or extended types? 16520 EVT VT = Op.getValueType(); 16521 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16522 return SDValue(); 16523 16524 // If estimates are explicitly disabled for this function, we're done. 16525 MachineFunction &MF = DAG.getMachineFunction(); 16526 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 16527 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16528 return SDValue(); 16529 16530 // Estimates may be explicitly enabled for this type with a custom number of 16531 // refinement steps. 16532 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 16533 16534 bool UseOneConstNR = false; 16535 if (SDValue Est = 16536 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 16537 Reciprocal)) { 16538 AddToWorklist(Est.getNode()); 16539 16540 if (Iterations) { 16541 Est = UseOneConstNR 16542 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 16543 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 16544 16545 if (!Reciprocal) { 16546 // Unfortunately, Est is now NaN if the input was exactly 0.0. 16547 // Select out this case and force the answer to 0.0. 16548 EVT VT = Op.getValueType(); 16549 SDLoc DL(Op); 16550 16551 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 16552 EVT CCVT = getSetCCResultType(VT); 16553 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 16554 AddToWorklist(ZeroCmp.getNode()); 16555 16556 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 16557 ZeroCmp, FPZero, Est); 16558 AddToWorklist(Est.getNode()); 16559 } 16560 } 16561 return Est; 16562 } 16563 16564 return SDValue(); 16565 } 16566 16567 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16568 return buildSqrtEstimateImpl(Op, Flags, true); 16569 } 16570 16571 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16572 return buildSqrtEstimateImpl(Op, Flags, false); 16573 } 16574 16575 /// Return true if base is a frame index, which is known not to alias with 16576 /// anything but itself. Provides base object and offset as results. 16577 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 16578 const GlobalValue *&GV, const void *&CV) { 16579 // Assume it is a primitive operation. 16580 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 16581 16582 // If it's an adding a simple constant then integrate the offset. 16583 if (Base.getOpcode() == ISD::ADD) { 16584 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 16585 Base = Base.getOperand(0); 16586 Offset += C->getSExtValue(); 16587 } 16588 } 16589 16590 // Return the underlying GlobalValue, and update the Offset. Return false 16591 // for GlobalAddressSDNode since the same GlobalAddress may be represented 16592 // by multiple nodes with different offsets. 16593 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 16594 GV = G->getGlobal(); 16595 Offset += G->getOffset(); 16596 return false; 16597 } 16598 16599 // Return the underlying Constant value, and update the Offset. Return false 16600 // for ConstantSDNodes since the same constant pool entry may be represented 16601 // by multiple nodes with different offsets. 16602 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 16603 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 16604 : (const void *)C->getConstVal(); 16605 Offset += C->getOffset(); 16606 return false; 16607 } 16608 // If it's any of the following then it can't alias with anything but itself. 16609 return isa<FrameIndexSDNode>(Base); 16610 } 16611 16612 /// Return true if there is any possibility that the two addresses overlap. 16613 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 16614 // If they are the same then they must be aliases. 16615 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 16616 16617 // If they are both volatile then they cannot be reordered. 16618 if (Op0->isVolatile() && Op1->isVolatile()) return true; 16619 16620 // If one operation reads from invariant memory, and the other may store, they 16621 // cannot alias. These should really be checking the equivalent of mayWrite, 16622 // but it only matters for memory nodes other than load /store. 16623 if (Op0->isInvariant() && Op1->writeMem()) 16624 return false; 16625 16626 if (Op1->isInvariant() && Op0->writeMem()) 16627 return false; 16628 16629 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3; 16630 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3; 16631 16632 // Check for BaseIndexOffset matching. 16633 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 16634 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 16635 if (BasePtr0.equalBaseIndex(BasePtr1)) 16636 return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) || 16637 (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset)); 16638 16639 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis 16640 // modified to use BaseIndexOffset. 16641 16642 // Gather base node and offset information. 16643 SDValue Base0, Base1; 16644 int64_t Offset0, Offset1; 16645 const GlobalValue *GV0, *GV1; 16646 const void *CV0, *CV1; 16647 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(), 16648 Base0, Offset0, GV0, CV0); 16649 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(), 16650 Base1, Offset1, GV1, CV1); 16651 16652 // If they have the same base address, then check to see if they overlap. 16653 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1))) 16654 return !((Offset0 + NumBytes0) <= Offset1 || 16655 (Offset1 + NumBytes1) <= Offset0); 16656 16657 // It is possible for different frame indices to alias each other, mostly 16658 // when tail call optimization reuses return address slots for arguments. 16659 // To catch this case, look up the actual index of frame indices to compute 16660 // the real alias relationship. 16661 if (IsFrameIndex0 && IsFrameIndex1) { 16662 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 16663 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex()); 16664 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 16665 return !((Offset0 + NumBytes0) <= Offset1 || 16666 (Offset1 + NumBytes1) <= Offset0); 16667 } 16668 16669 // Otherwise, if we know what the bases are, and they aren't identical, then 16670 // we know they cannot alias. 16671 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1)) 16672 return false; 16673 16674 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 16675 // compared to the size and offset of the access, we may be able to prove they 16676 // do not alias. This check is conservative for now to catch cases created by 16677 // splitting vector types. 16678 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 16679 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 16680 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 16681 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 16682 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 16683 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 16684 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 16685 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 16686 16687 // There is no overlap between these relatively aligned accesses of similar 16688 // size. Return no alias. 16689 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 16690 (OffAlign1 + NumBytes1) <= OffAlign0) 16691 return false; 16692 } 16693 16694 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 16695 ? CombinerGlobalAA 16696 : DAG.getSubtarget().useAA(); 16697 #ifndef NDEBUG 16698 if (CombinerAAOnlyFunc.getNumOccurrences() && 16699 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 16700 UseAA = false; 16701 #endif 16702 16703 if (UseAA && AA && 16704 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 16705 // Use alias analysis information. 16706 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 16707 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 16708 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 16709 AliasResult AAResult = 16710 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 16711 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 16712 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 16713 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 16714 if (AAResult == NoAlias) 16715 return false; 16716 } 16717 16718 // Otherwise we have to assume they alias. 16719 return true; 16720 } 16721 16722 /// Walk up chain skipping non-aliasing memory nodes, 16723 /// looking for aliasing nodes and adding them to the Aliases vector. 16724 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 16725 SmallVectorImpl<SDValue> &Aliases) { 16726 SmallVector<SDValue, 8> Chains; // List of chains to visit. 16727 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 16728 16729 // Get alias information for node. 16730 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 16731 16732 // Starting off. 16733 Chains.push_back(OriginalChain); 16734 unsigned Depth = 0; 16735 16736 // Look at each chain and determine if it is an alias. If so, add it to the 16737 // aliases list. If not, then continue up the chain looking for the next 16738 // candidate. 16739 while (!Chains.empty()) { 16740 SDValue Chain = Chains.pop_back_val(); 16741 16742 // For TokenFactor nodes, look at each operand and only continue up the 16743 // chain until we reach the depth limit. 16744 // 16745 // FIXME: The depth check could be made to return the last non-aliasing 16746 // chain we found before we hit a tokenfactor rather than the original 16747 // chain. 16748 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16749 Aliases.clear(); 16750 Aliases.push_back(OriginalChain); 16751 return; 16752 } 16753 16754 // Don't bother if we've been before. 16755 if (!Visited.insert(Chain.getNode()).second) 16756 continue; 16757 16758 switch (Chain.getOpcode()) { 16759 case ISD::EntryToken: 16760 // Entry token is ideal chain operand, but handled in FindBetterChain. 16761 break; 16762 16763 case ISD::LOAD: 16764 case ISD::STORE: { 16765 // Get alias information for Chain. 16766 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16767 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16768 16769 // If chain is alias then stop here. 16770 if (!(IsLoad && IsOpLoad) && 16771 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 16772 Aliases.push_back(Chain); 16773 } else { 16774 // Look further up the chain. 16775 Chains.push_back(Chain.getOperand(0)); 16776 ++Depth; 16777 } 16778 break; 16779 } 16780 16781 case ISD::TokenFactor: 16782 // We have to check each of the operands of the token factor for "small" 16783 // token factors, so we queue them up. Adding the operands to the queue 16784 // (stack) in reverse order maintains the original order and increases the 16785 // likelihood that getNode will find a matching token factor (CSE.) 16786 if (Chain.getNumOperands() > 16) { 16787 Aliases.push_back(Chain); 16788 break; 16789 } 16790 for (unsigned n = Chain.getNumOperands(); n;) 16791 Chains.push_back(Chain.getOperand(--n)); 16792 ++Depth; 16793 break; 16794 16795 case ISD::CopyFromReg: 16796 // Forward past CopyFromReg. 16797 Chains.push_back(Chain.getOperand(0)); 16798 ++Depth; 16799 break; 16800 16801 default: 16802 // For all other instructions we will just have to take what we can get. 16803 Aliases.push_back(Chain); 16804 break; 16805 } 16806 } 16807 } 16808 16809 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 16810 /// (aliasing node.) 16811 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 16812 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 16813 16814 // Accumulate all the aliases to this node. 16815 GatherAllAliases(N, OldChain, Aliases); 16816 16817 // If no operands then chain to entry token. 16818 if (Aliases.size() == 0) 16819 return DAG.getEntryNode(); 16820 16821 // If a single operand then chain to it. We don't need to revisit it. 16822 if (Aliases.size() == 1) 16823 return Aliases[0]; 16824 16825 // Construct a custom tailored token factor. 16826 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 16827 } 16828 16829 // This function tries to collect a bunch of potentially interesting 16830 // nodes to improve the chains of, all at once. This might seem 16831 // redundant, as this function gets called when visiting every store 16832 // node, so why not let the work be done on each store as it's visited? 16833 // 16834 // I believe this is mainly important because MergeConsecutiveStores 16835 // is unable to deal with merging stores of different sizes, so unless 16836 // we improve the chains of all the potential candidates up-front 16837 // before running MergeConsecutiveStores, it might only see some of 16838 // the nodes that will eventually be candidates, and then not be able 16839 // to go from a partially-merged state to the desired final 16840 // fully-merged state. 16841 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 16842 // This holds the base pointer, index, and the offset in bytes from the base 16843 // pointer. 16844 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 16845 16846 // We must have a base and an offset. 16847 if (!BasePtr.Base.getNode()) 16848 return false; 16849 16850 // Do not handle stores to undef base pointers. 16851 if (BasePtr.Base.isUndef()) 16852 return false; 16853 16854 SmallVector<StoreSDNode *, 8> ChainedStores; 16855 ChainedStores.push_back(St); 16856 16857 // Walk up the chain and look for nodes with offsets from the same 16858 // base pointer. Stop when reaching an instruction with a different kind 16859 // or instruction which has a different base pointer. 16860 StoreSDNode *Index = St; 16861 while (Index) { 16862 // If the chain has more than one use, then we can't reorder the mem ops. 16863 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 16864 break; 16865 16866 if (Index->isVolatile() || Index->isIndexed()) 16867 break; 16868 16869 // Find the base pointer and offset for this memory node. 16870 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16871 16872 // Check that the base pointer is the same as the original one. 16873 if (!Ptr.equalBaseIndex(BasePtr)) 16874 break; 16875 16876 // Walk up the chain to find the next store node, ignoring any 16877 // intermediate loads. Any other kind of node will halt the loop. 16878 SDNode *NextInChain = Index->getChain().getNode(); 16879 while (true) { 16880 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16881 // We found a store node. Use it for the next iteration. 16882 if (STn->isVolatile() || STn->isIndexed()) { 16883 Index = nullptr; 16884 break; 16885 } 16886 ChainedStores.push_back(STn); 16887 Index = STn; 16888 break; 16889 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16890 NextInChain = Ldn->getChain().getNode(); 16891 continue; 16892 } else { 16893 Index = nullptr; 16894 break; 16895 } 16896 } // end while 16897 } 16898 16899 // At this point, ChainedStores lists all of the Store nodes 16900 // reachable by iterating up through chain nodes matching the above 16901 // conditions. For each such store identified, try to find an 16902 // earlier chain to attach the store to which won't violate the 16903 // required ordering. 16904 bool MadeChangeToSt = false; 16905 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16906 16907 for (StoreSDNode *ChainedStore : ChainedStores) { 16908 SDValue Chain = ChainedStore->getChain(); 16909 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16910 16911 if (Chain != BetterChain) { 16912 if (ChainedStore == St) 16913 MadeChangeToSt = true; 16914 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16915 } 16916 } 16917 16918 // Do all replacements after finding the replacements to make to avoid making 16919 // the chains more complicated by introducing new TokenFactors. 16920 for (auto Replacement : BetterChains) 16921 replaceStoreChain(Replacement.first, Replacement.second); 16922 16923 return MadeChangeToSt; 16924 } 16925 16926 /// This is the entry point for the file. 16927 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 16928 CodeGenOpt::Level OptLevel) { 16929 /// This is the main entry point to this class. 16930 DAGCombiner(*this, AA, OptLevel).Run(Level); 16931 } 16932